@djangocfg/api 2.1.448 → 2.1.450

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 (55) hide show
  1. package/dist/auth-server.cjs +1 -2272
  2. package/dist/auth-server.cjs.map +1 -1
  3. package/dist/auth-server.d.cts +1 -35
  4. package/dist/auth-server.d.ts +1 -35
  5. package/dist/auth-server.mjs +1 -2272
  6. package/dist/auth-server.mjs.map +1 -1
  7. package/dist/auth.cjs +285 -146
  8. package/dist/auth.cjs.map +1 -1
  9. package/dist/auth.d.cts +137 -2
  10. package/dist/auth.d.ts +137 -2
  11. package/dist/auth.mjs +294 -155
  12. package/dist/auth.mjs.map +1 -1
  13. package/dist/clients.cjs +35 -0
  14. package/dist/clients.cjs.map +1 -1
  15. package/dist/clients.d.cts +147 -2
  16. package/dist/clients.d.ts +147 -2
  17. package/dist/clients.mjs +35 -0
  18. package/dist/clients.mjs.map +1 -1
  19. package/dist/hooks.cjs +11 -0
  20. package/dist/hooks.cjs.map +1 -1
  21. package/dist/hooks.mjs +11 -0
  22. package/dist/hooks.mjs.map +1 -1
  23. package/dist/index.cjs +35 -0
  24. package/dist/index.cjs.map +1 -1
  25. package/dist/index.d.cts +169 -6
  26. package/dist/index.d.ts +169 -6
  27. package/dist/index.mjs +35 -0
  28. package/dist/index.mjs.map +1 -1
  29. package/package.json +7 -4
  30. package/src/_api/generated/_cfg_accounts/api.ts +8 -0
  31. package/src/_api/generated/_cfg_accounts/openapi.json +84 -5
  32. package/src/_api/generated/_cfg_accounts/schemas/OAuthTokenResponse.ts +2 -2
  33. package/src/_api/generated/_cfg_accounts/schemas/OTPRequestResponse.ts +2 -0
  34. package/src/_api/generated/_cfg_accounts/schemas/WebmailLink.ts +15 -0
  35. package/src/_api/generated/_cfg_accounts/schemas/WebmailLinkProviderEnum.ts +9 -0
  36. package/src/_api/generated/_cfg_accounts/schemas/index.ts +2 -0
  37. package/src/_api/generated/_cfg_centrifugo/api.ts +8 -0
  38. package/src/_api/generated/_cfg_totp/api.ts +8 -0
  39. package/src/_api/generated/helpers/auth.ts +12 -0
  40. package/src/_api/generated/openapi.json +84 -5
  41. package/src/_api/generated/types.gen.ts +131 -2
  42. package/src/auth/__tests__/jwt.test.ts +119 -0
  43. package/src/auth/__tests__/onUnauthorized.test.ts +206 -0
  44. package/src/auth/__tests__/refreshRotation.test.ts +119 -0
  45. package/src/auth/__tests__/sessionBootstrap.test.ts +76 -0
  46. package/src/auth/context/AuthContext.tsx +131 -14
  47. package/src/auth/hooks/useAuthForm.ts +5 -2
  48. package/src/auth/hooks/useAuthFormState.ts +4 -1
  49. package/src/auth/hooks/useTokenRefresh.ts +28 -62
  50. package/src/auth/middlewares/index.ts +7 -7
  51. package/src/auth/refreshHandler.ts +79 -0
  52. package/src/auth/types/form.ts +10 -0
  53. package/src/auth/types/index.ts +1 -0
  54. package/src/auth/utils/jwt.ts +66 -0
  55. package/src/auth/middlewares/tokenRefresh.ts +0 -161
@@ -20,2279 +20,8 @@ __name(proxyMiddleware, "proxyMiddleware");
20
20
  var proxyMiddlewareConfig = {
21
21
  matcher: ["/media/:path*", "/api/:path*"]
22
22
  };
23
-
24
- // src/_api/generated/helpers/errors.ts
25
- var APIError = class extends Error {
26
- constructor(statusCode, statusText, response, url, message) {
27
- super(message || `HTTP ${statusCode}: ${statusText}`);
28
- this.statusCode = statusCode;
29
- this.statusText = statusText;
30
- this.response = response;
31
- this.url = url;
32
- this.name = "APIError";
33
- }
34
- static {
35
- __name(this, "APIError");
36
- }
37
- get details() {
38
- if (typeof this.response === "object" && this.response !== null) {
39
- return this.response;
40
- }
41
- return null;
42
- }
43
- get fieldErrors() {
44
- const details = this.details;
45
- if (!details) return null;
46
- const fieldErrors = {};
47
- for (const [key, value] of Object.entries(details)) {
48
- if (Array.isArray(value)) fieldErrors[key] = value;
49
- }
50
- return Object.keys(fieldErrors).length > 0 ? fieldErrors : null;
51
- }
52
- get errorMessage() {
53
- const details = this.details;
54
- if (!details) return this.message;
55
- if (details.detail) {
56
- return Array.isArray(details.detail) ? details.detail.join(", ") : String(details.detail);
57
- }
58
- if (details.error) return String(details.error);
59
- if (details.message) return String(details.message);
60
- const fieldErrors = this.fieldErrors;
61
- if (fieldErrors) {
62
- const firstField = Object.keys(fieldErrors)[0];
63
- if (firstField) return `${firstField}: ${fieldErrors[firstField]?.join(", ")}`;
64
- }
65
- return this.message;
66
- }
67
- get isValidationError() {
68
- return this.statusCode === 400;
69
- }
70
- get isAuthError() {
71
- return this.statusCode === 401;
72
- }
73
- get isPermissionError() {
74
- return this.statusCode === 403;
75
- }
76
- get isNotFoundError() {
77
- return this.statusCode === 404;
78
- }
79
- get isServerError() {
80
- return this.statusCode >= 500 && this.statusCode < 600;
81
- }
82
- };
83
-
84
- // src/_api/generated/helpers/auth.ts
85
- var ACCESS_KEY = "cfg.access_token";
86
- var REFRESH_KEY = "cfg.refresh_token";
87
- var API_KEY_KEY = "cfg.api_key";
88
- var isBrowser = typeof window !== "undefined";
89
- var localStorageBackend = {
90
- get(key) {
91
- if (!isBrowser) return null;
92
- try {
93
- return window.localStorage.getItem(key);
94
- } catch {
95
- return null;
96
- }
97
- },
98
- set(key, value) {
99
- if (!isBrowser) return;
100
- try {
101
- if (value === null) window.localStorage.removeItem(key);
102
- else window.localStorage.setItem(key, value);
103
- } catch {
104
- }
105
- }
106
- };
107
- var COOKIE_MAX_AGE = 60 * 60 * 24 * 30;
108
- var cookieBackend = {
109
- get(key) {
110
- if (!isBrowser) return null;
111
- try {
112
- const re = new RegExp(`(?:^|;\\s*)${encodeURIComponent(key)}=([^;]*)`);
113
- const m = document.cookie.match(re);
114
- return m ? decodeURIComponent(m[1]) : null;
115
- } catch {
116
- return null;
117
- }
118
- },
119
- set(key, value) {
120
- if (!isBrowser) return;
121
- try {
122
- const k = encodeURIComponent(key);
123
- const secure = window.location.protocol === "https:" ? "; Secure" : "";
124
- if (value === null) {
125
- document.cookie = `${k}=; Path=/; Max-Age=0; SameSite=Lax${secure}`;
126
- } else {
127
- const v = encodeURIComponent(value);
128
- document.cookie = `${k}=${v}; Path=/; Max-Age=${COOKIE_MAX_AGE}; SameSite=Lax${secure}`;
129
- }
130
- } catch {
131
- }
132
- }
133
- };
134
- var _storage = localStorageBackend;
135
- var _storageMode = "localStorage";
136
- function detectLocale() {
137
- try {
138
- if (typeof document !== "undefined") {
139
- const m = document.cookie.match(/(?:^|;\s*)NEXT_LOCALE=([^;]*)/);
140
- if (m) return decodeURIComponent(m[1]);
141
- }
142
- if (typeof navigator !== "undefined" && navigator.language) {
143
- return navigator.language;
144
- }
145
- } catch {
146
- }
147
- return null;
148
- }
149
- __name(detectLocale, "detectLocale");
150
- function defaultBaseUrl() {
151
- if (typeof window !== "undefined") {
152
- try {
153
- if (typeof process !== "undefined" && process.env) {
154
- if (process.env.NEXT_PUBLIC_STATIC_BUILD === "true") return "";
155
- if (process.env.NEXT_PUBLIC_API_PROXY_URL !== void 0)
156
- return process.env.NEXT_PUBLIC_API_PROXY_URL;
157
- return process.env.NEXT_PUBLIC_API_URL || "";
158
- }
159
- } catch {
160
- }
161
- return "";
162
- }
163
- try {
164
- if (typeof process !== "undefined" && process.env) {
165
- if (process.env.NEXT_PUBLIC_STATIC_BUILD === "true") return "";
166
- return process.env.NEXT_PUBLIC_API_URL || "";
167
- }
168
- } catch {
169
- }
170
- return "";
171
- }
172
- __name(defaultBaseUrl, "defaultBaseUrl");
173
- function defaultApiKey() {
174
- try {
175
- if (typeof process !== "undefined" && process.env?.NEXT_PUBLIC_API_KEY) {
176
- return process.env.NEXT_PUBLIC_API_KEY;
177
- }
178
- } catch {
179
- }
180
- return null;
181
- }
182
- __name(defaultApiKey, "defaultApiKey");
183
- var _localeOverride = null;
184
- var _apiKeyOverride = null;
185
- var _baseUrlOverride = null;
186
- var _withCredentials = true;
187
- var _onUnauthorized = null;
188
- var _refreshHandler = null;
189
- var _refreshInflight = null;
190
- var RETRY_MARKER = "X-Auth-Retry";
191
- var _client = null;
192
- function pushClientConfig() {
193
- if (!_client) return;
194
- _client.setConfig({
195
- baseUrl: auth.getBaseUrl(),
196
- credentials: _withCredentials ? "include" : "same-origin"
197
- });
198
- }
199
- __name(pushClientConfig, "pushClientConfig");
200
- var auth = {
201
- // ── Storage mode ──────────────────────────────────────────────────
202
- getStorageMode() {
203
- return _storageMode;
204
- },
205
- setStorageMode(mode) {
206
- _storageMode = mode;
207
- _storage = mode === "cookie" ? cookieBackend : localStorageBackend;
208
- },
209
- // ── Bearer token ──────────────────────────────────────────────────
210
- getToken() {
211
- return _storage.get(ACCESS_KEY);
212
- },
213
- setToken(token) {
214
- _storage.set(ACCESS_KEY, token);
215
- },
216
- getRefreshToken() {
217
- return _storage.get(REFRESH_KEY);
218
- },
219
- setRefreshToken(token) {
220
- _storage.set(REFRESH_KEY, token);
221
- },
222
- clearTokens() {
223
- _storage.set(ACCESS_KEY, null);
224
- _storage.set(REFRESH_KEY, null);
225
- },
226
- isAuthenticated() {
227
- return _storage.get(ACCESS_KEY) !== null;
228
- },
229
- // ── API key ───────────────────────────────────────────────────────
230
- getApiKey() {
231
- return _apiKeyOverride ?? _storage.get(API_KEY_KEY) ?? defaultApiKey();
232
- },
233
- setApiKey(key) {
234
- _apiKeyOverride = key;
235
- },
236
- setApiKeyPersist(key) {
237
- _apiKeyOverride = key;
238
- _storage.set(API_KEY_KEY, key);
239
- },
240
- clearApiKey() {
241
- _apiKeyOverride = null;
242
- _storage.set(API_KEY_KEY, null);
243
- },
244
- // ── Locale ────────────────────────────────────────────────────────
245
- getLocale() {
246
- return _localeOverride ?? detectLocale();
247
- },
248
- setLocale(locale) {
249
- _localeOverride = locale;
250
- },
251
- // ── Base URL ──────────────────────────────────────────────────────
252
- getBaseUrl() {
253
- const url = _baseUrlOverride ?? defaultBaseUrl();
254
- return url.replace(/\/$/, "");
255
- },
256
- setBaseUrl(url) {
257
- _baseUrlOverride = url ? url.replace(/\/$/, "") : null;
258
- pushClientConfig();
259
- },
260
- // ── Credentials toggle ────────────────────────────────────────────
261
- getWithCredentials() {
262
- return _withCredentials;
263
- },
264
- setWithCredentials(value) {
265
- _withCredentials = value;
266
- pushClientConfig();
267
- },
268
- // ── 401 handler ───────────────────────────────────────────────────
269
- /**
270
- * Fired when the server returns 401 AND no refresh path recovers it
271
- * (no refresh token, no refresh handler, refresh failed, or retry
272
- * still 401). The app should clear local state and redirect to login.
273
- *
274
- * NOT fired for 401 that gets transparently recovered by the refresh
275
- * handler — those are invisible to callers.
276
- */
277
- onUnauthorized(cb) {
278
- _onUnauthorized = cb;
279
- },
280
- /**
281
- * Register the refresh strategy. The handler receives the current
282
- * refresh token and must call your refresh endpoint, returning
283
- * `{ access, refresh? }` on success or `null` on failure.
284
- *
285
- * @example
286
- * auth.setRefreshHandler(async (refresh) => {
287
- * const { data } = await Auth.tokenRefreshCreate({ body: { refresh } });
288
- * return data ? { access: data.access, refresh: data.refresh } : null;
289
- * });
290
- */
291
- setRefreshHandler(fn) {
292
- _refreshHandler = fn;
293
- }
294
- };
295
- async function tryRefresh() {
296
- if (_refreshInflight) return _refreshInflight;
297
- if (!_refreshHandler) return null;
298
- const refresh = auth.getRefreshToken();
299
- if (!refresh) return null;
300
- _refreshInflight = (async () => {
301
- try {
302
- const result = await _refreshHandler(refresh);
303
- if (!result?.access) return null;
304
- auth.setToken(result.access);
305
- if (result.refresh) auth.setRefreshToken(result.refresh);
306
- return result.access;
307
- } catch {
308
- return null;
309
- } finally {
310
- _refreshInflight = null;
311
- }
312
- })();
313
- return _refreshInflight;
314
- }
315
- __name(tryRefresh, "tryRefresh");
316
- function dpopEnabled() {
317
- try {
318
- return typeof process !== "undefined" && process.env?.NEXT_PUBLIC_DPOP_ENABLED === "true";
319
- } catch {
320
- return false;
321
- }
322
- }
323
- __name(dpopEnabled, "dpopEnabled");
324
- var _DPOP_DB = "cfg-auth";
325
- var _DPOP_STORE = "keys";
326
- var _DPOP_KEY_ID = "dpop-ec-p256";
327
- function _idbOpen() {
328
- return new Promise((resolve, reject) => {
329
- const req = indexedDB.open(_DPOP_DB, 1);
330
- req.onupgradeneeded = () => req.result.createObjectStore(_DPOP_STORE);
331
- req.onsuccess = () => resolve(req.result);
332
- req.onerror = () => reject(req.error);
333
- });
334
- }
335
- __name(_idbOpen, "_idbOpen");
336
- function _idbGet(key) {
337
- return _idbOpen().then((db) => new Promise((resolve, reject) => {
338
- const tx = db.transaction(_DPOP_STORE, "readonly");
339
- const req = tx.objectStore(_DPOP_STORE).get(key);
340
- req.onsuccess = () => resolve(req.result);
341
- req.onerror = () => reject(req.error);
342
- }));
343
- }
344
- __name(_idbGet, "_idbGet");
345
- function _idbPut(key, value) {
346
- return _idbOpen().then((db) => new Promise((resolve, reject) => {
347
- const tx = db.transaction(_DPOP_STORE, "readwrite");
348
- tx.objectStore(_DPOP_STORE).put(value, key);
349
- tx.oncomplete = () => resolve();
350
- tx.onerror = () => reject(tx.error);
351
- }));
352
- }
353
- __name(_idbPut, "_idbPut");
354
- var _dpopKeyPromise = null;
355
- function _getDpopKeyPair() {
356
- if (_dpopKeyPromise) return _dpopKeyPromise;
357
- _dpopKeyPromise = (async () => {
358
- const existing = await _idbGet(_DPOP_KEY_ID).catch(() => void 0);
359
- if (existing) return existing;
360
- const pair = await crypto.subtle.generateKey(
361
- { name: "ECDSA", namedCurve: "P-256" },
362
- false,
363
- // extractable:false — JS can sign but never export the private key
364
- ["sign"]
365
- );
366
- await _idbPut(_DPOP_KEY_ID, pair).catch(() => {
367
- });
368
- return pair;
369
- })();
370
- return _dpopKeyPromise;
371
- }
372
- __name(_getDpopKeyPair, "_getDpopKeyPair");
373
- function _b64urlFromBytes(bytes) {
374
- const arr = bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes);
375
- let s = "";
376
- for (let i = 0; i < arr.length; i++) s += String.fromCharCode(arr[i]);
377
- return btoa(s).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
378
- }
379
- __name(_b64urlFromBytes, "_b64urlFromBytes");
380
- function _b64urlFromString(str) {
381
- return _b64urlFromBytes(new TextEncoder().encode(str));
382
- }
383
- __name(_b64urlFromString, "_b64urlFromString");
384
- async function _publicJwk(pub) {
385
- const jwk = await crypto.subtle.exportKey("jwk", pub);
386
- return { kty: "EC", crv: "P-256", x: jwk.x, y: jwk.y };
387
- }
388
- __name(_publicJwk, "_publicJwk");
389
- async function _makeDpopProof(method, url) {
390
- try {
391
- const pair = await _getDpopKeyPair();
392
- const jwk = await _publicJwk(pair.publicKey);
393
- const header = { typ: "dpop+jwt", alg: "ES256", jwk };
394
- const htu = url.split("#")[0].split("?")[0];
395
- const jti = crypto.randomUUID && crypto.randomUUID() || _b64urlFromBytes(crypto.getRandomValues(new Uint8Array(16)));
396
- const payload = { htm: method.toUpperCase(), htu, iat: Math.floor(Date.now() / 1e3), jti };
397
- const signingInput = `${_b64urlFromString(JSON.stringify(header))}.${_b64urlFromString(JSON.stringify(payload))}`;
398
- const sig = await crypto.subtle.sign(
399
- { name: "ECDSA", hash: "SHA-256" },
400
- pair.privateKey,
401
- new TextEncoder().encode(signingInput)
402
- );
403
- return `${signingInput}.${_b64urlFromBytes(sig)}`;
404
- } catch {
405
- return null;
406
- }
407
- }
408
- __name(_makeDpopProof, "_makeDpopProof");
409
- function installAuthOnClient(client2) {
410
- if (_client) return;
411
- _client = client2;
412
- client2.setConfig({
413
- baseUrl: auth.getBaseUrl(),
414
- credentials: _withCredentials ? "include" : "same-origin"
415
- });
416
- client2.interceptors.request.use(async (request) => {
417
- const token = auth.getToken();
418
- if (token) request.headers.set("Authorization", `Bearer ${token}`);
419
- const locale = auth.getLocale();
420
- if (locale) request.headers.set("Accept-Language", locale);
421
- const apiKey = auth.getApiKey();
422
- if (apiKey && !request.headers.has("X-API-Key")) request.headers.set("X-API-Key", apiKey);
423
- try {
424
- const tz = Intl.DateTimeFormat().resolvedOptions().timeZone;
425
- if (tz) request.headers.set("X-Timezone", tz);
426
- } catch {
427
- }
428
- request.headers.set("X-Client-Time", (/* @__PURE__ */ new Date()).toISOString());
429
- if (dpopEnabled() && typeof window !== "undefined") {
430
- const proof = await _makeDpopProof(request.method, request.url);
431
- if (proof) request.headers.set("DPoP", proof);
432
- }
433
- return request;
434
- });
435
- client2.interceptors.error.use((err, res, req) => {
436
- if (err instanceof APIError) return err;
437
- const url = req?.url ?? "";
438
- const status = res?.status ?? 0;
439
- const statusText = res?.statusText ?? "";
440
- return new APIError(status, statusText, err, url);
441
- });
442
- client2.interceptors.response.use(async (response, request) => {
443
- if (response.status !== 401) return response;
444
- if (request.headers.get(RETRY_MARKER)) {
445
- if (_onUnauthorized) {
446
- try {
447
- _onUnauthorized(response);
448
- } catch {
449
- }
450
- }
451
- return response;
452
- }
453
- const newToken = await tryRefresh();
454
- if (!newToken) {
455
- if (_onUnauthorized) {
456
- try {
457
- _onUnauthorized(response);
458
- } catch {
459
- }
460
- }
461
- return response;
462
- }
463
- const retry = request.clone();
464
- retry.headers.set("Authorization", `Bearer ${newToken}`);
465
- retry.headers.set(RETRY_MARKER, "1");
466
- if (dpopEnabled() && typeof window !== "undefined") {
467
- const proof = await _makeDpopProof(retry.method, retry.url);
468
- if (proof) retry.headers.set("DPoP", proof);
469
- }
470
- try {
471
- const retried = await fetch(retry);
472
- if (retried.status === 401 && _onUnauthorized) {
473
- try {
474
- _onUnauthorized(retried);
475
- } catch {
476
- }
477
- }
478
- return retried;
479
- } catch {
480
- if (_onUnauthorized) {
481
- try {
482
- _onUnauthorized(response);
483
- } catch {
484
- }
485
- }
486
- return response;
487
- }
488
- });
489
- }
490
- __name(installAuthOnClient, "installAuthOnClient");
491
-
492
- // src/_api/generated/helpers/logger.ts
493
- import { createConsola } from "consola";
494
- var DEFAULT_CONFIG = {
495
- enabled: typeof process !== "undefined" && process.env.NODE_ENV !== "production",
496
- logRequests: true,
497
- logResponses: true,
498
- logErrors: true,
499
- logBodies: true,
500
- logHeaders: false
501
- };
502
- var SENSITIVE_HEADERS = [
503
- "authorization",
504
- "cookie",
505
- "set-cookie",
506
- "x-api-key",
507
- "x-csrf-token"
508
- ];
509
- var APILogger = class {
510
- static {
511
- __name(this, "APILogger");
512
- }
513
- config;
514
- consola;
515
- constructor(config = {}) {
516
- this.config = { ...DEFAULT_CONFIG, ...config };
517
- this.consola = config.consola || createConsola({
518
- level: this.config.enabled ? 4 : 0
519
- });
520
- }
521
- enable() {
522
- this.config.enabled = true;
523
- }
524
- disable() {
525
- this.config.enabled = false;
526
- }
527
- setConfig(config) {
528
- this.config = { ...this.config, ...config };
529
- }
530
- filterHeaders(headers) {
531
- if (!headers) return {};
532
- const filtered = {};
533
- Object.keys(headers).forEach((key) => {
534
- filtered[key] = SENSITIVE_HEADERS.includes(key.toLowerCase()) ? "***" : headers[key] || "";
535
- });
536
- return filtered;
537
- }
538
- logRequest(request) {
539
- if (!this.config.enabled || !this.config.logRequests) return;
540
- const { method, url, headers, body } = request;
541
- this.consola.start(`${method} ${url}`);
542
- if (this.config.logHeaders && headers) this.consola.debug("Headers:", this.filterHeaders(headers));
543
- if (this.config.logBodies && body) this.consola.debug("Body:", body);
544
- }
545
- logResponse(request, response) {
546
- if (!this.config.enabled || !this.config.logResponses) return;
547
- const { method, url } = request;
548
- const { status, statusText, data, duration } = response;
549
- this.consola.success(`${method} ${url} ${status} ${statusText} (${duration}ms)`);
550
- if (this.config.logBodies && data) this.consola.debug("Response:", data);
551
- }
552
- logError(request, error) {
553
- if (!this.config.enabled || !this.config.logErrors) return;
554
- const { method, url } = request;
555
- const { message, statusCode, fieldErrors, duration } = error;
556
- this.consola.error(`${method} ${url} ${statusCode || "Network"} Error (${duration}ms)`);
557
- this.consola.error("Message:", message);
558
- if (fieldErrors && Object.keys(fieldErrors).length > 0) {
559
- this.consola.error("Field Errors:");
560
- Object.entries(fieldErrors).forEach(([field, errors]) => {
561
- errors.forEach((err) => this.consola.error(` \u2022 ${field}: ${err}`));
562
- });
563
- }
564
- }
565
- info(message, ...args) {
566
- if (this.config.enabled) this.consola.info(message, ...args);
567
- }
568
- warn(message, ...args) {
569
- if (this.config.enabled) this.consola.warn(message, ...args);
570
- }
571
- error(message, ...args) {
572
- if (this.config.enabled) this.consola.error(message, ...args);
573
- }
574
- debug(message, ...args) {
575
- if (this.config.enabled) this.consola.debug(message, ...args);
576
- }
577
- success(message, ...args) {
578
- if (this.config.enabled) this.consola.success(message, ...args);
579
- }
580
- withTag(tag) {
581
- return this.consola.withTag(tag);
582
- }
583
- };
584
- var defaultLogger = new APILogger();
585
-
586
- // src/_api/generated/core/bodySerializer.gen.ts
587
- var serializeFormDataPair = /* @__PURE__ */ __name((data, key, value) => {
588
- if (typeof value === "string" || value instanceof Blob) {
589
- data.append(key, value);
590
- } else if (value instanceof Date) {
591
- data.append(key, value.toISOString());
592
- } else {
593
- data.append(key, JSON.stringify(value));
594
- }
595
- }, "serializeFormDataPair");
596
- var formDataBodySerializer = {
597
- bodySerializer: /* @__PURE__ */ __name((body) => {
598
- const data = new FormData();
599
- Object.entries(body).forEach(([key, value]) => {
600
- if (value === void 0 || value === null) {
601
- return;
602
- }
603
- if (Array.isArray(value)) {
604
- value.forEach((v) => serializeFormDataPair(data, key, v));
605
- } else {
606
- serializeFormDataPair(data, key, value);
607
- }
608
- });
609
- return data;
610
- }, "bodySerializer")
611
- };
612
- var jsonBodySerializer = {
613
- bodySerializer: /* @__PURE__ */ __name((body) => JSON.stringify(body, (_key, value) => typeof value === "bigint" ? value.toString() : value), "bodySerializer")
614
- };
615
-
616
- // src/_api/generated/core/params.gen.ts
617
- var extraPrefixesMap = {
618
- $body_: "body",
619
- $headers_: "headers",
620
- $path_: "path",
621
- $query_: "query"
622
- };
623
- var extraPrefixes = Object.entries(extraPrefixesMap);
624
-
625
- // src/_api/generated/core/serverSentEvents.gen.ts
626
- function createSseClient({
627
- onRequest,
628
- onSseError,
629
- onSseEvent,
630
- responseTransformer,
631
- responseValidator,
632
- sseDefaultRetryDelay,
633
- sseMaxRetryAttempts,
634
- sseMaxRetryDelay,
635
- sseSleepFn,
636
- url,
637
- ...options
638
- }) {
639
- let lastEventId;
640
- const sleep = sseSleepFn ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
641
- const createStream = /* @__PURE__ */ __name(async function* () {
642
- let retryDelay = sseDefaultRetryDelay ?? 3e3;
643
- let attempt = 0;
644
- const signal = options.signal ?? new AbortController().signal;
645
- while (true) {
646
- if (signal.aborted) break;
647
- attempt++;
648
- const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers);
649
- if (lastEventId !== void 0) {
650
- headers.set("Last-Event-ID", lastEventId);
651
- }
652
- try {
653
- const requestInit = {
654
- redirect: "follow",
655
- ...options,
656
- body: options.serializedBody,
657
- headers,
658
- signal
659
- };
660
- let request = new Request(url, requestInit);
661
- if (onRequest) {
662
- request = await onRequest(url, requestInit);
663
- }
664
- const _fetch = options.fetch ?? globalThis.fetch;
665
- const response = await _fetch(request);
666
- if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`);
667
- if (!response.body) throw new Error("No body in SSE response");
668
- const reader = response.body.pipeThrough(new TextDecoderStream()).getReader();
669
- let buffer = "";
670
- const abortHandler = /* @__PURE__ */ __name(() => {
671
- try {
672
- reader.cancel();
673
- } catch {
674
- }
675
- }, "abortHandler");
676
- signal.addEventListener("abort", abortHandler);
677
- try {
678
- while (true) {
679
- const { done, value } = await reader.read();
680
- if (done) break;
681
- buffer += value;
682
- buffer = buffer.replace(/\r\n?/g, "\n");
683
- const chunks = buffer.split("\n\n");
684
- buffer = chunks.pop() ?? "";
685
- for (const chunk of chunks) {
686
- const lines = chunk.split("\n");
687
- const dataLines = [];
688
- let eventName;
689
- for (const line of lines) {
690
- if (line.startsWith("data:")) {
691
- dataLines.push(line.replace(/^data:\s*/, ""));
692
- } else if (line.startsWith("event:")) {
693
- eventName = line.replace(/^event:\s*/, "");
694
- } else if (line.startsWith("id:")) {
695
- lastEventId = line.replace(/^id:\s*/, "");
696
- } else if (line.startsWith("retry:")) {
697
- const parsed = Number.parseInt(line.replace(/^retry:\s*/, ""), 10);
698
- if (!Number.isNaN(parsed)) {
699
- retryDelay = parsed;
700
- }
701
- }
702
- }
703
- let data;
704
- let parsedJson = false;
705
- if (dataLines.length) {
706
- const rawData = dataLines.join("\n");
707
- try {
708
- data = JSON.parse(rawData);
709
- parsedJson = true;
710
- } catch {
711
- data = rawData;
712
- }
713
- }
714
- if (parsedJson) {
715
- if (responseValidator) {
716
- await responseValidator(data);
717
- }
718
- if (responseTransformer) {
719
- data = await responseTransformer(data);
720
- }
721
- }
722
- onSseEvent?.({
723
- data,
724
- event: eventName,
725
- id: lastEventId,
726
- retry: retryDelay
727
- });
728
- if (dataLines.length) {
729
- yield data;
730
- }
731
- }
732
- }
733
- } finally {
734
- signal.removeEventListener("abort", abortHandler);
735
- reader.releaseLock();
736
- }
737
- break;
738
- } catch (error) {
739
- onSseError?.(error);
740
- if (sseMaxRetryAttempts !== void 0 && attempt >= sseMaxRetryAttempts) {
741
- break;
742
- }
743
- const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 3e4);
744
- await sleep(backoff);
745
- }
746
- }
747
- }, "createStream");
748
- const stream = createStream();
749
- return { stream };
750
- }
751
- __name(createSseClient, "createSseClient");
752
-
753
- // src/_api/generated/core/pathSerializer.gen.ts
754
- var separatorArrayExplode = /* @__PURE__ */ __name((style) => {
755
- switch (style) {
756
- case "label":
757
- return ".";
758
- case "matrix":
759
- return ";";
760
- case "simple":
761
- return ",";
762
- default:
763
- return "&";
764
- }
765
- }, "separatorArrayExplode");
766
- var separatorArrayNoExplode = /* @__PURE__ */ __name((style) => {
767
- switch (style) {
768
- case "form":
769
- return ",";
770
- case "pipeDelimited":
771
- return "|";
772
- case "spaceDelimited":
773
- return "%20";
774
- default:
775
- return ",";
776
- }
777
- }, "separatorArrayNoExplode");
778
- var separatorObjectExplode = /* @__PURE__ */ __name((style) => {
779
- switch (style) {
780
- case "label":
781
- return ".";
782
- case "matrix":
783
- return ";";
784
- case "simple":
785
- return ",";
786
- default:
787
- return "&";
788
- }
789
- }, "separatorObjectExplode");
790
- var serializeArrayParam = /* @__PURE__ */ __name(({
791
- allowReserved,
792
- explode,
793
- name,
794
- style,
795
- value
796
- }) => {
797
- if (!explode) {
798
- const joinedValues2 = (allowReserved ? value : value.map((v) => encodeURIComponent(v))).join(separatorArrayNoExplode(style));
799
- switch (style) {
800
- case "label":
801
- return `.${joinedValues2}`;
802
- case "matrix":
803
- return `;${name}=${joinedValues2}`;
804
- case "simple":
805
- return joinedValues2;
806
- default:
807
- return `${name}=${joinedValues2}`;
808
- }
809
- }
810
- const separator = separatorArrayExplode(style);
811
- const joinedValues = value.map((v) => {
812
- if (style === "label" || style === "simple") {
813
- return allowReserved ? v : encodeURIComponent(v);
814
- }
815
- return serializePrimitiveParam({
816
- allowReserved,
817
- name,
818
- value: v
819
- });
820
- }).join(separator);
821
- return style === "label" || style === "matrix" ? separator + joinedValues : joinedValues;
822
- }, "serializeArrayParam");
823
- var serializePrimitiveParam = /* @__PURE__ */ __name(({
824
- allowReserved,
825
- name,
826
- value
827
- }) => {
828
- if (value === void 0 || value === null) {
829
- return "";
830
- }
831
- if (typeof value === "object") {
832
- throw new Error(
833
- "Deeply-nested arrays/objects aren\u2019t supported. Provide your own `querySerializer()` to handle these."
834
- );
835
- }
836
- return `${name}=${allowReserved ? value : encodeURIComponent(value)}`;
837
- }, "serializePrimitiveParam");
838
- var serializeObjectParam = /* @__PURE__ */ __name(({
839
- allowReserved,
840
- explode,
841
- name,
842
- style,
843
- value,
844
- valueOnly
845
- }) => {
846
- if (value instanceof Date) {
847
- return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`;
848
- }
849
- if (style !== "deepObject" && !explode) {
850
- let values = [];
851
- Object.entries(value).forEach(([key, v]) => {
852
- values = [...values, key, allowReserved ? v : encodeURIComponent(v)];
853
- });
854
- const joinedValues2 = values.join(",");
855
- switch (style) {
856
- case "form":
857
- return `${name}=${joinedValues2}`;
858
- case "label":
859
- return `.${joinedValues2}`;
860
- case "matrix":
861
- return `;${name}=${joinedValues2}`;
862
- default:
863
- return joinedValues2;
864
- }
865
- }
866
- const separator = separatorObjectExplode(style);
867
- const joinedValues = Object.entries(value).map(
868
- ([key, v]) => serializePrimitiveParam({
869
- allowReserved,
870
- name: style === "deepObject" ? `${name}[${key}]` : key,
871
- value: v
872
- })
873
- ).join(separator);
874
- return style === "label" || style === "matrix" ? separator + joinedValues : joinedValues;
875
- }, "serializeObjectParam");
876
-
877
- // src/_api/generated/core/utils.gen.ts
878
- var PATH_PARAM_RE = /\{[^{}]+\}/g;
879
- var defaultPathSerializer = /* @__PURE__ */ __name(({ path, url: _url }) => {
880
- let url = _url;
881
- const matches = _url.match(PATH_PARAM_RE);
882
- if (matches) {
883
- for (const match of matches) {
884
- let explode = false;
885
- let name = match.substring(1, match.length - 1);
886
- let style = "simple";
887
- if (name.endsWith("*")) {
888
- explode = true;
889
- name = name.substring(0, name.length - 1);
890
- }
891
- if (name.startsWith(".")) {
892
- name = name.substring(1);
893
- style = "label";
894
- } else if (name.startsWith(";")) {
895
- name = name.substring(1);
896
- style = "matrix";
897
- }
898
- const value = path[name];
899
- if (value === void 0 || value === null) {
900
- continue;
901
- }
902
- if (Array.isArray(value)) {
903
- url = url.replace(match, serializeArrayParam({ explode, name, style, value }));
904
- continue;
905
- }
906
- if (typeof value === "object") {
907
- url = url.replace(
908
- match,
909
- serializeObjectParam({
910
- explode,
911
- name,
912
- style,
913
- value,
914
- valueOnly: true
915
- })
916
- );
917
- continue;
918
- }
919
- if (style === "matrix") {
920
- url = url.replace(
921
- match,
922
- `;${serializePrimitiveParam({
923
- name,
924
- value
925
- })}`
926
- );
927
- continue;
928
- }
929
- const replaceValue = encodeURIComponent(
930
- style === "label" ? `.${value}` : value
931
- );
932
- url = url.replace(match, replaceValue);
933
- }
934
- }
935
- return url;
936
- }, "defaultPathSerializer");
937
- var getUrl = /* @__PURE__ */ __name(({
938
- baseUrl,
939
- path,
940
- query,
941
- querySerializer,
942
- url: _url
943
- }) => {
944
- const pathUrl = _url.startsWith("/") ? _url : `/${_url}`;
945
- let url = (baseUrl ?? "") + pathUrl;
946
- if (path) {
947
- url = defaultPathSerializer({ path, url });
948
- }
949
- let search = query ? querySerializer(query) : "";
950
- if (search.startsWith("?")) {
951
- search = search.substring(1);
952
- }
953
- if (search) {
954
- url += `?${search}`;
955
- }
956
- return url;
957
- }, "getUrl");
958
- function getValidRequestBody(options) {
959
- const hasBody = options.body !== void 0;
960
- const isSerializedBody = hasBody && options.bodySerializer;
961
- if (isSerializedBody) {
962
- if ("serializedBody" in options) {
963
- const hasSerializedBody = options.serializedBody !== void 0 && options.serializedBody !== "";
964
- return hasSerializedBody ? options.serializedBody : null;
965
- }
966
- return options.body !== "" ? options.body : null;
967
- }
968
- if (hasBody) {
969
- return options.body;
970
- }
971
- return void 0;
972
- }
973
- __name(getValidRequestBody, "getValidRequestBody");
974
-
975
- // src/_api/generated/core/auth.gen.ts
976
- var getAuthToken = /* @__PURE__ */ __name(async (auth2, callback) => {
977
- const token = typeof callback === "function" ? await callback(auth2) : callback;
978
- if (!token) {
979
- return;
980
- }
981
- if (auth2.scheme === "bearer") {
982
- return `Bearer ${token}`;
983
- }
984
- if (auth2.scheme === "basic") {
985
- return `Basic ${btoa(token)}`;
986
- }
987
- return token;
988
- }, "getAuthToken");
989
-
990
- // src/_api/generated/client/utils.gen.ts
991
- var createQuerySerializer = /* @__PURE__ */ __name(({
992
- parameters = {},
993
- ...args
994
- } = {}) => {
995
- const querySerializer = /* @__PURE__ */ __name((queryParams) => {
996
- const search = [];
997
- if (queryParams && typeof queryParams === "object") {
998
- for (const name in queryParams) {
999
- const value = queryParams[name];
1000
- if (value === void 0 || value === null) {
1001
- continue;
1002
- }
1003
- const options = parameters[name] || args;
1004
- if (Array.isArray(value)) {
1005
- const serializedArray = serializeArrayParam({
1006
- allowReserved: options.allowReserved,
1007
- explode: true,
1008
- name,
1009
- style: "form",
1010
- value,
1011
- ...options.array
1012
- });
1013
- if (serializedArray) search.push(serializedArray);
1014
- } else if (typeof value === "object") {
1015
- const serializedObject = serializeObjectParam({
1016
- allowReserved: options.allowReserved,
1017
- explode: true,
1018
- name,
1019
- style: "deepObject",
1020
- value,
1021
- ...options.object
1022
- });
1023
- if (serializedObject) search.push(serializedObject);
1024
- } else {
1025
- const serializedPrimitive = serializePrimitiveParam({
1026
- allowReserved: options.allowReserved,
1027
- name,
1028
- value
1029
- });
1030
- if (serializedPrimitive) search.push(serializedPrimitive);
1031
- }
1032
- }
1033
- }
1034
- return search.join("&");
1035
- }, "querySerializer");
1036
- return querySerializer;
1037
- }, "createQuerySerializer");
1038
- var getParseAs = /* @__PURE__ */ __name((contentType) => {
1039
- if (!contentType) {
1040
- return "stream";
1041
- }
1042
- const cleanContent = contentType.split(";")[0]?.trim();
1043
- if (!cleanContent) {
1044
- return;
1045
- }
1046
- if (cleanContent.startsWith("application/json") || cleanContent.endsWith("+json")) {
1047
- return "json";
1048
- }
1049
- if (cleanContent === "multipart/form-data") {
1050
- return "formData";
1051
- }
1052
- if (["application/", "audio/", "image/", "video/"].some((type) => cleanContent.startsWith(type))) {
1053
- return "blob";
1054
- }
1055
- if (cleanContent.startsWith("text/")) {
1056
- return "text";
1057
- }
1058
- return;
1059
- }, "getParseAs");
1060
- var checkForExistence = /* @__PURE__ */ __name((options, name) => {
1061
- if (!name) {
1062
- return false;
1063
- }
1064
- if (options.headers.has(name) || options.query?.[name] || options.headers.get("Cookie")?.includes(`${name}=`)) {
1065
- return true;
1066
- }
1067
- return false;
1068
- }, "checkForExistence");
1069
- async function setAuthParams(options) {
1070
- for (const auth2 of options.security ?? []) {
1071
- if (checkForExistence(options, auth2.name)) {
1072
- continue;
1073
- }
1074
- const token = await getAuthToken(auth2, options.auth);
1075
- if (!token) {
1076
- continue;
1077
- }
1078
- const name = auth2.name ?? "Authorization";
1079
- switch (auth2.in) {
1080
- case "query":
1081
- if (!options.query) {
1082
- options.query = {};
1083
- }
1084
- options.query[name] = token;
1085
- break;
1086
- case "cookie":
1087
- options.headers.append("Cookie", `${name}=${token}`);
1088
- break;
1089
- case "header":
1090
- default:
1091
- options.headers.set(name, token);
1092
- break;
1093
- }
1094
- }
1095
- }
1096
- __name(setAuthParams, "setAuthParams");
1097
- var buildUrl = /* @__PURE__ */ __name((options) => getUrl({
1098
- baseUrl: options.baseUrl,
1099
- path: options.path,
1100
- query: options.query,
1101
- querySerializer: typeof options.querySerializer === "function" ? options.querySerializer : createQuerySerializer(options.querySerializer),
1102
- url: options.url
1103
- }), "buildUrl");
1104
- var mergeConfigs = /* @__PURE__ */ __name((a, b) => {
1105
- const config = { ...a, ...b };
1106
- if (config.baseUrl?.endsWith("/")) {
1107
- config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1);
1108
- }
1109
- config.headers = mergeHeaders(a.headers, b.headers);
1110
- return config;
1111
- }, "mergeConfigs");
1112
- var headersEntries = /* @__PURE__ */ __name((headers) => {
1113
- const entries = [];
1114
- headers.forEach((value, key) => {
1115
- entries.push([key, value]);
1116
- });
1117
- return entries;
1118
- }, "headersEntries");
1119
- var mergeHeaders = /* @__PURE__ */ __name((...headers) => {
1120
- const mergedHeaders = new Headers();
1121
- for (const header of headers) {
1122
- if (!header) {
1123
- continue;
1124
- }
1125
- const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header);
1126
- for (const [key, value] of iterator) {
1127
- if (value === null) {
1128
- mergedHeaders.delete(key);
1129
- } else if (Array.isArray(value)) {
1130
- for (const v of value) {
1131
- mergedHeaders.append(key, v);
1132
- }
1133
- } else if (value !== void 0) {
1134
- mergedHeaders.set(
1135
- key,
1136
- typeof value === "object" ? JSON.stringify(value) : value
1137
- );
1138
- }
1139
- }
1140
- }
1141
- return mergedHeaders;
1142
- }, "mergeHeaders");
1143
- var Interceptors = class {
1144
- static {
1145
- __name(this, "Interceptors");
1146
- }
1147
- fns = [];
1148
- clear() {
1149
- this.fns = [];
1150
- }
1151
- eject(id) {
1152
- const index = this.getInterceptorIndex(id);
1153
- if (this.fns[index]) {
1154
- this.fns[index] = null;
1155
- }
1156
- }
1157
- exists(id) {
1158
- const index = this.getInterceptorIndex(id);
1159
- return Boolean(this.fns[index]);
1160
- }
1161
- getInterceptorIndex(id) {
1162
- if (typeof id === "number") {
1163
- return this.fns[id] ? id : -1;
1164
- }
1165
- return this.fns.indexOf(id);
1166
- }
1167
- update(id, fn) {
1168
- const index = this.getInterceptorIndex(id);
1169
- if (this.fns[index]) {
1170
- this.fns[index] = fn;
1171
- return id;
1172
- }
1173
- return false;
1174
- }
1175
- use(fn) {
1176
- this.fns.push(fn);
1177
- return this.fns.length - 1;
1178
- }
1179
- };
1180
- var createInterceptors = /* @__PURE__ */ __name(() => ({
1181
- error: new Interceptors(),
1182
- request: new Interceptors(),
1183
- response: new Interceptors()
1184
- }), "createInterceptors");
1185
- var defaultQuerySerializer = createQuerySerializer({
1186
- allowReserved: false,
1187
- array: {
1188
- explode: true,
1189
- style: "form"
1190
- },
1191
- object: {
1192
- explode: true,
1193
- style: "deepObject"
1194
- }
1195
- });
1196
- var defaultHeaders = {
1197
- "Content-Type": "application/json"
1198
- };
1199
- var createConfig = /* @__PURE__ */ __name((override = {}) => ({
1200
- ...jsonBodySerializer,
1201
- headers: defaultHeaders,
1202
- parseAs: "auto",
1203
- querySerializer: defaultQuerySerializer,
1204
- ...override
1205
- }), "createConfig");
1206
-
1207
- // src/_api/generated/client/client.gen.ts
1208
- var createClient = /* @__PURE__ */ __name((config = {}) => {
1209
- let _config = mergeConfigs(createConfig(), config);
1210
- const getConfig = /* @__PURE__ */ __name(() => ({ ..._config }), "getConfig");
1211
- const setConfig = /* @__PURE__ */ __name((config2) => {
1212
- _config = mergeConfigs(_config, config2);
1213
- return getConfig();
1214
- }, "setConfig");
1215
- const interceptors = createInterceptors();
1216
- const beforeRequest = /* @__PURE__ */ __name(async (options) => {
1217
- const opts = {
1218
- ..._config,
1219
- ...options,
1220
- fetch: options.fetch ?? _config.fetch ?? globalThis.fetch,
1221
- headers: mergeHeaders(_config.headers, options.headers),
1222
- serializedBody: void 0
1223
- };
1224
- if (opts.security) {
1225
- await setAuthParams(opts);
1226
- }
1227
- if (opts.requestValidator) {
1228
- await opts.requestValidator(opts);
1229
- }
1230
- if (opts.body !== void 0 && opts.bodySerializer) {
1231
- opts.serializedBody = opts.bodySerializer(opts.body);
1232
- }
1233
- if (opts.body === void 0 || opts.serializedBody === "") {
1234
- opts.headers.delete("Content-Type");
1235
- }
1236
- const resolvedOpts = opts;
1237
- const url = buildUrl(resolvedOpts);
1238
- return { opts: resolvedOpts, url };
1239
- }, "beforeRequest");
1240
- const request = /* @__PURE__ */ __name(async (options) => {
1241
- const throwOnError = options.throwOnError ?? _config.throwOnError;
1242
- const responseStyle = options.responseStyle ?? _config.responseStyle;
1243
- let request2;
1244
- let response;
1245
- try {
1246
- const { opts, url } = await beforeRequest(options);
1247
- const requestInit = {
1248
- redirect: "follow",
1249
- ...opts,
1250
- body: getValidRequestBody(opts)
1251
- };
1252
- request2 = new Request(url, requestInit);
1253
- for (const fn of interceptors.request.fns) {
1254
- if (fn) {
1255
- request2 = await fn(request2, opts);
1256
- }
1257
- }
1258
- const _fetch = opts.fetch;
1259
- response = await _fetch(request2);
1260
- for (const fn of interceptors.response.fns) {
1261
- if (fn) {
1262
- response = await fn(response, request2, opts);
1263
- }
1264
- }
1265
- const result = {
1266
- request: request2,
1267
- response
1268
- };
1269
- if (response.ok) {
1270
- const parseAs = (opts.parseAs === "auto" ? getParseAs(response.headers.get("Content-Type")) : opts.parseAs) ?? "json";
1271
- if (response.status === 204 || response.headers.get("Content-Length") === "0") {
1272
- let emptyData;
1273
- switch (parseAs) {
1274
- case "arrayBuffer":
1275
- case "blob":
1276
- case "text":
1277
- emptyData = await response[parseAs]();
1278
- break;
1279
- case "formData":
1280
- emptyData = new FormData();
1281
- break;
1282
- case "stream":
1283
- emptyData = response.body;
1284
- break;
1285
- case "json":
1286
- default:
1287
- emptyData = {};
1288
- break;
1289
- }
1290
- return opts.responseStyle === "data" ? emptyData : {
1291
- data: emptyData,
1292
- ...result
1293
- };
1294
- }
1295
- let data;
1296
- switch (parseAs) {
1297
- case "arrayBuffer":
1298
- case "blob":
1299
- case "formData":
1300
- case "text":
1301
- data = await response[parseAs]();
1302
- break;
1303
- case "json": {
1304
- const text = await response.text();
1305
- data = text ? JSON.parse(text) : {};
1306
- break;
1307
- }
1308
- case "stream":
1309
- return opts.responseStyle === "data" ? response.body : {
1310
- data: response.body,
1311
- ...result
1312
- };
1313
- }
1314
- if (parseAs === "json") {
1315
- if (opts.responseValidator) {
1316
- await opts.responseValidator(data);
1317
- }
1318
- if (opts.responseTransformer) {
1319
- data = await opts.responseTransformer(data);
1320
- }
1321
- }
1322
- return opts.responseStyle === "data" ? data : {
1323
- data,
1324
- ...result
1325
- };
1326
- }
1327
- const textError = await response.text();
1328
- let jsonError;
1329
- try {
1330
- jsonError = JSON.parse(textError);
1331
- } catch {
1332
- }
1333
- throw jsonError ?? textError;
1334
- } catch (error) {
1335
- let finalError = error;
1336
- for (const fn of interceptors.error.fns) {
1337
- if (fn) {
1338
- finalError = await fn(finalError, response, request2, options);
1339
- }
1340
- }
1341
- finalError = finalError || {};
1342
- if (throwOnError) {
1343
- throw finalError;
1344
- }
1345
- return responseStyle === "data" ? void 0 : {
1346
- error: finalError,
1347
- request: request2,
1348
- response
1349
- };
1350
- }
1351
- }, "request");
1352
- const makeMethodFn = /* @__PURE__ */ __name((method) => (options) => request({ ...options, method }), "makeMethodFn");
1353
- const makeSseFn = /* @__PURE__ */ __name((method) => async (options) => {
1354
- const { opts, url } = await beforeRequest(options);
1355
- return createSseClient({
1356
- ...opts,
1357
- body: opts.body,
1358
- method,
1359
- onRequest: /* @__PURE__ */ __name(async (url2, init) => {
1360
- let request2 = new Request(url2, init);
1361
- for (const fn of interceptors.request.fns) {
1362
- if (fn) {
1363
- request2 = await fn(request2, opts);
1364
- }
1365
- }
1366
- return request2;
1367
- }, "onRequest"),
1368
- serializedBody: getValidRequestBody(opts),
1369
- url
1370
- });
1371
- }, "makeSseFn");
1372
- const _buildUrl = /* @__PURE__ */ __name((options) => buildUrl({ ..._config, ...options }), "_buildUrl");
1373
- return {
1374
- buildUrl: _buildUrl,
1375
- connect: makeMethodFn("CONNECT"),
1376
- delete: makeMethodFn("DELETE"),
1377
- get: makeMethodFn("GET"),
1378
- getConfig,
1379
- head: makeMethodFn("HEAD"),
1380
- interceptors,
1381
- options: makeMethodFn("OPTIONS"),
1382
- patch: makeMethodFn("PATCH"),
1383
- post: makeMethodFn("POST"),
1384
- put: makeMethodFn("PUT"),
1385
- request,
1386
- setConfig,
1387
- sse: {
1388
- connect: makeSseFn("CONNECT"),
1389
- delete: makeSseFn("DELETE"),
1390
- get: makeSseFn("GET"),
1391
- head: makeSseFn("HEAD"),
1392
- options: makeSseFn("OPTIONS"),
1393
- patch: makeSseFn("PATCH"),
1394
- post: makeSseFn("POST"),
1395
- put: makeSseFn("PUT"),
1396
- trace: makeSseFn("TRACE")
1397
- },
1398
- trace: makeMethodFn("TRACE")
1399
- };
1400
- }, "createClient");
1401
-
1402
- // src/_api/generated/client.gen.ts
1403
- var client = createClient(createConfig({ baseUrl: "http://localhost:8000" }));
1404
- installAuthOnClient(client);
1405
-
1406
- // src/_api/generated/sdk.gen.ts
1407
- var CfgAccountsApiKey = class {
1408
- static {
1409
- __name(this, "CfgAccountsApiKey");
1410
- }
1411
- /**
1412
- * Get API key details
1413
- *
1414
- * Retrieve the current user's API key (masked) and metadata.
1415
- */
1416
- static cfgAccountsApiKeyRetrieve(options) {
1417
- return (options?.client ?? client).get({
1418
- security: [
1419
- { scheme: "bearer", type: "http" },
1420
- {
1421
- in: "cookie",
1422
- name: "sessionid",
1423
- type: "apiKey"
1424
- },
1425
- { name: "X-API-Key", type: "apiKey" }
1426
- ],
1427
- url: "/cfg/accounts/api-key/",
1428
- ...options
1429
- });
1430
- }
1431
- /**
1432
- * Regenerate API key
1433
- *
1434
- * Generate a new API key. The full key is returned only once.
1435
- */
1436
- static cfgAccountsApiKeyRegenerateCreate(options) {
1437
- return (options.client ?? client).post({
1438
- security: [
1439
- { scheme: "bearer", type: "http" },
1440
- {
1441
- in: "cookie",
1442
- name: "sessionid",
1443
- type: "apiKey"
1444
- },
1445
- { name: "X-API-Key", type: "apiKey" }
1446
- ],
1447
- url: "/cfg/accounts/api-key/regenerate/",
1448
- ...options,
1449
- headers: {
1450
- "Content-Type": "application/json",
1451
- ...options.headers
1452
- }
1453
- });
1454
- }
1455
- /**
1456
- * Reveal API key
1457
- *
1458
- * Return the current full API key WITHOUT rotating it. The same durable value every one of the user's agents uses — for the signed-in user to copy and paste into agent onboarding. Default GET stays masked; this is the explicit reveal action.
1459
- */
1460
- static cfgAccountsApiKeyRevealCreate(options) {
1461
- return (options.client ?? client).post({
1462
- security: [
1463
- { scheme: "bearer", type: "http" },
1464
- {
1465
- in: "cookie",
1466
- name: "sessionid",
1467
- type: "apiKey"
1468
- },
1469
- { name: "X-API-Key", type: "apiKey" }
1470
- ],
1471
- url: "/cfg/accounts/api-key/reveal/",
1472
- ...options,
1473
- headers: {
1474
- "Content-Type": "application/json",
1475
- ...options.headers
1476
- }
1477
- });
1478
- }
1479
- /**
1480
- * Test API key
1481
- *
1482
- * Test whether an API key is valid without consuming it.
1483
- */
1484
- static cfgAccountsApiKeyTestCreate(options) {
1485
- return (options.client ?? client).post({
1486
- security: [
1487
- { scheme: "bearer", type: "http" },
1488
- {
1489
- in: "cookie",
1490
- name: "sessionid",
1491
- type: "apiKey"
1492
- },
1493
- { name: "X-API-Key", type: "apiKey" }
1494
- ],
1495
- url: "/cfg/accounts/api-key/test/",
1496
- ...options,
1497
- headers: {
1498
- "Content-Type": "application/json",
1499
- ...options.headers
1500
- }
1501
- });
1502
- }
1503
- };
1504
- var CfgAccountsOauth = class {
1505
- static {
1506
- __name(this, "CfgAccountsOauth");
1507
- }
1508
- /**
1509
- * List OAuth connections
1510
- *
1511
- * Get all OAuth connections for the current user.
1512
- */
1513
- static cfgAccountsOauthConnectionsList(options) {
1514
- return (options?.client ?? client).get({
1515
- security: [{ name: "X-API-Key", type: "apiKey" }, { scheme: "bearer", type: "http" }],
1516
- url: "/cfg/accounts/oauth/connections/",
1517
- ...options
1518
- });
1519
- }
1520
- /**
1521
- * Disconnect OAuth provider
1522
- *
1523
- * Remove OAuth connection for the specified provider.
1524
- */
1525
- static cfgAccountsOauthDisconnectCreate(options) {
1526
- return (options.client ?? client).post({
1527
- security: [{ name: "X-API-Key", type: "apiKey" }, { scheme: "bearer", type: "http" }],
1528
- url: "/cfg/accounts/oauth/disconnect/",
1529
- ...options,
1530
- headers: {
1531
- "Content-Type": "application/json",
1532
- ...options.headers
1533
- }
1534
- });
1535
- }
1536
- /**
1537
- * Start GitHub OAuth
1538
- *
1539
- * Generate GitHub OAuth authorization URL. Redirect user to this URL to start authentication.
1540
- */
1541
- static cfgAccountsOauthGithubAuthorizeCreate(options) {
1542
- return (options?.client ?? client).post({
1543
- url: "/cfg/accounts/oauth/github/authorize/",
1544
- ...options,
1545
- headers: {
1546
- "Content-Type": "application/json",
1547
- ...options?.headers
1548
- }
1549
- });
1550
- }
1551
- /**
1552
- * Complete GitHub OAuth
1553
- *
1554
- * Exchange authorization code for JWT tokens. Call this after GitHub redirects back with code.
1555
- */
1556
- static cfgAccountsOauthGithubCallbackCreate(options) {
1557
- return (options.client ?? client).post({
1558
- url: "/cfg/accounts/oauth/github/callback/",
1559
- ...options,
1560
- headers: {
1561
- "Content-Type": "application/json",
1562
- ...options.headers
1563
- }
1564
- });
1565
- }
1566
- /**
1567
- * List OAuth providers
1568
- *
1569
- * Get list of available OAuth providers for authentication.
1570
- */
1571
- static cfgAccountsOauthProvidersRetrieve(options) {
1572
- return (options?.client ?? client).get({ url: "/cfg/accounts/oauth/providers/", ...options });
1573
- }
1574
- };
1575
- var CfgAccounts = class {
1576
- static {
1577
- __name(this, "CfgAccounts");
1578
- }
1579
- /**
1580
- * Request OTP code to email.
1581
- */
1582
- static cfgAccountsOtpRequestCreate(options) {
1583
- return (options.client ?? client).post({
1584
- security: [{ name: "X-API-Key", type: "apiKey" }, { scheme: "bearer", type: "http" }],
1585
- url: "/cfg/accounts/otp/request/",
1586
- ...options,
1587
- headers: {
1588
- "Content-Type": "application/json",
1589
- ...options.headers
1590
- }
1591
- });
1592
- }
1593
- /**
1594
- * Verify OTP code and return JWT tokens or 2FA session.
1595
- *
1596
- * If user has 2FA enabled:
1597
- * - Returns requires_2fa=True with session_id
1598
- * - Client must complete 2FA verification at /cfg/totp/verify/
1599
- *
1600
- * If user has no 2FA:
1601
- * - Returns JWT tokens and user data directly
1602
- */
1603
- static cfgAccountsOtpVerifyCreate(options) {
1604
- return (options.client ?? client).post({
1605
- security: [{ name: "X-API-Key", type: "apiKey" }, { scheme: "bearer", type: "http" }],
1606
- url: "/cfg/accounts/otp/verify/",
1607
- ...options,
1608
- headers: {
1609
- "Content-Type": "application/json",
1610
- ...options.headers
1611
- }
1612
- });
1613
- }
1614
- };
1615
- var CfgAccountsProfile = class {
1616
- static {
1617
- __name(this, "CfgAccountsProfile");
1618
- }
1619
- /**
1620
- * Get current user profile
1621
- *
1622
- * Retrieve the current authenticated user's profile information.
1623
- */
1624
- static cfgAccountsProfileRetrieve(options) {
1625
- return (options?.client ?? client).get({
1626
- security: [{ scheme: "bearer", type: "http" }, {
1627
- in: "cookie",
1628
- name: "sessionid",
1629
- type: "apiKey"
1630
- }],
1631
- url: "/cfg/accounts/profile/",
1632
- ...options
1633
- });
1634
- }
1635
- /**
1636
- * Upload user avatar
1637
- *
1638
- * Upload avatar image for the current authenticated user. Accepts multipart/form-data with 'avatar' field.
1639
- */
1640
- static cfgAccountsProfileAvatarCreate(options) {
1641
- return (options?.client ?? client).post({
1642
- ...formDataBodySerializer,
1643
- security: [{ name: "X-API-Key", type: "apiKey" }, { scheme: "bearer", type: "http" }],
1644
- url: "/cfg/accounts/profile/avatar/",
1645
- ...options,
1646
- headers: {
1647
- "Content-Type": null,
1648
- ...options?.headers
1649
- }
1650
- });
1651
- }
1652
- /**
1653
- * Delete user account
1654
- *
1655
- *
1656
- * Permanently delete the current user's account.
1657
- *
1658
- * This operation:
1659
- * - Deactivates the account (user cannot log in)
1660
- * - Anonymizes personal data (GDPR compliance)
1661
- * - Frees up the email address for re-registration
1662
- * - Preserves audit trail
1663
- *
1664
- * The account can be restored by an administrator if needed.
1665
- *
1666
- */
1667
- static cfgAccountsProfileDeleteCreate(options) {
1668
- return (options?.client ?? client).post({
1669
- security: [{ scheme: "bearer", type: "http" }, {
1670
- in: "cookie",
1671
- name: "sessionid",
1672
- type: "apiKey"
1673
- }],
1674
- url: "/cfg/accounts/profile/delete/",
1675
- ...options
1676
- });
1677
- }
1678
- /**
1679
- * Partial update user profile
1680
- *
1681
- * Partially update the current authenticated user's profile information. Supports avatar upload.
1682
- */
1683
- static cfgAccountsProfilePartialPartialUpdate(options) {
1684
- return (options?.client ?? client).patch({
1685
- security: [{ scheme: "bearer", type: "http" }, {
1686
- in: "cookie",
1687
- name: "sessionid",
1688
- type: "apiKey"
1689
- }],
1690
- url: "/cfg/accounts/profile/partial/",
1691
- ...options,
1692
- headers: {
1693
- "Content-Type": "application/json",
1694
- ...options?.headers
1695
- }
1696
- });
1697
- }
1698
- /**
1699
- * Partial update user profile
1700
- *
1701
- * Partially update the current authenticated user's profile information. Supports avatar upload.
1702
- */
1703
- static cfgAccountsProfilePartialUpdate(options) {
1704
- return (options?.client ?? client).put({
1705
- security: [{ scheme: "bearer", type: "http" }, {
1706
- in: "cookie",
1707
- name: "sessionid",
1708
- type: "apiKey"
1709
- }],
1710
- url: "/cfg/accounts/profile/partial/",
1711
- ...options,
1712
- headers: {
1713
- "Content-Type": "application/json",
1714
- ...options?.headers
1715
- }
1716
- });
1717
- }
1718
- /**
1719
- * Update user profile
1720
- *
1721
- * Update the current authenticated user's profile information.
1722
- */
1723
- static cfgAccountsProfileUpdatePartialUpdate(options) {
1724
- return (options?.client ?? client).patch({
1725
- security: [{ scheme: "bearer", type: "http" }, {
1726
- in: "cookie",
1727
- name: "sessionid",
1728
- type: "apiKey"
1729
- }],
1730
- url: "/cfg/accounts/profile/update/",
1731
- ...options,
1732
- headers: {
1733
- "Content-Type": "application/json",
1734
- ...options?.headers
1735
- }
1736
- });
1737
- }
1738
- /**
1739
- * Update user profile
1740
- *
1741
- * Update the current authenticated user's profile information.
1742
- */
1743
- static cfgAccountsProfileUpdateUpdate(options) {
1744
- return (options?.client ?? client).put({
1745
- security: [{ scheme: "bearer", type: "http" }, {
1746
- in: "cookie",
1747
- name: "sessionid",
1748
- type: "apiKey"
1749
- }],
1750
- url: "/cfg/accounts/profile/update/",
1751
- ...options,
1752
- headers: {
1753
- "Content-Type": "application/json",
1754
- ...options?.headers
1755
- }
1756
- });
1757
- }
1758
- };
1759
- var CfgAccountsAuth = class {
1760
- static {
1761
- __name(this, "CfgAccountsAuth");
1762
- }
1763
- /**
1764
- * Refresh JWT token.
1765
- *
1766
- * DPoP-aware: when the incoming refresh token is key-bound (`cnf.jkt`), the
1767
- * rotated access/refresh in the response are re-stamped with the same `cnf`
1768
- * (stock SimpleJWT drops it from the derived access), and a matching DPoP
1769
- * proof is required on the refresh request — so a stolen refresh token can't
1770
- * be used to mint fresh tokens.
1771
- */
1772
- static cfgAccountsTokenRefreshCreate(options) {
1773
- return (options.client ?? client).post({
1774
- url: "/cfg/accounts/token/refresh/",
1775
- ...options,
1776
- headers: {
1777
- "Content-Type": "application/json",
1778
- ...options.headers
1779
- }
1780
- });
1781
- }
1782
- };
1783
- var CfgCentrifugo = class {
1784
- static {
1785
- __name(this, "CfgCentrifugo");
1786
- }
1787
- /**
1788
- * Get Centrifugo connection token
1789
- *
1790
- * Generate JWT token for WebSocket connection to Centrifugo. Token includes user's allowed channels based on their permissions. Requires authentication.
1791
- */
1792
- static cfgCentrifugoAuthTokenRetrieve(options) {
1793
- return (options?.client ?? client).get({
1794
- security: [{ name: "X-API-Key", type: "apiKey" }, { scheme: "bearer", type: "http" }],
1795
- url: "/cfg/centrifugo/auth/token/",
1796
- ...options
1797
- });
1798
- }
1799
- };
1800
- var CfgTotpBackupCodes = class {
1801
- static {
1802
- __name(this, "CfgTotpBackupCodes");
1803
- }
1804
- /**
1805
- * Get backup codes status for user.
1806
- */
1807
- static cfgTotpBackupCodesRetrieve(options) {
1808
- return (options?.client ?? client).get({
1809
- security: [{ name: "X-API-Key", type: "apiKey" }, { scheme: "bearer", type: "http" }],
1810
- url: "/cfg/totp/backup-codes/",
1811
- ...options
1812
- });
1813
- }
1814
- /**
1815
- * Regenerate backup codes.
1816
- *
1817
- * Requires TOTP code for verification.
1818
- * Invalidates all existing codes.
1819
- */
1820
- static cfgTotpBackupCodesRegenerateCreate(options) {
1821
- return (options.client ?? client).post({
1822
- security: [{ name: "X-API-Key", type: "apiKey" }, { scheme: "bearer", type: "http" }],
1823
- url: "/cfg/totp/backup-codes/regenerate/",
1824
- ...options,
1825
- headers: {
1826
- "Content-Type": "application/json",
1827
- ...options.headers
1828
- }
1829
- });
1830
- }
1831
- };
1832
- var CfgTotp = class {
1833
- static {
1834
- __name(this, "CfgTotp");
1835
- }
1836
- /**
1837
- * List all TOTP devices for user.
1838
- */
1839
- static cfgTotpDevicesRetrieve(options) {
1840
- return (options?.client ?? client).get({
1841
- security: [{ name: "X-API-Key", type: "apiKey" }, { scheme: "bearer", type: "http" }],
1842
- url: "/cfg/totp/devices/",
1843
- ...options
1844
- });
1845
- }
1846
- /**
1847
- * Delete a TOTP device.
1848
- *
1849
- * Requires verification code if removing the last/primary device.
1850
- */
1851
- static cfgTotpDevicesDestroy(options) {
1852
- return (options.client ?? client).delete({
1853
- security: [{ name: "X-API-Key", type: "apiKey" }, { scheme: "bearer", type: "http" }],
1854
- url: "/cfg/totp/devices/{id}/",
1855
- ...options
1856
- });
1857
- }
1858
- /**
1859
- * Completely disable 2FA for account.
1860
- *
1861
- * Requires verification code.
1862
- */
1863
- static cfgTotpDisableCreate(options) {
1864
- return (options.client ?? client).post({
1865
- security: [{ name: "X-API-Key", type: "apiKey" }, { scheme: "bearer", type: "http" }],
1866
- url: "/cfg/totp/disable/",
1867
- ...options,
1868
- headers: {
1869
- "Content-Type": "application/json",
1870
- ...options.headers
1871
- }
1872
- });
1873
- }
1874
- };
1875
- var CfgTotpSetup = class {
1876
- static {
1877
- __name(this, "CfgTotpSetup");
1878
- }
1879
- /**
1880
- * Start 2FA setup process.
1881
- *
1882
- * Creates a new TOTP device and returns QR code for scanning.
1883
- */
1884
- static cfgTotpSetupCreate(options) {
1885
- return (options?.client ?? client).post({
1886
- security: [{ name: "X-API-Key", type: "apiKey" }, { scheme: "bearer", type: "http" }],
1887
- url: "/cfg/totp/setup/",
1888
- ...options,
1889
- headers: {
1890
- "Content-Type": "application/json",
1891
- ...options?.headers
1892
- }
1893
- });
1894
- }
1895
- /**
1896
- * Confirm 2FA setup with first valid code.
1897
- *
1898
- * Activates the device and generates backup codes.
1899
- */
1900
- static cfgTotpSetupConfirmCreate(options) {
1901
- return (options.client ?? client).post({
1902
- security: [{ name: "X-API-Key", type: "apiKey" }, { scheme: "bearer", type: "http" }],
1903
- url: "/cfg/totp/setup/confirm/",
1904
- ...options,
1905
- headers: {
1906
- "Content-Type": "application/json",
1907
- ...options.headers
1908
- }
1909
- });
1910
- }
1911
- };
1912
- var CfgTotpVerify = class {
1913
- static {
1914
- __name(this, "CfgTotpVerify");
1915
- }
1916
- /**
1917
- * Verify TOTP code for 2FA session.
1918
- *
1919
- * Completes authentication and returns JWT tokens on success.
1920
- */
1921
- static cfgTotpVerifyCreate(options) {
1922
- return (options.client ?? client).post({
1923
- security: [{ name: "X-API-Key", type: "apiKey" }, { scheme: "bearer", type: "http" }],
1924
- url: "/cfg/totp/verify/",
1925
- ...options,
1926
- headers: {
1927
- "Content-Type": "application/json",
1928
- ...options.headers
1929
- }
1930
- });
1931
- }
1932
- /**
1933
- * Verify backup recovery code for 2FA session.
1934
- *
1935
- * Alternative verification method when TOTP device unavailable.
1936
- */
1937
- static cfgTotpVerifyBackupCreate(options) {
1938
- return (options.client ?? client).post({
1939
- security: [{ name: "X-API-Key", type: "apiKey" }, { scheme: "bearer", type: "http" }],
1940
- url: "/cfg/totp/verify/backup/",
1941
- ...options,
1942
- headers: {
1943
- "Content-Type": "application/json",
1944
- ...options.headers
1945
- }
1946
- });
1947
- }
1948
- };
1949
-
1950
- // src/_api/generated/_cfg_accounts/api.ts
1951
- var API = class {
1952
- static {
1953
- __name(this, "API");
1954
- }
1955
- logger;
1956
- cfgAccountsApiKey = CfgAccountsApiKey;
1957
- cfgAccountsOauth = CfgAccountsOauth;
1958
- cfgAccounts = CfgAccounts;
1959
- cfgAccountsProfile = CfgAccountsProfile;
1960
- cfgAccountsAuth = CfgAccountsAuth;
1961
- constructor(_baseUrl, opts = {}) {
1962
- this.logger = new APILogger(opts.logger);
1963
- if (_baseUrl) auth.setBaseUrl(_baseUrl);
1964
- if (opts.locale !== void 0) auth.setLocale(opts.locale);
1965
- if (opts.apiKey !== void 0) auth.setApiKey(opts.apiKey);
1966
- if (opts.withCredentials !== void 0) auth.setWithCredentials(opts.withCredentials);
1967
- }
1968
- // ── Base URL ────────────────────────────────────────────────────────────
1969
- getBaseUrl() {
1970
- return auth.getBaseUrl();
1971
- }
1972
- setBaseUrl(url) {
1973
- auth.setBaseUrl(url);
1974
- }
1975
- // ── Tokens ──────────────────────────────────────────────────────────────
1976
- getToken() {
1977
- return auth.getToken();
1978
- }
1979
- setToken(token) {
1980
- auth.setToken(token);
1981
- }
1982
- getRefreshToken() {
1983
- return auth.getRefreshToken();
1984
- }
1985
- setRefreshToken(token) {
1986
- auth.setRefreshToken(token);
1987
- }
1988
- clearToken() {
1989
- auth.clearTokens();
1990
- }
1991
- isAuthenticated() {
1992
- return auth.isAuthenticated();
1993
- }
1994
- // ── Locale / API key ────────────────────────────────────────────────────
1995
- getLocale() {
1996
- return auth.getLocale();
1997
- }
1998
- setLocale(locale) {
1999
- auth.setLocale(locale);
2000
- }
2001
- getApiKey() {
2002
- return auth.getApiKey();
2003
- }
2004
- setApiKey(key) {
2005
- auth.setApiKey(key);
2006
- }
2007
- // ── 401 handling ────────────────────────────────────────────────────────
2008
- /** Fired only on terminal 401 (after refresh+retry path is exhausted). */
2009
- onUnauthorized(cb) {
2010
- auth.onUnauthorized(cb);
2011
- }
2012
- /** Provide a refresh strategy. See `auth.setRefreshHandler` for the contract. */
2013
- setRefreshHandler(fn) {
2014
- auth.setRefreshHandler(fn);
2015
- }
2016
- };
2017
-
2018
- // src/_api/generated/_cfg_centrifugo/api.ts
2019
- var API2 = class {
2020
- static {
2021
- __name(this, "API");
2022
- }
2023
- logger;
2024
- cfgCentrifugo = CfgCentrifugo;
2025
- constructor(_baseUrl, opts = {}) {
2026
- this.logger = new APILogger(opts.logger);
2027
- if (_baseUrl) auth.setBaseUrl(_baseUrl);
2028
- if (opts.locale !== void 0) auth.setLocale(opts.locale);
2029
- if (opts.apiKey !== void 0) auth.setApiKey(opts.apiKey);
2030
- if (opts.withCredentials !== void 0) auth.setWithCredentials(opts.withCredentials);
2031
- }
2032
- // ── Base URL ────────────────────────────────────────────────────────────
2033
- getBaseUrl() {
2034
- return auth.getBaseUrl();
2035
- }
2036
- setBaseUrl(url) {
2037
- auth.setBaseUrl(url);
2038
- }
2039
- // ── Tokens ──────────────────────────────────────────────────────────────
2040
- getToken() {
2041
- return auth.getToken();
2042
- }
2043
- setToken(token) {
2044
- auth.setToken(token);
2045
- }
2046
- getRefreshToken() {
2047
- return auth.getRefreshToken();
2048
- }
2049
- setRefreshToken(token) {
2050
- auth.setRefreshToken(token);
2051
- }
2052
- clearToken() {
2053
- auth.clearTokens();
2054
- }
2055
- isAuthenticated() {
2056
- return auth.isAuthenticated();
2057
- }
2058
- // ── Locale / API key ────────────────────────────────────────────────────
2059
- getLocale() {
2060
- return auth.getLocale();
2061
- }
2062
- setLocale(locale) {
2063
- auth.setLocale(locale);
2064
- }
2065
- getApiKey() {
2066
- return auth.getApiKey();
2067
- }
2068
- setApiKey(key) {
2069
- auth.setApiKey(key);
2070
- }
2071
- // ── 401 handling ────────────────────────────────────────────────────────
2072
- /** Fired only on terminal 401 (after refresh+retry path is exhausted). */
2073
- onUnauthorized(cb) {
2074
- auth.onUnauthorized(cb);
2075
- }
2076
- /** Provide a refresh strategy. See `auth.setRefreshHandler` for the contract. */
2077
- setRefreshHandler(fn) {
2078
- auth.setRefreshHandler(fn);
2079
- }
2080
- };
2081
-
2082
- // src/_api/generated/_cfg_totp/api.ts
2083
- var API3 = class {
2084
- static {
2085
- __name(this, "API");
2086
- }
2087
- logger;
2088
- cfgTotpBackupCodes = CfgTotpBackupCodes;
2089
- cfgTotp = CfgTotp;
2090
- cfgTotpSetup = CfgTotpSetup;
2091
- cfgTotpVerify = CfgTotpVerify;
2092
- constructor(_baseUrl, opts = {}) {
2093
- this.logger = new APILogger(opts.logger);
2094
- if (_baseUrl) auth.setBaseUrl(_baseUrl);
2095
- if (opts.locale !== void 0) auth.setLocale(opts.locale);
2096
- if (opts.apiKey !== void 0) auth.setApiKey(opts.apiKey);
2097
- if (opts.withCredentials !== void 0) auth.setWithCredentials(opts.withCredentials);
2098
- }
2099
- // ── Base URL ────────────────────────────────────────────────────────────
2100
- getBaseUrl() {
2101
- return auth.getBaseUrl();
2102
- }
2103
- setBaseUrl(url) {
2104
- auth.setBaseUrl(url);
2105
- }
2106
- // ── Tokens ──────────────────────────────────────────────────────────────
2107
- getToken() {
2108
- return auth.getToken();
2109
- }
2110
- setToken(token) {
2111
- auth.setToken(token);
2112
- }
2113
- getRefreshToken() {
2114
- return auth.getRefreshToken();
2115
- }
2116
- setRefreshToken(token) {
2117
- auth.setRefreshToken(token);
2118
- }
2119
- clearToken() {
2120
- auth.clearTokens();
2121
- }
2122
- isAuthenticated() {
2123
- return auth.isAuthenticated();
2124
- }
2125
- // ── Locale / API key ────────────────────────────────────────────────────
2126
- getLocale() {
2127
- return auth.getLocale();
2128
- }
2129
- setLocale(locale) {
2130
- auth.setLocale(locale);
2131
- }
2132
- getApiKey() {
2133
- return auth.getApiKey();
2134
- }
2135
- setApiKey(key) {
2136
- auth.setApiKey(key);
2137
- }
2138
- // ── 401 handling ────────────────────────────────────────────────────────
2139
- /** Fired only on terminal 401 (after refresh+retry path is exhausted). */
2140
- onUnauthorized(cb) {
2141
- auth.onUnauthorized(cb);
2142
- }
2143
- /** Provide a refresh strategy. See `auth.setRefreshHandler` for the contract. */
2144
- setRefreshHandler(fn) {
2145
- auth.setRefreshHandler(fn);
2146
- }
2147
- };
2148
-
2149
- // src/_api/generated/index.ts
2150
- var CfgAccountsApi = new API();
2151
- var CfgCentrifugoApi = new API2();
2152
- var CfgTotpApi = new API3();
2153
-
2154
- // src/auth/utils/env.ts
2155
- var isDev = process.env.NODE_ENV === "development";
2156
- var isStaticBuild = process.env.NEXT_PUBLIC_STATIC_BUILD === "true";
2157
- var dpopEnabled2 = process.env.NEXT_PUBLIC_DPOP_ENABLED === "true";
2158
-
2159
- // src/log-control.ts
2160
- var verboseByDefault = isDev || isStaticBuild;
2161
- var DEFAULT_LEVEL = verboseByDefault ? 4 : 1;
2162
- var _level = DEFAULT_LEVEL;
2163
- var _subscribers = /* @__PURE__ */ new Set();
2164
- function getLogLevel() {
2165
- return _level;
2166
- }
2167
- __name(getLogLevel, "getLogLevel");
2168
- function onLogLevelChange(fn) {
2169
- _subscribers.add(fn);
2170
- try {
2171
- fn(_level);
2172
- } catch {
2173
- }
2174
- return () => _subscribers.delete(fn);
2175
- }
2176
- __name(onLogLevelChange, "onLogLevelChange");
2177
-
2178
- // src/auth/utils/logger.ts
2179
- import { createConsola as createConsola2 } from "consola";
2180
- var logger = createConsola2({
2181
- level: getLogLevel()
2182
- }).withTag("api");
2183
- onLogLevelChange((level) => {
2184
- logger.level = level;
2185
- });
2186
- var authLogger = logger.withTag("auth");
2187
-
2188
- // src/auth/middlewares/tokenRefresh.ts
2189
- var isRefreshing = false;
2190
- var refreshSubscribers = [];
2191
- function subscribeTokenRefresh(callback) {
2192
- refreshSubscribers.push(callback);
2193
- }
2194
- __name(subscribeTokenRefresh, "subscribeTokenRefresh");
2195
- function onTokenRefreshed(token) {
2196
- refreshSubscribers.forEach((callback) => callback(token));
2197
- refreshSubscribers = [];
2198
- }
2199
- __name(onTokenRefreshed, "onTokenRefreshed");
2200
- async function refreshAccessToken() {
2201
- if (isRefreshing) {
2202
- return new Promise((resolve) => {
2203
- subscribeTokenRefresh((token) => resolve(token));
2204
- });
2205
- }
2206
- isRefreshing = true;
2207
- authLogger.info("Starting token refresh...");
2208
- try {
2209
- const refreshToken = CfgAccountsApi.getRefreshToken();
2210
- if (!refreshToken) {
2211
- authLogger.warn("No refresh token available for refresh");
2212
- onTokenRefreshed(null);
2213
- return null;
2214
- }
2215
- const result = await CfgAccountsAuth.cfgAccountsTokenRefreshCreate({
2216
- body: { refresh: refreshToken },
2217
- throwOnError: true
2218
- });
2219
- const newAccessToken = result.data.access;
2220
- if (!newAccessToken) {
2221
- authLogger.error("Token refresh response missing access token");
2222
- onTokenRefreshed(null);
2223
- return null;
2224
- }
2225
- CfgAccountsApi.setToken(newAccessToken);
2226
- CfgAccountsApi.setRefreshToken(refreshToken);
2227
- authLogger.info("Token refreshed successfully");
2228
- onTokenRefreshed(newAccessToken);
2229
- return newAccessToken;
2230
- } catch (error) {
2231
- authLogger.error("Token refresh error:", error);
2232
- onTokenRefreshed(null);
2233
- return null;
2234
- } finally {
2235
- isRefreshing = false;
2236
- }
2237
- }
2238
- __name(refreshAccessToken, "refreshAccessToken");
2239
- function isAuthenticationError(response) {
2240
- return response.status === 401;
2241
- }
2242
- __name(isAuthenticationError, "isAuthenticationError");
2243
- function createAutoRefreshFetch(originalFetch) {
2244
- return async (input, init) => {
2245
- let response = await originalFetch(input, init);
2246
- if (isAuthenticationError(response) && CfgAccountsApi.getRefreshToken()) {
2247
- authLogger.info("Received 401, attempting token refresh...");
2248
- const newToken = await refreshAccessToken();
2249
- if (newToken) {
2250
- const newInit = {
2251
- ...init,
2252
- headers: {
2253
- ...init?.headers,
2254
- Authorization: `Bearer ${newToken}`
2255
- }
2256
- };
2257
- authLogger.info("Retrying request with new token...");
2258
- response = await originalFetch(input, newInit);
2259
- } else {
2260
- authLogger.warn("Token refresh failed, returning original 401 response");
2261
- }
2262
- }
2263
- return response;
2264
- };
2265
- }
2266
- __name(createAutoRefreshFetch, "createAutoRefreshFetch");
2267
- function isTokenExpiringSoon(thresholdMs = 5 * 60 * 1e3) {
2268
- const token = CfgAccountsApi.getToken();
2269
- if (!token) return false;
2270
- try {
2271
- const payload = JSON.parse(atob(token.split(".")[1]));
2272
- const expiresAt = payload.exp * 1e3;
2273
- const now = Date.now();
2274
- const timeUntilExpiry = expiresAt - now;
2275
- return timeUntilExpiry < thresholdMs;
2276
- } catch (error) {
2277
- authLogger.error("Error checking token expiry:", error);
2278
- return false;
2279
- }
2280
- }
2281
- __name(isTokenExpiringSoon, "isTokenExpiringSoon");
2282
- async function refreshIfExpiringSoon(thresholdMs = 5 * 60 * 1e3) {
2283
- if (isTokenExpiringSoon(thresholdMs)) {
2284
- authLogger.info("Token expiring soon, proactively refreshing...");
2285
- await refreshAccessToken();
2286
- }
2287
- }
2288
- __name(refreshIfExpiringSoon, "refreshIfExpiringSoon");
2289
23
  export {
2290
- createAutoRefreshFetch,
2291
- isAuthenticationError,
2292
- isTokenExpiringSoon,
2293
24
  proxyMiddleware,
2294
- proxyMiddlewareConfig,
2295
- refreshAccessToken,
2296
- refreshIfExpiringSoon
25
+ proxyMiddlewareConfig
2297
26
  };
2298
27
  //# sourceMappingURL=auth-server.mjs.map