@djangocfg/ext-knowbase 1.0.0

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 (104) hide show
  1. package/README.md +177 -0
  2. package/dist/chunk-GNRC54ON.js +4308 -0
  3. package/dist/hooks.cjs +6003 -0
  4. package/dist/hooks.d.cts +610 -0
  5. package/dist/hooks.d.ts +610 -0
  6. package/dist/hooks.js +1486 -0
  7. package/dist/index.cjs +4450 -0
  8. package/dist/index.d.cts +4398 -0
  9. package/dist/index.d.ts +4398 -0
  10. package/dist/index.js +1 -0
  11. package/package.json +81 -0
  12. package/src/api/generated/ext_knowbase/_utils/fetchers/ext_knowbase__knowbase.ts +2983 -0
  13. package/src/api/generated/ext_knowbase/_utils/fetchers/index.ts +28 -0
  14. package/src/api/generated/ext_knowbase/_utils/hooks/ext_knowbase__knowbase.ts +999 -0
  15. package/src/api/generated/ext_knowbase/_utils/hooks/index.ts +28 -0
  16. package/src/api/generated/ext_knowbase/_utils/schemas/ArchiveItem.schema.ts +33 -0
  17. package/src/api/generated/ext_knowbase/_utils/schemas/ArchiveItemChunk.schema.ts +29 -0
  18. package/src/api/generated/ext_knowbase/_utils/schemas/ArchiveItemChunkDetail.schema.ts +30 -0
  19. package/src/api/generated/ext_knowbase/_utils/schemas/ArchiveItemChunkRequest.schema.ts +22 -0
  20. package/src/api/generated/ext_knowbase/_utils/schemas/ArchiveItemDetail.schema.ts +35 -0
  21. package/src/api/generated/ext_knowbase/_utils/schemas/ArchiveItemRequest.schema.ts +22 -0
  22. package/src/api/generated/ext_knowbase/_utils/schemas/ArchiveProcessingResult.schema.ts +26 -0
  23. package/src/api/generated/ext_knowbase/_utils/schemas/ArchiveSearchRequestRequest.schema.ts +25 -0
  24. package/src/api/generated/ext_knowbase/_utils/schemas/ArchiveSearchResult.schema.ts +24 -0
  25. package/src/api/generated/ext_knowbase/_utils/schemas/ArchiveStatistics.schema.ts +28 -0
  26. package/src/api/generated/ext_knowbase/_utils/schemas/ChatHistory.schema.ts +22 -0
  27. package/src/api/generated/ext_knowbase/_utils/schemas/ChatMessage.schema.ts +27 -0
  28. package/src/api/generated/ext_knowbase/_utils/schemas/ChatQueryRequest.schema.ts +22 -0
  29. package/src/api/generated/ext_knowbase/_utils/schemas/ChatResponse.schema.ts +26 -0
  30. package/src/api/generated/ext_knowbase/_utils/schemas/ChatResponseRequest.schema.ts +26 -0
  31. package/src/api/generated/ext_knowbase/_utils/schemas/ChatSession.schema.ts +29 -0
  32. package/src/api/generated/ext_knowbase/_utils/schemas/ChatSessionCreateRequest.schema.ts +22 -0
  33. package/src/api/generated/ext_knowbase/_utils/schemas/ChatSessionRequest.schema.ts +25 -0
  34. package/src/api/generated/ext_knowbase/_utils/schemas/ChatSource.schema.ts +21 -0
  35. package/src/api/generated/ext_knowbase/_utils/schemas/ChatSourceRequest.schema.ts +21 -0
  36. package/src/api/generated/ext_knowbase/_utils/schemas/ChunkRevectorizationRequestRequest.schema.ts +20 -0
  37. package/src/api/generated/ext_knowbase/_utils/schemas/Document.schema.ts +32 -0
  38. package/src/api/generated/ext_knowbase/_utils/schemas/DocumentArchive.schema.ts +44 -0
  39. package/src/api/generated/ext_knowbase/_utils/schemas/DocumentArchiveDetail.schema.ts +48 -0
  40. package/src/api/generated/ext_knowbase/_utils/schemas/DocumentArchiveList.schema.ts +35 -0
  41. package/src/api/generated/ext_knowbase/_utils/schemas/DocumentArchiveRequest.schema.ts +21 -0
  42. package/src/api/generated/ext_knowbase/_utils/schemas/DocumentCategory.schema.ts +23 -0
  43. package/src/api/generated/ext_knowbase/_utils/schemas/DocumentCategoryRequest.schema.ts +21 -0
  44. package/src/api/generated/ext_knowbase/_utils/schemas/DocumentCreateRequest.schema.ts +22 -0
  45. package/src/api/generated/ext_knowbase/_utils/schemas/DocumentProcessingStatus.schema.ts +23 -0
  46. package/src/api/generated/ext_knowbase/_utils/schemas/DocumentRequest.schema.ts +22 -0
  47. package/src/api/generated/ext_knowbase/_utils/schemas/DocumentStats.schema.ts +25 -0
  48. package/src/api/generated/ext_knowbase/_utils/schemas/PaginatedArchiveItemChunkList.schema.ts +24 -0
  49. package/src/api/generated/ext_knowbase/_utils/schemas/PaginatedArchiveItemList.schema.ts +24 -0
  50. package/src/api/generated/ext_knowbase/_utils/schemas/PaginatedArchiveSearchResultList.schema.ts +24 -0
  51. package/src/api/generated/ext_knowbase/_utils/schemas/PaginatedChatResponseList.schema.ts +24 -0
  52. package/src/api/generated/ext_knowbase/_utils/schemas/PaginatedChatSessionList.schema.ts +24 -0
  53. package/src/api/generated/ext_knowbase/_utils/schemas/PaginatedDocumentArchiveListList.schema.ts +24 -0
  54. package/src/api/generated/ext_knowbase/_utils/schemas/PaginatedDocumentList.schema.ts +24 -0
  55. package/src/api/generated/ext_knowbase/_utils/schemas/PaginatedPublicCategoryList.schema.ts +24 -0
  56. package/src/api/generated/ext_knowbase/_utils/schemas/PaginatedPublicDocumentListList.schema.ts +24 -0
  57. package/src/api/generated/ext_knowbase/_utils/schemas/PatchedArchiveItemChunkRequest.schema.ts +22 -0
  58. package/src/api/generated/ext_knowbase/_utils/schemas/PatchedArchiveItemRequest.schema.ts +22 -0
  59. package/src/api/generated/ext_knowbase/_utils/schemas/PatchedChatResponseRequest.schema.ts +26 -0
  60. package/src/api/generated/ext_knowbase/_utils/schemas/PatchedChatSessionRequest.schema.ts +25 -0
  61. package/src/api/generated/ext_knowbase/_utils/schemas/PatchedDocumentArchiveRequest.schema.ts +21 -0
  62. package/src/api/generated/ext_knowbase/_utils/schemas/PatchedDocumentRequest.schema.ts +22 -0
  63. package/src/api/generated/ext_knowbase/_utils/schemas/PublicCategory.schema.ts +21 -0
  64. package/src/api/generated/ext_knowbase/_utils/schemas/PublicDocument.schema.ts +25 -0
  65. package/src/api/generated/ext_knowbase/_utils/schemas/PublicDocumentList.schema.ts +24 -0
  66. package/src/api/generated/ext_knowbase/_utils/schemas/VectorizationResult.schema.ts +24 -0
  67. package/src/api/generated/ext_knowbase/_utils/schemas/VectorizationStatistics.schema.ts +26 -0
  68. package/src/api/generated/ext_knowbase/_utils/schemas/index.ts +70 -0
  69. package/src/api/generated/ext_knowbase/api-instance.ts +131 -0
  70. package/src/api/generated/ext_knowbase/client.ts +301 -0
  71. package/src/api/generated/ext_knowbase/enums.ts +241 -0
  72. package/src/api/generated/ext_knowbase/errors.ts +116 -0
  73. package/src/api/generated/ext_knowbase/ext_knowbase__knowbase/client.ts +666 -0
  74. package/src/api/generated/ext_knowbase/ext_knowbase__knowbase/index.ts +2 -0
  75. package/src/api/generated/ext_knowbase/ext_knowbase__knowbase/models.ts +1120 -0
  76. package/src/api/generated/ext_knowbase/http.ts +103 -0
  77. package/src/api/generated/ext_knowbase/index.ts +273 -0
  78. package/src/api/generated/ext_knowbase/logger.ts +259 -0
  79. package/src/api/generated/ext_knowbase/retry.ts +175 -0
  80. package/src/api/generated/ext_knowbase/schema.json +5865 -0
  81. package/src/api/generated/ext_knowbase/storage.ts +161 -0
  82. package/src/api/generated/ext_knowbase/validation-events.ts +133 -0
  83. package/src/api/index.ts +9 -0
  84. package/src/components/Chat/ChatUIContext.tsx +110 -0
  85. package/src/components/Chat/ChatWidget.tsx +476 -0
  86. package/src/components/Chat/README.md +122 -0
  87. package/src/components/Chat/components/MessageInput.tsx +124 -0
  88. package/src/components/Chat/components/MessageList.tsx +169 -0
  89. package/src/components/Chat/components/SessionList.tsx +192 -0
  90. package/src/components/Chat/components/index.ts +9 -0
  91. package/src/components/Chat/hooks/index.ts +6 -0
  92. package/src/components/Chat/hooks/useInfiniteSessions.ts +81 -0
  93. package/src/components/Chat/index.tsx +45 -0
  94. package/src/components/Chat/types.ts +81 -0
  95. package/src/config.ts +20 -0
  96. package/src/contexts/knowbase/ChatContext.tsx +173 -0
  97. package/src/contexts/knowbase/DocumentsContext.tsx +306 -0
  98. package/src/contexts/knowbase/KnowbaseProvider.tsx +47 -0
  99. package/src/contexts/knowbase/SessionsContext.tsx +175 -0
  100. package/src/contexts/knowbase/index.ts +63 -0
  101. package/src/contexts/knowbase/types.ts +69 -0
  102. package/src/hooks/index.ts +28 -0
  103. package/src/index.ts +22 -0
  104. package/src/utils/logger.ts +10 -0
@@ -0,0 +1,24 @@
1
+ /**
2
+ * Zod schema for PublicDocumentList
3
+ *
4
+ * This schema provides runtime validation and type inference.
5
+ * * Public document list serializer - minimal fields for listing.
6
+ * */
7
+ import { z } from 'zod'
8
+ import { PublicCategorySchema } from './PublicCategory.schema'
9
+
10
+ /**
11
+ * Public document list serializer - minimal fields for listing.
12
+ */
13
+ export const PublicDocumentListSchema = z.object({
14
+ id: z.string().regex(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i),
15
+ title: z.string().max(512),
16
+ category: PublicCategorySchema,
17
+ created_at: z.iso.datetime(),
18
+ updated_at: z.iso.datetime(),
19
+ })
20
+
21
+ /**
22
+ * Infer TypeScript type from Zod schema
23
+ */
24
+ export type PublicDocumentList = z.infer<typeof PublicDocumentListSchema>
@@ -0,0 +1,24 @@
1
+ /**
2
+ * Zod schema for VectorizationResult
3
+ *
4
+ * This schema provides runtime validation and type inference.
5
+ * * Vectorization result serializer.
6
+ * */
7
+ import { z } from 'zod'
8
+
9
+ /**
10
+ * Vectorization result serializer.
11
+ */
12
+ export const VectorizationResultSchema = z.object({
13
+ vectorized_count: z.int(),
14
+ failed_count: z.int(),
15
+ total_tokens: z.int(),
16
+ total_cost: z.number(),
17
+ success_rate: z.number(),
18
+ errors: z.array(z.string()),
19
+ })
20
+
21
+ /**
22
+ * Infer TypeScript type from Zod schema
23
+ */
24
+ export type VectorizationResult = z.infer<typeof VectorizationResultSchema>
@@ -0,0 +1,26 @@
1
+ /**
2
+ * Zod schema for VectorizationStatistics
3
+ *
4
+ * This schema provides runtime validation and type inference.
5
+ * * Vectorization statistics serializer.
6
+ * */
7
+ import { z } from 'zod'
8
+
9
+ /**
10
+ * Vectorization statistics serializer.
11
+ */
12
+ export const VectorizationStatisticsSchema = z.object({
13
+ total_chunks: z.int(),
14
+ vectorized_chunks: z.int(),
15
+ pending_chunks: z.int(),
16
+ vectorization_rate: z.number(),
17
+ total_tokens: z.int(),
18
+ total_cost: z.number(),
19
+ avg_tokens_per_chunk: z.number(),
20
+ avg_cost_per_chunk: z.number(),
21
+ })
22
+
23
+ /**
24
+ * Infer TypeScript type from Zod schema
25
+ */
26
+ export type VectorizationStatistics = z.infer<typeof VectorizationStatisticsSchema>
@@ -0,0 +1,70 @@
1
+ /**
2
+ * Zod Schemas - Runtime validation and type inference
3
+ *
4
+ * Auto-generated from OpenAPI specification.
5
+ * Provides runtime validation for API requests and responses.
6
+ *
7
+ * Usage:
8
+ * ```typescript
9
+ * import { UserSchema } from './schemas'
10
+ *
11
+ * // Validate data
12
+ * const user = UserSchema.parse(data)
13
+ *
14
+ * // Type inference
15
+ * type User = z.infer<typeof UserSchema>
16
+ * ```
17
+ */
18
+
19
+ export * from './ArchiveItem.schema'
20
+ export * from './ArchiveItemChunk.schema'
21
+ export * from './ArchiveItemChunkDetail.schema'
22
+ export * from './ArchiveItemChunkRequest.schema'
23
+ export * from './ArchiveItemDetail.schema'
24
+ export * from './ArchiveItemRequest.schema'
25
+ export * from './ArchiveProcessingResult.schema'
26
+ export * from './ArchiveSearchRequestRequest.schema'
27
+ export * from './ArchiveSearchResult.schema'
28
+ export * from './ArchiveStatistics.schema'
29
+ export * from './ChatHistory.schema'
30
+ export * from './ChatMessage.schema'
31
+ export * from './ChatQueryRequest.schema'
32
+ export * from './ChatResponse.schema'
33
+ export * from './ChatResponseRequest.schema'
34
+ export * from './ChatSession.schema'
35
+ export * from './ChatSessionCreateRequest.schema'
36
+ export * from './ChatSessionRequest.schema'
37
+ export * from './ChatSource.schema'
38
+ export * from './ChatSourceRequest.schema'
39
+ export * from './ChunkRevectorizationRequestRequest.schema'
40
+ export * from './Document.schema'
41
+ export * from './DocumentArchive.schema'
42
+ export * from './DocumentArchiveDetail.schema'
43
+ export * from './DocumentArchiveList.schema'
44
+ export * from './DocumentArchiveRequest.schema'
45
+ export * from './DocumentCategory.schema'
46
+ export * from './DocumentCategoryRequest.schema'
47
+ export * from './DocumentCreateRequest.schema'
48
+ export * from './DocumentProcessingStatus.schema'
49
+ export * from './DocumentRequest.schema'
50
+ export * from './DocumentStats.schema'
51
+ export * from './PaginatedArchiveItemChunkList.schema'
52
+ export * from './PaginatedArchiveItemList.schema'
53
+ export * from './PaginatedArchiveSearchResultList.schema'
54
+ export * from './PaginatedChatResponseList.schema'
55
+ export * from './PaginatedChatSessionList.schema'
56
+ export * from './PaginatedDocumentArchiveListList.schema'
57
+ export * from './PaginatedDocumentList.schema'
58
+ export * from './PaginatedPublicCategoryList.schema'
59
+ export * from './PaginatedPublicDocumentListList.schema'
60
+ export * from './PatchedArchiveItemChunkRequest.schema'
61
+ export * from './PatchedArchiveItemRequest.schema'
62
+ export * from './PatchedChatResponseRequest.schema'
63
+ export * from './PatchedChatSessionRequest.schema'
64
+ export * from './PatchedDocumentArchiveRequest.schema'
65
+ export * from './PatchedDocumentRequest.schema'
66
+ export * from './PublicCategory.schema'
67
+ export * from './PublicDocument.schema'
68
+ export * from './PublicDocumentList.schema'
69
+ export * from './VectorizationResult.schema'
70
+ export * from './VectorizationStatistics.schema'
@@ -0,0 +1,131 @@
1
+ /**
2
+ * Global API Instance - Singleton configuration
3
+ *
4
+ * This module provides a global API instance that can be configured once
5
+ * and used throughout your application.
6
+ *
7
+ * Usage:
8
+ * ```typescript
9
+ * // Configure once (e.g., in your app entry point)
10
+ * import { configureAPI } from './api-instance'
11
+ *
12
+ * configureAPI({
13
+ * baseUrl: 'https://api.example.com',
14
+ * token: 'your-jwt-token'
15
+ * })
16
+ *
17
+ * // Then use fetchers and hooks anywhere without configuration
18
+ * import { getUsers } from './fetchers'
19
+ * const users = await getUsers({ page: 1 })
20
+ * ```
21
+ *
22
+ * For SSR or multiple instances:
23
+ * ```typescript
24
+ * import { API } from './index'
25
+ * import { getUsers } from './fetchers'
26
+ *
27
+ * const api = new API('https://api.example.com')
28
+ * const users = await getUsers({ page: 1 }, api)
29
+ * ```
30
+ */
31
+
32
+ import { API, type APIOptions } from './index'
33
+
34
+ let globalAPI: API | null = null
35
+
36
+ /**
37
+ * Get the global API instance
38
+ * @throws Error if API is not configured
39
+ */
40
+ export function getAPIInstance(): API {
41
+ if (!globalAPI) {
42
+ throw new Error(
43
+ 'API not configured. Call configureAPI() with your base URL before using fetchers or hooks.\n\n' +
44
+ 'Example:\n' +
45
+ ' import { configureAPI } from "./api-instance"\n' +
46
+ ' configureAPI({ baseUrl: "https://api.example.com" })'
47
+ )
48
+ }
49
+ return globalAPI
50
+ }
51
+
52
+ /**
53
+ * Check if API is configured
54
+ */
55
+ export function isAPIConfigured(): boolean {
56
+ return globalAPI !== null
57
+ }
58
+
59
+ /**
60
+ * Configure the global API instance
61
+ *
62
+ * @param baseUrl - Base URL for the API
63
+ * @param options - Optional configuration (storage, retry, logger)
64
+ *
65
+ * @example
66
+ * ```typescript
67
+ * configureAPI({
68
+ * baseUrl: 'https://api.example.com',
69
+ * token: 'jwt-token',
70
+ * options: {
71
+ * retryConfig: { maxRetries: 3 },
72
+ * loggerConfig: { enabled: true }
73
+ * }
74
+ * })
75
+ * ```
76
+ */
77
+ export function configureAPI(config: {
78
+ baseUrl: string
79
+ token?: string
80
+ refreshToken?: string
81
+ options?: APIOptions
82
+ }): API {
83
+ globalAPI = new API(config.baseUrl, config.options)
84
+
85
+ if (config.token) {
86
+ globalAPI.setToken(config.token, config.refreshToken)
87
+ }
88
+
89
+ return globalAPI
90
+ }
91
+
92
+ /**
93
+ * Reconfigure the global API instance with new settings
94
+ * Useful for updating tokens or base URL
95
+ */
96
+ export function reconfigureAPI(updates: {
97
+ baseUrl?: string
98
+ token?: string
99
+ refreshToken?: string
100
+ }): API {
101
+ const instance = getAPIInstance()
102
+
103
+ if (updates.baseUrl) {
104
+ instance.setBaseUrl(updates.baseUrl)
105
+ }
106
+
107
+ if (updates.token) {
108
+ instance.setToken(updates.token, updates.refreshToken)
109
+ }
110
+
111
+ return instance
112
+ }
113
+
114
+ /**
115
+ * Clear tokens from the global API instance
116
+ */
117
+ export function clearAPITokens(): void {
118
+ const instance = getAPIInstance()
119
+ instance.clearTokens()
120
+ }
121
+
122
+ /**
123
+ * Reset the global API instance
124
+ * Useful for testing or logout scenarios
125
+ */
126
+ export function resetAPI(): void {
127
+ if (globalAPI) {
128
+ globalAPI.clearTokens()
129
+ }
130
+ globalAPI = null
131
+ }
@@ -0,0 +1,301 @@
1
+ import { ExtKnowbaseKnowbase } from "./ext_knowbase__knowbase";
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
+
29
+ // Sub-clients
30
+ public ext_knowbase_knowbase: ExtKnowbaseKnowbase;
31
+
32
+ constructor(
33
+ baseUrl: string,
34
+ options?: {
35
+ httpClient?: HttpClientAdapter;
36
+ loggerConfig?: Partial<LoggerConfig>;
37
+ retryConfig?: RetryConfig;
38
+ }
39
+ ) {
40
+ this.baseUrl = baseUrl.replace(/\/$/, '');
41
+ this.httpClient = options?.httpClient || new FetchAdapter();
42
+
43
+ // Initialize logger if config provided
44
+ if (options?.loggerConfig !== undefined) {
45
+ this.logger = new APILogger(options.loggerConfig);
46
+ }
47
+
48
+ // Store retry configuration
49
+ if (options?.retryConfig !== undefined) {
50
+ this.retryConfig = options.retryConfig;
51
+ }
52
+
53
+ // Initialize sub-clients
54
+ this.ext_knowbase_knowbase = new ExtKnowbaseKnowbase(this);
55
+ }
56
+
57
+ /**
58
+ * Get CSRF token from cookies (for SessionAuthentication).
59
+ *
60
+ * Returns null if cookie doesn't exist (JWT-only auth).
61
+ */
62
+ getCsrfToken(): string | null {
63
+ const name = 'csrftoken';
64
+ const value = `; ${document.cookie}`;
65
+ const parts = value.split(`; ${name}=`);
66
+ if (parts.length === 2) {
67
+ return parts.pop()?.split(';').shift() || null;
68
+ }
69
+ return null;
70
+ }
71
+
72
+ /**
73
+ * Make HTTP request with Django CSRF and session handling.
74
+ * Automatically retries on network errors and 5xx server errors.
75
+ */
76
+ async request<T>(
77
+ method: string,
78
+ path: string,
79
+ options?: {
80
+ params?: Record<string, any>;
81
+ body?: any;
82
+ formData?: FormData;
83
+ headers?: Record<string, string>;
84
+ }
85
+ ): Promise<T> {
86
+ // Wrap request in retry logic if configured
87
+ if (this.retryConfig) {
88
+ return withRetry(() => this._makeRequest<T>(method, path, options), {
89
+ ...this.retryConfig,
90
+ onFailedAttempt: (info) => {
91
+ // Log retry attempts
92
+ if (this.logger) {
93
+ this.logger.warn(
94
+ `Retry attempt ${info.attemptNumber}/${info.retriesLeft + info.attemptNumber} ` +
95
+ `for ${method} ${path}: ${info.error.message}`
96
+ );
97
+ }
98
+ // Call user's onFailedAttempt if provided
99
+ this.retryConfig?.onFailedAttempt?.(info);
100
+ },
101
+ });
102
+ }
103
+
104
+ // No retry configured, make request directly
105
+ return this._makeRequest<T>(method, path, options);
106
+ }
107
+
108
+ /**
109
+ * Internal request method (without retry wrapper).
110
+ * Used by request() method with optional retry logic.
111
+ */
112
+ private async _makeRequest<T>(
113
+ method: string,
114
+ path: string,
115
+ options?: {
116
+ params?: Record<string, any>;
117
+ body?: any;
118
+ formData?: FormData;
119
+ headers?: Record<string, string>;
120
+ }
121
+ ): Promise<T> {
122
+ // Build URL - handle both absolute and relative paths
123
+ // When baseUrl is empty (static builds), path is used as-is (relative to current origin)
124
+ const url = this.baseUrl ? `${this.baseUrl}${path}` : path;
125
+ const startTime = Date.now();
126
+
127
+ // Build headers - start with custom headers from options
128
+ const headers: Record<string, string> = {
129
+ ...(options?.headers || {})
130
+ };
131
+
132
+ // Don't set Content-Type for FormData (browser will set it with boundary)
133
+ if (!options?.formData && !headers['Content-Type']) {
134
+ headers['Content-Type'] = 'application/json';
135
+ }
136
+
137
+ // CSRF not needed - SessionAuthentication not enabled in DRF config
138
+ // Your API uses JWT/Token authentication (no CSRF required)
139
+
140
+ // Log request
141
+ if (this.logger) {
142
+ this.logger.logRequest({
143
+ method,
144
+ url: url,
145
+ headers,
146
+ body: options?.formData || options?.body,
147
+ timestamp: startTime,
148
+ });
149
+ }
150
+
151
+ try {
152
+ // Make request via HTTP adapter
153
+ const response = await this.httpClient.request<T>({
154
+ method,
155
+ url: url,
156
+ headers,
157
+ params: options?.params,
158
+ body: options?.body,
159
+ formData: options?.formData,
160
+ });
161
+
162
+ const duration = Date.now() - startTime;
163
+
164
+ // Check for HTTP errors
165
+ if (response.status >= 400) {
166
+ const error = new APIError(
167
+ response.status,
168
+ response.statusText,
169
+ response.data,
170
+ url
171
+ );
172
+
173
+ // Log error
174
+ if (this.logger) {
175
+ this.logger.logError(
176
+ {
177
+ method,
178
+ url: url,
179
+ headers,
180
+ body: options?.formData || options?.body,
181
+ timestamp: startTime,
182
+ },
183
+ {
184
+ message: error.message,
185
+ statusCode: response.status,
186
+ duration,
187
+ timestamp: Date.now(),
188
+ }
189
+ );
190
+ }
191
+
192
+ throw error;
193
+ }
194
+
195
+ // Log successful response
196
+ if (this.logger) {
197
+ this.logger.logResponse(
198
+ {
199
+ method,
200
+ url: url,
201
+ headers,
202
+ body: options?.formData || options?.body,
203
+ timestamp: startTime,
204
+ },
205
+ {
206
+ status: response.status,
207
+ statusText: response.statusText,
208
+ data: response.data,
209
+ duration,
210
+ timestamp: Date.now(),
211
+ }
212
+ );
213
+ }
214
+
215
+ return response.data as T;
216
+ } catch (error) {
217
+ const duration = Date.now() - startTime;
218
+
219
+ // Re-throw APIError as-is
220
+ if (error instanceof APIError) {
221
+ throw error;
222
+ }
223
+
224
+ // Detect CORS errors and dispatch event
225
+ const isCORSError = error instanceof TypeError &&
226
+ (error.message.toLowerCase().includes('cors') ||
227
+ error.message.toLowerCase().includes('failed to fetch') ||
228
+ error.message.toLowerCase().includes('network request failed'));
229
+
230
+ // Log specific error type first
231
+ if (this.logger) {
232
+ if (isCORSError) {
233
+ this.logger.error(`🚫 CORS Error: ${method} ${url}`);
234
+ this.logger.error(` → ${error instanceof Error ? error.message : String(error)}`);
235
+ this.logger.error(` → Configure security_domains parameter on the server`);
236
+ } else {
237
+ this.logger.error(`⚠️ Network Error: ${method} ${url}`);
238
+ this.logger.error(` → ${error instanceof Error ? error.message : String(error)}`);
239
+ }
240
+ }
241
+
242
+ // Dispatch browser events
243
+ if (typeof window !== 'undefined') {
244
+ try {
245
+ if (isCORSError) {
246
+ // Dispatch CORS-specific error event
247
+ window.dispatchEvent(new CustomEvent('cors-error', {
248
+ detail: {
249
+ url: url,
250
+ method: method,
251
+ error: error instanceof Error ? error.message : String(error),
252
+ timestamp: new Date(),
253
+ },
254
+ bubbles: true,
255
+ cancelable: false,
256
+ }));
257
+ } else {
258
+ // Dispatch generic network error event
259
+ window.dispatchEvent(new CustomEvent('network-error', {
260
+ detail: {
261
+ url: url,
262
+ method: method,
263
+ error: error instanceof Error ? error.message : String(error),
264
+ timestamp: new Date(),
265
+ },
266
+ bubbles: true,
267
+ cancelable: false,
268
+ }));
269
+ }
270
+ } catch (eventError) {
271
+ // Silently fail - event dispatch should never crash the app
272
+ }
273
+ }
274
+
275
+ // Wrap other errors as NetworkError
276
+ const networkError = error instanceof Error
277
+ ? new NetworkError(error.message, url, error)
278
+ : new NetworkError('Unknown error', url);
279
+
280
+ // Detailed logging via logger.logError
281
+ if (this.logger) {
282
+ this.logger.logError(
283
+ {
284
+ method,
285
+ url: url,
286
+ headers,
287
+ body: options?.formData || options?.body,
288
+ timestamp: startTime,
289
+ },
290
+ {
291
+ message: networkError.message,
292
+ duration,
293
+ timestamp: Date.now(),
294
+ }
295
+ );
296
+ }
297
+
298
+ throw networkError;
299
+ }
300
+ }
301
+ }