@djangocfg/api 2.1.138 → 2.1.140

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 (48) hide show
  1. package/dist/auth-server.cjs +2 -199
  2. package/dist/auth-server.cjs.map +1 -1
  3. package/dist/auth-server.mjs +2 -199
  4. package/dist/auth-server.mjs.map +1 -1
  5. package/dist/auth.cjs +11 -836
  6. package/dist/auth.cjs.map +1 -1
  7. package/dist/auth.mjs +11 -836
  8. package/dist/auth.mjs.map +1 -1
  9. package/dist/clients.cjs +40 -1077
  10. package/dist/clients.cjs.map +1 -1
  11. package/dist/clients.d.cts +209 -754
  12. package/dist/clients.d.ts +209 -754
  13. package/dist/clients.mjs +40 -1077
  14. package/dist/clients.mjs.map +1 -1
  15. package/dist/index.cjs +0 -1198
  16. package/dist/index.cjs.map +1 -1
  17. package/dist/index.d.cts +229 -1211
  18. package/dist/index.d.ts +229 -1211
  19. package/dist/index.mjs +0 -1198
  20. package/dist/index.mjs.map +1 -1
  21. package/package.json +2 -2
  22. package/src/clients.ts +2 -12
  23. package/src/index.ts +0 -6
  24. package/src/generated/cfg_webpush/CLAUDE.md +0 -63
  25. package/src/generated/cfg_webpush/_utils/fetchers/index.ts +0 -29
  26. package/src/generated/cfg_webpush/_utils/fetchers/webpush__web_push.ts +0 -211
  27. package/src/generated/cfg_webpush/_utils/hooks/index.ts +0 -29
  28. package/src/generated/cfg_webpush/_utils/hooks/webpush__web_push.ts +0 -79
  29. package/src/generated/cfg_webpush/_utils/schemas/SendPushRequestRequest.schema.ts +0 -22
  30. package/src/generated/cfg_webpush/_utils/schemas/SendPushResponse.schema.ts +0 -20
  31. package/src/generated/cfg_webpush/_utils/schemas/SubscribeRequestRequest.schema.ts +0 -20
  32. package/src/generated/cfg_webpush/_utils/schemas/SubscribeResponse.schema.ts +0 -21
  33. package/src/generated/cfg_webpush/_utils/schemas/VapidPublicKeyResponse.schema.ts +0 -19
  34. package/src/generated/cfg_webpush/_utils/schemas/index.ts +0 -24
  35. package/src/generated/cfg_webpush/api-instance.ts +0 -180
  36. package/src/generated/cfg_webpush/client.ts +0 -322
  37. package/src/generated/cfg_webpush/errors.ts +0 -117
  38. package/src/generated/cfg_webpush/http.ts +0 -110
  39. package/src/generated/cfg_webpush/index.ts +0 -275
  40. package/src/generated/cfg_webpush/logger.ts +0 -260
  41. package/src/generated/cfg_webpush/retry.ts +0 -176
  42. package/src/generated/cfg_webpush/schema.json +0 -302
  43. package/src/generated/cfg_webpush/storage.ts +0 -162
  44. package/src/generated/cfg_webpush/validation-events.ts +0 -134
  45. package/src/generated/cfg_webpush/webpush__web_push/client.ts +0 -45
  46. package/src/generated/cfg_webpush/webpush__web_push/index.ts +0 -3
  47. package/src/generated/cfg_webpush/webpush__web_push/models.ts +0 -65
  48. package/src/hooks/webpush.ts +0 -12
@@ -1,110 +0,0 @@
1
- // Auto-generated by DjangoCFG - see CLAUDE.md
2
- /**
3
- * HTTP Client Adapter Pattern
4
- *
5
- * Allows switching between fetch/axios/httpx without changing generated code.
6
- * Provides unified interface for making HTTP requests.
7
- */
8
-
9
- export interface HttpRequest {
10
- method: string;
11
- url: string;
12
- headers?: Record<string, string>;
13
- body?: any;
14
- params?: Record<string, any>;
15
- /** FormData for file uploads (multipart/form-data) */
16
- formData?: FormData;
17
- /** Binary data for octet-stream uploads */
18
- binaryBody?: Blob | ArrayBuffer;
19
- }
20
-
21
- export interface HttpResponse<T = any> {
22
- data: T;
23
- status: number;
24
- statusText: string;
25
- headers: Record<string, string>;
26
- }
27
-
28
- /**
29
- * HTTP Client Adapter Interface.
30
- * Implement this to use custom HTTP clients (axios, httpx, etc.)
31
- */
32
- export interface HttpClientAdapter {
33
- request<T = any>(request: HttpRequest): Promise<HttpResponse<T>>;
34
- }
35
-
36
- /**
37
- * Default Fetch API adapter.
38
- * Uses native browser fetch() with proper error handling.
39
- */
40
- export class FetchAdapter implements HttpClientAdapter {
41
- async request<T = any>(request: HttpRequest): Promise<HttpResponse<T>> {
42
- const { method, url, headers, body, params, formData, binaryBody } = request;
43
-
44
- // Build URL with query params
45
- let finalUrl = url;
46
- if (params) {
47
- const searchParams = new URLSearchParams();
48
- Object.entries(params).forEach(([key, value]) => {
49
- if (value !== null && value !== undefined) {
50
- searchParams.append(key, String(value));
51
- }
52
- });
53
- const queryString = searchParams.toString();
54
- if (queryString) {
55
- finalUrl = url.includes('?') ? `${url}&${queryString}` : `${url}?${queryString}`;
56
- }
57
- }
58
-
59
- // Build headers
60
- const finalHeaders: Record<string, string> = { ...headers };
61
-
62
- // Determine body and content-type
63
- let requestBody: string | FormData | Blob | ArrayBuffer | undefined;
64
-
65
- if (formData) {
66
- // For multipart/form-data, let browser set Content-Type with boundary
67
- requestBody = formData;
68
- // Don't set Content-Type - browser will set it with boundary
69
- } else if (binaryBody) {
70
- // Binary upload (application/octet-stream)
71
- finalHeaders['Content-Type'] = 'application/octet-stream';
72
- requestBody = binaryBody;
73
- } else if (body) {
74
- // JSON request
75
- finalHeaders['Content-Type'] = 'application/json';
76
- requestBody = JSON.stringify(body);
77
- }
78
-
79
- // Make request
80
- const response = await fetch(finalUrl, {
81
- method,
82
- headers: finalHeaders,
83
- body: requestBody,
84
- credentials: 'include', // Include Django session cookies
85
- });
86
-
87
- // Parse response
88
- let data: any = null;
89
- const contentType = response.headers.get('content-type');
90
-
91
- if (response.status !== 204 && contentType?.includes('application/json')) {
92
- data = await response.json();
93
- } else if (response.status !== 204) {
94
- data = await response.text();
95
- }
96
-
97
- // Convert Headers to plain object
98
- const responseHeaders: Record<string, string> = {};
99
- response.headers.forEach((value, key) => {
100
- responseHeaders[key] = value;
101
- });
102
-
103
- return {
104
- data,
105
- status: response.status,
106
- statusText: response.statusText,
107
- headers: responseHeaders,
108
- };
109
- }
110
- }
@@ -1,275 +0,0 @@
1
- // Auto-generated by DjangoCFG - see CLAUDE.md
2
- /**
3
- * Django CFG API - API Client with JWT Management
4
- *
5
- * Usage:
6
- * ```typescript
7
- * import { API } from './api';
8
- *
9
- * const api = new API('https://api.example.com');
10
- *
11
- * // Set JWT token
12
- * api.setToken('your-jwt-token', 'refresh-token');
13
- *
14
- * // Use API
15
- * const posts = await api.posts.list();
16
- * const user = await api.users.retrieve(1);
17
- *
18
- * // Check authentication
19
- * if (api.isAuthenticated()) {
20
- * // ...
21
- * }
22
- *
23
- * // Custom storage with logging (for Electron/Node.js)
24
- * import { MemoryStorageAdapter, APILogger } from './storage';
25
- * const logger = new APILogger({ enabled: true, logLevel: 'debug' });
26
- * const api = new API('https://api.example.com', {
27
- * storage: new MemoryStorageAdapter(logger),
28
- * loggerConfig: { enabled: true, logLevel: 'debug' }
29
- * });
30
- *
31
- * // Get OpenAPI schema
32
- * const schema = api.getSchema();
33
- * ```
34
- */
35
-
36
- import { APIClient } from "./client";
37
- import {
38
- StorageAdapter,
39
- LocalStorageAdapter,
40
- CookieStorageAdapter,
41
- MemoryStorageAdapter
42
- } from "./storage";
43
- import type { RetryConfig } from "./retry";
44
- import type { LoggerConfig } from "./logger";
45
- import { APILogger } from "./logger";
46
- import { WebPush } from "./webpush__web_push/client";
47
- export * as WebPushTypes from "./webpush__web_push/models";
48
- // Note: Direct exports (export * from) are removed to avoid duplicate type conflicts
49
- // Use namespace exports like CfgAccountsTypes.User or import from specific modules
50
-
51
- // Re-export Zod schemas for runtime validation
52
- export * as Schemas from "./_utils/schemas";
53
- // Also export all schemas directly for convenience
54
- export * from "./_utils/schemas";
55
-
56
- // Re-export Zod validation events for browser integration
57
- export type { ValidationErrorDetail, ValidationErrorEvent } from "./validation-events";
58
- export { dispatchValidationError, onValidationError, formatZodError } from "./validation-events";
59
-
60
- // Re-export typed fetchers for universal usage
61
- export * as Fetchers from "./_utils/fetchers";
62
- export * from "./_utils/fetchers";
63
-
64
- // Re-export API instance configuration functions
65
- export {
66
- configureAPI,
67
- getAPIInstance,
68
- reconfigureAPI,
69
- clearAPITokens,
70
- resetAPI,
71
- isAPIConfigured
72
- } from "./api-instance";
73
- // NOTE: SWR hooks are generated in ./_utils/hooks/ but NOT exported here to keep
74
- // the main bundle server-safe. Import hooks directly from the hooks directory:
75
- // import { useUsers } from './_utils/hooks';
76
- // Or use a separate entry point like '@djangocfg/api/hooks' for client components.
77
-
78
- // Re-export core client
79
- export { APIClient };
80
-
81
- // Re-export storage adapters for convenience
82
- export type { StorageAdapter };
83
- export { LocalStorageAdapter, CookieStorageAdapter, MemoryStorageAdapter };
84
-
85
- // Re-export error classes for convenience
86
- export { APIError, NetworkError } from "./errors";
87
-
88
- // Re-export HTTP adapters for custom implementations
89
- export type { HttpClientAdapter, HttpRequest, HttpResponse } from "./http";
90
- export { FetchAdapter } from "./http";
91
-
92
- // Re-export logger types and classes
93
- export type { LoggerConfig, RequestLog, ResponseLog, ErrorLog } from "./logger";
94
- export { APILogger } from "./logger";
95
-
96
- // Re-export retry configuration and utilities
97
- export type { RetryConfig, FailedAttemptInfo } from "./retry";
98
- export { withRetry, shouldRetry, DEFAULT_RETRY_CONFIG } from "./retry";
99
-
100
- export const TOKEN_KEY = "auth_token";
101
- export const REFRESH_TOKEN_KEY = "refresh_token";
102
-
103
- export interface APIOptions {
104
- /** Custom storage adapter (defaults to LocalStorageAdapter) */
105
- storage?: StorageAdapter;
106
- /** Retry configuration for failed requests */
107
- retryConfig?: RetryConfig;
108
- /** Logger configuration */
109
- loggerConfig?: Partial<LoggerConfig>;
110
- }
111
-
112
- export class API {
113
- private baseUrl: string;
114
- private _client: APIClient;
115
- private _token: string | null = null;
116
- private _refreshToken: string | null = null;
117
- private storage: StorageAdapter;
118
- private options?: APIOptions;
119
-
120
- // Sub-clients
121
- public web_push!: WebPush;
122
-
123
- constructor(baseUrl: string, options?: APIOptions) {
124
- this.baseUrl = baseUrl;
125
- this.options = options;
126
-
127
- // Create logger if config provided
128
- const logger = options?.loggerConfig ? new APILogger(options.loggerConfig) : undefined;
129
-
130
- // Initialize storage with logger
131
- this.storage = options?.storage || new LocalStorageAdapter(logger);
132
-
133
- this._loadTokensFromStorage();
134
-
135
- // Initialize APIClient with token getter for URL authentication
136
- this._client = new APIClient(this.baseUrl, {
137
- retryConfig: this.options?.retryConfig,
138
- loggerConfig: this.options?.loggerConfig,
139
- tokenGetter: () => this.getToken(),
140
- });
141
-
142
- // Always inject auth header wrapper (reads token dynamically from storage)
143
- this._injectAuthHeader();
144
-
145
- // Initialize sub-clients from APIClient
146
- this.web_push = this._client.web_push;
147
- }
148
-
149
- private _loadTokensFromStorage(): void {
150
- this._token = this.storage.getItem(TOKEN_KEY);
151
- this._refreshToken = this.storage.getItem(REFRESH_TOKEN_KEY);
152
- }
153
-
154
- private _reinitClients(): void {
155
- this._client = new APIClient(this.baseUrl, {
156
- retryConfig: this.options?.retryConfig,
157
- loggerConfig: this.options?.loggerConfig,
158
- tokenGetter: () => this.getToken(),
159
- });
160
-
161
- // Always inject auth header wrapper (reads token dynamically from storage)
162
- this._injectAuthHeader();
163
-
164
- // Reinitialize sub-clients
165
- this.web_push = this._client.web_push;
166
- }
167
-
168
- private _injectAuthHeader(): void {
169
- // Override request method to inject auth header
170
- const originalRequest = this._client.request.bind(this._client);
171
- this._client.request = async <T>(
172
- method: string,
173
- path: string,
174
- options?: { params?: Record<string, any>; body?: any; formData?: FormData; headers?: Record<string, string> }
175
- ): Promise<T> => {
176
- // Read token from storage dynamically (supports JWT injection after instantiation)
177
- const token = this.getToken();
178
- const mergedOptions = {
179
- ...options,
180
- headers: {
181
- ...(options?.headers || {}),
182
- ...(token ? { 'Authorization': `Bearer ${token}` } : {}),
183
- },
184
- };
185
-
186
- return originalRequest(method, path, mergedOptions);
187
- };
188
- }
189
-
190
- /**
191
- * Get current JWT token
192
- */
193
- getToken(): string | null {
194
- return this.storage.getItem(TOKEN_KEY);
195
- }
196
-
197
- /**
198
- * Get current refresh token
199
- */
200
- getRefreshToken(): string | null {
201
- return this.storage.getItem(REFRESH_TOKEN_KEY);
202
- }
203
-
204
- /**
205
- * Set JWT token and refresh token
206
- * @param token - JWT access token
207
- * @param refreshToken - JWT refresh token (optional)
208
- */
209
- setToken(token: string, refreshToken?: string): void {
210
- this._token = token;
211
- this.storage.setItem(TOKEN_KEY, token);
212
-
213
- if (refreshToken) {
214
- this._refreshToken = refreshToken;
215
- this.storage.setItem(REFRESH_TOKEN_KEY, refreshToken);
216
- }
217
-
218
- // Reinitialize clients with new token
219
- this._reinitClients();
220
- }
221
-
222
- /**
223
- * Clear all tokens
224
- */
225
- clearTokens(): void {
226
- this._token = null;
227
- this._refreshToken = null;
228
- this.storage.removeItem(TOKEN_KEY);
229
- this.storage.removeItem(REFRESH_TOKEN_KEY);
230
-
231
- // Reinitialize clients without token
232
- this._reinitClients();
233
- }
234
-
235
- /**
236
- * Check if user is authenticated
237
- */
238
- isAuthenticated(): boolean {
239
- return !!this.getToken();
240
- }
241
-
242
- /**
243
- * Update base URL and reinitialize clients
244
- * @param url - New base URL
245
- */
246
- setBaseUrl(url: string): void {
247
- this.baseUrl = url;
248
- this._reinitClients();
249
- }
250
-
251
- /**
252
- * Get current base URL
253
- */
254
- getBaseUrl(): string {
255
- return this.baseUrl;
256
- }
257
-
258
- /**
259
- * Get OpenAPI schema path
260
- * @returns Path to the OpenAPI schema JSON file
261
- *
262
- * Note: The OpenAPI schema is available in the schema.json file.
263
- * You can load it dynamically using:
264
- * ```typescript
265
- * const schema = await fetch('./schema.json').then(r => r.json());
266
- * // or using fs in Node.js:
267
- * // const schema = JSON.parse(fs.readFileSync('./schema.json', 'utf-8'));
268
- * ```
269
- */
270
- getSchemaPath(): string {
271
- return './schema.json';
272
- }
273
- }
274
-
275
- export default API;
@@ -1,260 +0,0 @@
1
- // Auto-generated by DjangoCFG - see CLAUDE.md
2
- /**
3
- * API Logger with Consola
4
- * Beautiful console logging for API requests and responses
5
- *
6
- * Installation:
7
- * npm install consola
8
- */
9
-
10
- import { type ConsolaInstance, createConsola } from 'consola';
11
-
12
- /**
13
- * Request log data
14
- */
15
- export interface RequestLog {
16
- method: string;
17
- url: string;
18
- headers?: Record<string, string>;
19
- body?: any;
20
- timestamp: number;
21
- }
22
-
23
- /**
24
- * Response log data
25
- */
26
- export interface ResponseLog {
27
- status: number;
28
- statusText: string;
29
- data?: any;
30
- duration: number;
31
- timestamp: number;
32
- }
33
-
34
- /**
35
- * Error log data
36
- */
37
- export interface ErrorLog {
38
- message: string;
39
- statusCode?: number;
40
- fieldErrors?: Record<string, string[]>;
41
- duration: number;
42
- timestamp: number;
43
- }
44
-
45
- /**
46
- * Logger configuration
47
- */
48
- export interface LoggerConfig {
49
- /** Enable logging */
50
- enabled: boolean;
51
- /** Log requests */
52
- logRequests: boolean;
53
- /** Log responses */
54
- logResponses: boolean;
55
- /** Log errors */
56
- logErrors: boolean;
57
- /** Log request/response bodies */
58
- logBodies: boolean;
59
- /** Log headers (excluding sensitive ones) */
60
- logHeaders: boolean;
61
- /** Custom consola instance */
62
- consola?: ConsolaInstance;
63
- }
64
-
65
- /**
66
- * Default logger configuration
67
- */
68
- const DEFAULT_CONFIG: LoggerConfig = {
69
- enabled: process.env.NODE_ENV !== 'production',
70
- logRequests: true,
71
- logResponses: true,
72
- logErrors: true,
73
- logBodies: true,
74
- logHeaders: false,
75
- };
76
-
77
- /**
78
- * Sensitive header names to filter out
79
- */
80
- const SENSITIVE_HEADERS = [
81
- 'authorization',
82
- 'cookie',
83
- 'set-cookie',
84
- 'x-api-key',
85
- 'x-csrf-token',
86
- ];
87
-
88
- /**
89
- * API Logger class
90
- */
91
- export class APILogger {
92
- private config: LoggerConfig;
93
- private consola: ConsolaInstance;
94
-
95
- constructor(config: Partial<LoggerConfig> = {}) {
96
- this.config = { ...DEFAULT_CONFIG, ...config };
97
- this.consola = config.consola || createConsola({
98
- level: this.config.enabled ? 4 : 0,
99
- });
100
- }
101
-
102
- /**
103
- * Enable logging
104
- */
105
- enable(): void {
106
- this.config.enabled = true;
107
- }
108
-
109
- /**
110
- * Disable logging
111
- */
112
- disable(): void {
113
- this.config.enabled = false;
114
- }
115
-
116
- /**
117
- * Update configuration
118
- */
119
- setConfig(config: Partial<LoggerConfig>): void {
120
- this.config = { ...this.config, ...config };
121
- }
122
-
123
- /**
124
- * Filter sensitive headers
125
- */
126
- private filterHeaders(headers?: Record<string, string>): Record<string, string> {
127
- if (!headers) return {};
128
-
129
- const filtered: Record<string, string> = {};
130
- Object.keys(headers).forEach((key) => {
131
- const lowerKey = key.toLowerCase();
132
- if (SENSITIVE_HEADERS.includes(lowerKey)) {
133
- filtered[key] = '***';
134
- } else {
135
- filtered[key] = headers[key] || '';
136
- }
137
- });
138
-
139
- return filtered;
140
- }
141
-
142
- /**
143
- * Log request
144
- */
145
- logRequest(request: RequestLog): void {
146
- if (!this.config.enabled || !this.config.logRequests) return;
147
-
148
- const { method, url, headers, body } = request;
149
-
150
- this.consola.start(`${method} ${url}`);
151
-
152
- if (this.config.logHeaders && headers) {
153
- this.consola.debug('Headers:', this.filterHeaders(headers));
154
- }
155
-
156
- if (this.config.logBodies && body) {
157
- this.consola.debug('Body:', body);
158
- }
159
- }
160
-
161
- /**
162
- * Log response
163
- */
164
- logResponse(request: RequestLog, response: ResponseLog): void {
165
- if (!this.config.enabled || !this.config.logResponses) return;
166
-
167
- const { method, url } = request;
168
- const { status, statusText, data, duration } = response;
169
-
170
- const statusColor = status >= 500 ? 'red'
171
- : status >= 400 ? 'yellow'
172
- : status >= 300 ? 'cyan'
173
- : 'green';
174
-
175
- this.consola.success(
176
- `${method} ${url} ${status} ${statusText} (${duration}ms)`
177
- );
178
-
179
- if (this.config.logBodies && data) {
180
- this.consola.debug('Response:', data);
181
- }
182
- }
183
-
184
- /**
185
- * Log error
186
- */
187
- logError(request: RequestLog, error: ErrorLog): void {
188
- if (!this.config.enabled || !this.config.logErrors) return;
189
-
190
- const { method, url } = request;
191
- const { message, statusCode, fieldErrors, duration } = error;
192
-
193
- this.consola.error(
194
- `${method} ${url} ${statusCode || 'Network'} Error (${duration}ms)`
195
- );
196
-
197
- this.consola.error('Message:', message);
198
-
199
- if (fieldErrors && Object.keys(fieldErrors).length > 0) {
200
- this.consola.error('Field Errors:');
201
- Object.entries(fieldErrors).forEach(([field, errors]) => {
202
- errors.forEach((err) => {
203
- this.consola.error(` • ${field}: ${err}`);
204
- });
205
- });
206
- }
207
- }
208
-
209
- /**
210
- * Log general info
211
- */
212
- info(message: string, ...args: any[]): void {
213
- if (!this.config.enabled) return;
214
- this.consola.info(message, ...args);
215
- }
216
-
217
- /**
218
- * Log warning
219
- */
220
- warn(message: string, ...args: any[]): void {
221
- if (!this.config.enabled) return;
222
- this.consola.warn(message, ...args);
223
- }
224
-
225
- /**
226
- * Log error
227
- */
228
- error(message: string, ...args: any[]): void {
229
- if (!this.config.enabled) return;
230
- this.consola.error(message, ...args);
231
- }
232
-
233
- /**
234
- * Log debug
235
- */
236
- debug(message: string, ...args: any[]): void {
237
- if (!this.config.enabled) return;
238
- this.consola.debug(message, ...args);
239
- }
240
-
241
- /**
242
- * Log success
243
- */
244
- success(message: string, ...args: any[]): void {
245
- if (!this.config.enabled) return;
246
- this.consola.success(message, ...args);
247
- }
248
-
249
- /**
250
- * Create a sub-logger with prefix
251
- */
252
- withTag(tag: string): ConsolaInstance {
253
- return this.consola.withTag(tag);
254
- }
255
- }
256
-
257
- /**
258
- * Default logger instance
259
- */
260
- export const defaultLogger = new APILogger();