@djangocfg/monitor 2.1.216

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 (62) hide show
  1. package/README.md +341 -0
  2. package/dist/client.cjs +1273 -0
  3. package/dist/client.cjs.map +1 -0
  4. package/dist/client.d.cts +123 -0
  5. package/dist/client.d.ts +123 -0
  6. package/dist/client.mjs +1243 -0
  7. package/dist/client.mjs.map +1 -0
  8. package/dist/index.cjs +18 -0
  9. package/dist/index.cjs.map +1 -0
  10. package/dist/index.d.cts +101 -0
  11. package/dist/index.d.ts +101 -0
  12. package/dist/index.mjs +1 -0
  13. package/dist/index.mjs.map +1 -0
  14. package/dist/server.cjs +947 -0
  15. package/dist/server.cjs.map +1 -0
  16. package/dist/server.d.cts +117 -0
  17. package/dist/server.d.ts +117 -0
  18. package/dist/server.mjs +917 -0
  19. package/dist/server.mjs.map +1 -0
  20. package/package.json +82 -0
  21. package/src/.claude/.sidecar/activity.jsonl +1 -0
  22. package/src/.claude/.sidecar/map_cache.json +38 -0
  23. package/src/.claude/.sidecar/usage.json +5 -0
  24. package/src/.claude/project-map.md +29 -0
  25. package/src/_api/BaseClient.ts +18 -0
  26. package/src/_api/generated/cfg_monitor/CLAUDE.md +60 -0
  27. package/src/_api/generated/cfg_monitor/_utils/fetchers/index.ts +30 -0
  28. package/src/_api/generated/cfg_monitor/_utils/fetchers/monitor.ts +51 -0
  29. package/src/_api/generated/cfg_monitor/_utils/hooks/index.ts +30 -0
  30. package/src/_api/generated/cfg_monitor/_utils/hooks/monitor.ts +43 -0
  31. package/src/_api/generated/cfg_monitor/_utils/schemas/FrontendEventIngestRequest.schema.ts +34 -0
  32. package/src/_api/generated/cfg_monitor/_utils/schemas/IngestBatchRequest.schema.ts +20 -0
  33. package/src/_api/generated/cfg_monitor/_utils/schemas/index.ts +22 -0
  34. package/src/_api/generated/cfg_monitor/api-instance.ts +181 -0
  35. package/src/_api/generated/cfg_monitor/client.ts +322 -0
  36. package/src/_api/generated/cfg_monitor/enums.ts +36 -0
  37. package/src/_api/generated/cfg_monitor/errors.ts +118 -0
  38. package/src/_api/generated/cfg_monitor/http.ts +137 -0
  39. package/src/_api/generated/cfg_monitor/index.ts +317 -0
  40. package/src/_api/generated/cfg_monitor/logger.ts +261 -0
  41. package/src/_api/generated/cfg_monitor/monitor/client.ts +25 -0
  42. package/src/_api/generated/cfg_monitor/monitor/index.ts +4 -0
  43. package/src/_api/generated/cfg_monitor/monitor/models.ts +48 -0
  44. package/src/_api/generated/cfg_monitor/retry.ts +177 -0
  45. package/src/_api/generated/cfg_monitor/schema.json +184 -0
  46. package/src/_api/generated/cfg_monitor/storage.ts +163 -0
  47. package/src/_api/generated/cfg_monitor/validation-events.ts +135 -0
  48. package/src/_api/index.ts +6 -0
  49. package/src/client/capture/console.ts +72 -0
  50. package/src/client/capture/fingerprint.ts +27 -0
  51. package/src/client/capture/js-errors.ts +70 -0
  52. package/src/client/capture/network.ts +47 -0
  53. package/src/client/capture/session.ts +33 -0
  54. package/src/client/capture/validation.ts +38 -0
  55. package/src/client/index.ts +72 -0
  56. package/src/client/store/index.ts +41 -0
  57. package/src/client/transport/ingest.ts +31 -0
  58. package/src/index.ts +12 -0
  59. package/src/server/index.ts +85 -0
  60. package/src/types/config.ts +33 -0
  61. package/src/types/events.ts +5 -0
  62. package/src/types/index.ts +6 -0
@@ -0,0 +1,181 @@
1
+ // @ts-nocheck
2
+ // Auto-generated by DjangoCFG - see CLAUDE.md
3
+ /**
4
+ * Global API Instance - Singleton configuration with auto-configuration support
5
+ *
6
+ * This module provides a global API instance that auto-configures from
7
+ * environment variables or can be configured manually.
8
+ *
9
+ * AUTO-CONFIGURATION (recommended):
10
+ * Set one of these environment variables and the API will auto-configure:
11
+ * - NEXT_PUBLIC_API_URL (Next.js)
12
+ * - VITE_API_URL (Vite)
13
+ * - REACT_APP_API_URL (Create React App)
14
+ * - API_URL (generic)
15
+ *
16
+ * Then just use fetchers and hooks directly:
17
+ * ```typescript
18
+ * import { getUsers } from './_utils/fetchers'
19
+ * const users = await getUsers({ page: 1 })
20
+ * ```
21
+ *
22
+ * MANUAL CONFIGURATION:
23
+ * ```typescript
24
+ * import { configureAPI } from './api-instance'
25
+ *
26
+ * configureAPI({
27
+ * baseUrl: 'https://api.example.com',
28
+ * token: 'your-jwt-token'
29
+ * })
30
+ * ```
31
+ *
32
+ * For SSR or multiple instances:
33
+ * ```typescript
34
+ * import { API } from './index'
35
+ * import { getUsers } from './_utils/fetchers'
36
+ *
37
+ * const api = new API('https://api.example.com')
38
+ * const users = await getUsers({ page: 1 }, api)
39
+ * ```
40
+ */
41
+
42
+ import { API, type APIOptions } from './index'
43
+
44
+ let globalAPI: API | null = null
45
+ let autoConfigAttempted = false
46
+
47
+ /**
48
+ * Auto-configure from environment variable if available (Next.js pattern)
49
+ * This allows hooks and fetchers to work without explicit configureAPI() call
50
+ *
51
+ * Supported environment variables:
52
+ * - NEXT_PUBLIC_API_URL (Next.js)
53
+ * - VITE_API_URL (Vite)
54
+ * - REACT_APP_API_URL (Create React App)
55
+ * - API_URL (generic)
56
+ */
57
+ function tryAutoConfigureFromEnv(): void {
58
+ // Only attempt once
59
+ if (autoConfigAttempted) return
60
+ autoConfigAttempted = true
61
+
62
+ // Skip if already configured
63
+ if (globalAPI) return
64
+
65
+ // Skip if process is not available (pure browser without bundler)
66
+ if (typeof process === 'undefined' || !process.env) return
67
+
68
+ // Try different environment variable patterns
69
+ const baseUrl =
70
+ process.env.NEXT_PUBLIC_API_URL ||
71
+ process.env.VITE_API_URL ||
72
+ process.env.REACT_APP_API_URL ||
73
+ process.env.API_URL
74
+
75
+ if (baseUrl) {
76
+ globalAPI = new API(baseUrl)
77
+ }
78
+ }
79
+
80
+ /**
81
+ * Get the global API instance
82
+ * Auto-configures from environment variables on first call if not manually configured.
83
+ * @throws Error if API is not configured and no env variable is set
84
+ */
85
+ export function getAPIInstance(): API {
86
+ // Try auto-configuration on first access (lazy initialization)
87
+ tryAutoConfigureFromEnv()
88
+
89
+ if (!globalAPI) {
90
+ throw new Error(
91
+ 'API not configured. Call configureAPI() with your base URL before using fetchers or hooks.\n\n' +
92
+ 'Example:\n' +
93
+ ' import { configureAPI } from "./api-instance"\n' +
94
+ ' configureAPI({ baseUrl: "https://api.example.com" })\n\n' +
95
+ 'Or set environment variable: NEXT_PUBLIC_API_URL, VITE_API_URL, or REACT_APP_API_URL'
96
+ )
97
+ }
98
+ return globalAPI
99
+ }
100
+
101
+ /**
102
+ * Check if API is configured (or can be auto-configured)
103
+ */
104
+ export function isAPIConfigured(): boolean {
105
+ tryAutoConfigureFromEnv()
106
+ return globalAPI !== null
107
+ }
108
+
109
+ /**
110
+ * Configure the global API instance
111
+ *
112
+ * @param baseUrl - Base URL for the API
113
+ * @param options - Optional configuration (storage, retry, logger)
114
+ *
115
+ * @example
116
+ * ```typescript
117
+ * configureAPI({
118
+ * baseUrl: 'https://api.example.com',
119
+ * token: 'jwt-token',
120
+ * options: {
121
+ * retryConfig: { maxRetries: 3 },
122
+ * loggerConfig: { enabled: true }
123
+ * }
124
+ * })
125
+ * ```
126
+ */
127
+ export function configureAPI(config: {
128
+ baseUrl: string
129
+ token?: string
130
+ refreshToken?: string
131
+ options?: APIOptions
132
+ }): API {
133
+ globalAPI = new API(config.baseUrl, config.options)
134
+
135
+ if (config.token) {
136
+ globalAPI.setToken(config.token, config.refreshToken)
137
+ }
138
+
139
+ return globalAPI
140
+ }
141
+
142
+ /**
143
+ * Reconfigure the global API instance with new settings
144
+ * Useful for updating tokens or base URL
145
+ */
146
+ export function reconfigureAPI(updates: {
147
+ baseUrl?: string
148
+ token?: string
149
+ refreshToken?: string
150
+ }): API {
151
+ const instance = getAPIInstance()
152
+
153
+ if (updates.baseUrl) {
154
+ instance.setBaseUrl(updates.baseUrl)
155
+ }
156
+
157
+ if (updates.token) {
158
+ instance.setToken(updates.token, updates.refreshToken)
159
+ }
160
+
161
+ return instance
162
+ }
163
+
164
+ /**
165
+ * Clear tokens from the global API instance
166
+ */
167
+ export function clearAPITokens(): void {
168
+ const instance = getAPIInstance()
169
+ instance.clearTokens()
170
+ }
171
+
172
+ /**
173
+ * Reset the global API instance
174
+ * Useful for testing or logout scenarios
175
+ */
176
+ export function resetAPI(): void {
177
+ if (globalAPI) {
178
+ globalAPI.clearTokens()
179
+ }
180
+ globalAPI = null
181
+ }
@@ -0,0 +1,322 @@
1
+ import { Monitor } from "./monitor";
2
+ import { HttpClientAdapter, FetchAdapter } from "./http";
3
+ import { APIError, NetworkError } from "./errors";
4
+ import { APILogger, type LoggerConfig } from "./logger";
5
+ import { withRetry, type RetryConfig } from "./retry";
6
+
7
+
8
+ /**
9
+ * Async API client for Django CFG API.
10
+ *
11
+ * Usage:
12
+ * ```typescript
13
+ * const client = new APIClient('https://api.example.com');
14
+ * const users = await client.users.list();
15
+ * const post = await client.posts.create(newPost);
16
+ *
17
+ * // Custom HTTP adapter (e.g., Axios)
18
+ * const client = new APIClient('https://api.example.com', {
19
+ * httpClient: new AxiosAdapter()
20
+ * });
21
+ * ```
22
+ */
23
+ export class APIClient {
24
+ private baseUrl: string;
25
+ private httpClient: HttpClientAdapter;
26
+ private logger: APILogger | null = null;
27
+ private retryConfig: RetryConfig | null = null;
28
+ private tokenGetter: (() => string | null) | null = null;
29
+
30
+ // Sub-clients
31
+ public monitor: Monitor;
32
+
33
+ constructor(
34
+ baseUrl: string,
35
+ options?: {
36
+ httpClient?: HttpClientAdapter;
37
+ loggerConfig?: Partial<LoggerConfig>;
38
+ retryConfig?: RetryConfig;
39
+ tokenGetter?: () => string | null;
40
+ }
41
+ ) {
42
+ this.baseUrl = baseUrl.replace(/\/$/, '');
43
+ this.httpClient = options?.httpClient || new FetchAdapter();
44
+ this.tokenGetter = options?.tokenGetter || null;
45
+
46
+ // Initialize logger if config provided
47
+ if (options?.loggerConfig !== undefined) {
48
+ this.logger = new APILogger(options.loggerConfig);
49
+ }
50
+
51
+ // Store retry configuration
52
+ if (options?.retryConfig !== undefined) {
53
+ this.retryConfig = options.retryConfig;
54
+ }
55
+
56
+ // Initialize sub-clients
57
+ this.monitor = new Monitor(this);
58
+ }
59
+
60
+ /**
61
+ * Get CSRF token from cookies (for SessionAuthentication).
62
+ *
63
+ * Returns null if cookie doesn't exist (JWT-only auth).
64
+ */
65
+ getCsrfToken(): string | null {
66
+ const name = 'csrftoken';
67
+ const value = `; ${document.cookie}`;
68
+ const parts = value.split(`; ${name}=`);
69
+ if (parts.length === 2) {
70
+ return parts.pop()?.split(';').shift() || null;
71
+ }
72
+ return null;
73
+ }
74
+
75
+ /**
76
+ * Get the base URL for building streaming/download URLs.
77
+ */
78
+ getBaseUrl(): string {
79
+ return this.baseUrl;
80
+ }
81
+
82
+ /**
83
+ * Get JWT token for URL authentication (used in streaming endpoints).
84
+ * Returns null if no token getter is configured or no token is available.
85
+ */
86
+ getToken(): string | null {
87
+ return this.tokenGetter ? this.tokenGetter() : null;
88
+ }
89
+
90
+ /**
91
+ * Make HTTP request with Django CSRF and session handling.
92
+ * Automatically retries on network errors and 5xx server errors.
93
+ */
94
+ async request<T>(
95
+ method: string,
96
+ path: string,
97
+ options?: {
98
+ params?: Record<string, any>;
99
+ body?: any;
100
+ formData?: FormData;
101
+ binaryBody?: Blob | ArrayBuffer;
102
+ headers?: Record<string, string>;
103
+ }
104
+ ): Promise<T> {
105
+ // Wrap request in retry logic if configured
106
+ if (this.retryConfig) {
107
+ return withRetry(() => this._makeRequest<T>(method, path, options), {
108
+ ...this.retryConfig,
109
+ onFailedAttempt: (info) => {
110
+ // Log retry attempts
111
+ if (this.logger) {
112
+ this.logger.warn(
113
+ `Retry attempt ${info.attemptNumber}/${info.retriesLeft + info.attemptNumber} ` +
114
+ `for ${method} ${path}: ${info.error.message}`
115
+ );
116
+ }
117
+ // Call user's onFailedAttempt if provided
118
+ this.retryConfig?.onFailedAttempt?.(info);
119
+ },
120
+ });
121
+ }
122
+
123
+ // No retry configured, make request directly
124
+ return this._makeRequest<T>(method, path, options);
125
+ }
126
+
127
+ /**
128
+ * Internal request method (without retry wrapper).
129
+ * Used by request() method with optional retry logic.
130
+ */
131
+ private async _makeRequest<T>(
132
+ method: string,
133
+ path: string,
134
+ options?: {
135
+ params?: Record<string, any>;
136
+ body?: any;
137
+ formData?: FormData;
138
+ binaryBody?: Blob | ArrayBuffer;
139
+ headers?: Record<string, string>;
140
+ }
141
+ ): Promise<T> {
142
+ // Build URL - handle both absolute and relative paths
143
+ // When baseUrl is empty (static builds), path is used as-is (relative to current origin)
144
+ const url = this.baseUrl ? `${this.baseUrl}${path}` : path;
145
+ const startTime = Date.now();
146
+
147
+ // Build headers - start with custom headers from options
148
+ const headers: Record<string, string> = {
149
+ ...(options?.headers || {})
150
+ };
151
+
152
+ // Don't set Content-Type for FormData/binaryBody (browser will set it with boundary)
153
+ if (!options?.formData && !options?.binaryBody && !headers['Content-Type']) {
154
+ headers['Content-Type'] = 'application/json';
155
+ }
156
+
157
+ // CSRF not needed - SessionAuthentication not enabled in DRF config
158
+ // Your API uses JWT/Token authentication (no CSRF required)
159
+
160
+ // Log request
161
+ if (this.logger) {
162
+ this.logger.logRequest({
163
+ method,
164
+ url: url,
165
+ headers,
166
+ body: options?.formData || options?.body,
167
+ timestamp: startTime,
168
+ });
169
+ }
170
+
171
+ try {
172
+ // Make request via HTTP adapter
173
+ const response = await this.httpClient.request<T>({
174
+ method,
175
+ url: url,
176
+ headers,
177
+ params: options?.params,
178
+ body: options?.body,
179
+ formData: options?.formData,
180
+ binaryBody: options?.binaryBody,
181
+ });
182
+
183
+ const duration = Date.now() - startTime;
184
+
185
+ // Check for HTTP errors
186
+ if (response.status >= 400) {
187
+ const error = new APIError(
188
+ response.status,
189
+ response.statusText,
190
+ response.data,
191
+ url
192
+ );
193
+
194
+ // Log error
195
+ if (this.logger) {
196
+ this.logger.logError(
197
+ {
198
+ method,
199
+ url: url,
200
+ headers,
201
+ body: options?.formData || options?.body,
202
+ timestamp: startTime,
203
+ },
204
+ {
205
+ message: error.message,
206
+ statusCode: response.status,
207
+ duration,
208
+ timestamp: Date.now(),
209
+ }
210
+ );
211
+ }
212
+
213
+ throw error;
214
+ }
215
+
216
+ // Log successful response
217
+ if (this.logger) {
218
+ this.logger.logResponse(
219
+ {
220
+ method,
221
+ url: url,
222
+ headers,
223
+ body: options?.formData || options?.body,
224
+ timestamp: startTime,
225
+ },
226
+ {
227
+ status: response.status,
228
+ statusText: response.statusText,
229
+ data: response.data,
230
+ duration,
231
+ timestamp: Date.now(),
232
+ }
233
+ );
234
+ }
235
+
236
+ return response.data as T;
237
+ } catch (error) {
238
+ const duration = Date.now() - startTime;
239
+
240
+ // Re-throw APIError as-is
241
+ if (error instanceof APIError) {
242
+ throw error;
243
+ }
244
+
245
+ // Detect CORS errors and dispatch event
246
+ const isCORSError = error instanceof TypeError &&
247
+ (error.message.toLowerCase().includes('cors') ||
248
+ error.message.toLowerCase().includes('failed to fetch') ||
249
+ error.message.toLowerCase().includes('network request failed'));
250
+
251
+ // Log specific error type first
252
+ if (this.logger) {
253
+ if (isCORSError) {
254
+ this.logger.error(`🚫 CORS Error: ${method} ${url}`);
255
+ this.logger.error(` → ${error instanceof Error ? error.message : String(error)}`);
256
+ this.logger.error(` → Configure security_domains parameter on the server`);
257
+ } else {
258
+ this.logger.error(`⚠️ Network Error: ${method} ${url}`);
259
+ this.logger.error(` → ${error instanceof Error ? error.message : String(error)}`);
260
+ }
261
+ }
262
+
263
+ // Dispatch browser events
264
+ if (typeof window !== 'undefined') {
265
+ try {
266
+ if (isCORSError) {
267
+ // Dispatch CORS-specific error event
268
+ window.dispatchEvent(new CustomEvent('cors-error', {
269
+ detail: {
270
+ url: url,
271
+ method: method,
272
+ error: error instanceof Error ? error.message : String(error),
273
+ timestamp: new Date(),
274
+ },
275
+ bubbles: true,
276
+ cancelable: false,
277
+ }));
278
+ } else {
279
+ // Dispatch generic network error event
280
+ window.dispatchEvent(new CustomEvent('network-error', {
281
+ detail: {
282
+ url: url,
283
+ method: method,
284
+ error: error instanceof Error ? error.message : String(error),
285
+ timestamp: new Date(),
286
+ },
287
+ bubbles: true,
288
+ cancelable: false,
289
+ }));
290
+ }
291
+ } catch (eventError) {
292
+ // Silently fail - event dispatch should never crash the app
293
+ }
294
+ }
295
+
296
+ // Wrap other errors as NetworkError
297
+ const networkError = error instanceof Error
298
+ ? new NetworkError(error.message, url, error)
299
+ : new NetworkError('Unknown error', url);
300
+
301
+ // Detailed logging via logger.logError
302
+ if (this.logger) {
303
+ this.logger.logError(
304
+ {
305
+ method,
306
+ url: url,
307
+ headers,
308
+ body: options?.formData || options?.body,
309
+ timestamp: startTime,
310
+ },
311
+ {
312
+ message: networkError.message,
313
+ duration,
314
+ timestamp: Date.now(),
315
+ }
316
+ );
317
+ }
318
+
319
+ throw networkError;
320
+ }
321
+ }
322
+ }
@@ -0,0 +1,36 @@
1
+ // @ts-nocheck
2
+ // Auto-generated by DjangoCFG - see CLAUDE.md
3
+ /**
4
+ * * `ERROR` - Error
5
+ * * `WARNING` - Warning
6
+ * * `INFO` - Info
7
+ * * `PAGE_VIEW` - Page View
8
+ * * `PERFORMANCE` - Performance
9
+ * * `NETWORK_ERROR` - Network Error
10
+ * * `JS_ERROR` - JS Error
11
+ * * `CONSOLE` - Console
12
+ */
13
+ export enum FrontendEventIngestRequestEventType {
14
+ ERROR = "ERROR",
15
+ WARNING = "WARNING",
16
+ INFO = "INFO",
17
+ PAGE_VIEW = "PAGE_VIEW",
18
+ PERFORMANCE = "PERFORMANCE",
19
+ NETWORK_ERROR = "NETWORK_ERROR",
20
+ JS_ERROR = "JS_ERROR",
21
+ CONSOLE = "CONSOLE",
22
+ }
23
+
24
+ /**
25
+ * * `error` - Error
26
+ * * `warn` - Warning
27
+ * * `info` - Info
28
+ * * `debug` - Debug
29
+ */
30
+ export enum FrontendEventIngestRequestLevel {
31
+ ERROR = "error",
32
+ WARN = "warn",
33
+ INFO = "info",
34
+ DEBUG = "debug",
35
+ }
36
+
@@ -0,0 +1,118 @@
1
+ // @ts-nocheck
2
+ // Auto-generated by DjangoCFG - see CLAUDE.md
3
+ /**
4
+ * API Error Classes
5
+ *
6
+ * Typed error classes with Django REST Framework support.
7
+ */
8
+
9
+ /**
10
+ * HTTP API Error with DRF field-specific validation errors.
11
+ *
12
+ * Usage:
13
+ * ```typescript
14
+ * try {
15
+ * await api.users.create(userData);
16
+ * } catch (error) {
17
+ * if (error instanceof APIError) {
18
+ * if (error.isValidationError) {
19
+ * console.log('Field errors:', error.fieldErrors);
20
+ * // { "email": ["Email already exists"], "username": ["Required"] }
21
+ * }
22
+ * }
23
+ * }
24
+ * ```
25
+ */
26
+ export class APIError extends Error {
27
+ constructor(
28
+ public statusCode: number,
29
+ public statusText: string,
30
+ public response: any,
31
+ public url: string,
32
+ message?: string
33
+ ) {
34
+ super(message || `HTTP ${statusCode}: ${statusText}`);
35
+ this.name = 'APIError';
36
+ }
37
+
38
+ /**
39
+ * Get error details from response.
40
+ * DRF typically returns: { "detail": "Error message" } or { "field": ["error1", "error2"] }
41
+ */
42
+ get details(): Record<string, any> | null {
43
+ if (typeof this.response === 'object' && this.response !== null) {
44
+ return this.response;
45
+ }
46
+ return null;
47
+ }
48
+
49
+ /**
50
+ * Get field-specific validation errors from DRF.
51
+ * Returns: { "field_name": ["error1", "error2"], ... }
52
+ */
53
+ get fieldErrors(): Record<string, string[]> | null {
54
+ const details = this.details;
55
+ if (!details) return null;
56
+
57
+ // DRF typically returns: { "field": ["error1", "error2"] }
58
+ const fieldErrors: Record<string, string[]> = {};
59
+ for (const [key, value] of Object.entries(details)) {
60
+ if (Array.isArray(value)) {
61
+ fieldErrors[key] = value;
62
+ }
63
+ }
64
+
65
+ return Object.keys(fieldErrors).length > 0 ? fieldErrors : null;
66
+ }
67
+
68
+ /**
69
+ * Get single error message from DRF.
70
+ * Checks for "detail", "message", or first field error.
71
+ */
72
+ get errorMessage(): string {
73
+ const details = this.details;
74
+ if (!details) return this.message;
75
+
76
+ // Check for "detail" field (common in DRF)
77
+ if (details.detail) {
78
+ return Array.isArray(details.detail) ? details.detail.join(', ') : String(details.detail);
79
+ }
80
+
81
+ // Check for "message" field
82
+ if (details.message) {
83
+ return String(details.message);
84
+ }
85
+
86
+ // Return first field error
87
+ const fieldErrors = this.fieldErrors;
88
+ if (fieldErrors) {
89
+ const firstField = Object.keys(fieldErrors)[0];
90
+ if (firstField) {
91
+ return `${firstField}: ${fieldErrors[firstField]?.join(', ')}`;
92
+ }
93
+ }
94
+
95
+ return this.message;
96
+ }
97
+
98
+ // Helper methods for common HTTP status codes
99
+ get isValidationError(): boolean { return this.statusCode === 400; }
100
+ get isAuthError(): boolean { return this.statusCode === 401; }
101
+ get isPermissionError(): boolean { return this.statusCode === 403; }
102
+ get isNotFoundError(): boolean { return this.statusCode === 404; }
103
+ get isServerError(): boolean { return this.statusCode >= 500 && this.statusCode < 600; }
104
+ }
105
+
106
+ /**
107
+ * Network Error (connection failed, timeout, etc.)
108
+ */
109
+ export class NetworkError extends Error {
110
+ constructor(
111
+ message: string,
112
+ public url: string,
113
+ public originalError?: Error
114
+ ) {
115
+ super(message);
116
+ this.name = 'NetworkError';
117
+ }
118
+ }