api-core-lib 12.0.0 → 12.0.4

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.
package/dist/index.d.mts CHANGED
@@ -1,41 +1,26 @@
1
- import { InternalAxiosRequestConfig, AxiosResponse, AxiosRequestConfig, AxiosProgressEvent, AxiosInstance, Method } from 'axios';
2
- import { Dispatch, SetStateAction } from 'react';
1
+ import { InternalAxiosRequestConfig, AxiosResponse, AxiosRequestConfig, AxiosProgressEvent, AxiosInstance, Method, AxiosError } from 'axios';
2
+ import * as React$1 from 'react';
3
+ import React__default, { Dispatch, SetStateAction } from 'react';
3
4
 
4
5
  /**
5
- * @file src/types.ts
6
- * @description This file serves as the central source for all data types and interfaces
7
- * used throughout the library. Defining types here ensures consistency, type safety,
8
- * and provides a clear API contract for the end-user.
9
- */
10
-
11
- /**
12
- * Defines the structure for pagination metadata returned by the API.
6
+ * يمثل معلومات الترقيم (Pagination) التي قد تعود من ה-API.
13
7
  */
14
8
  interface PaginationMeta {
15
9
  itemsPerPage: number;
16
10
  totalItems: number;
17
11
  currentPage: number;
18
12
  totalPages: number;
13
+ [key: string]: any;
19
14
  }
20
15
  /**
21
- * Represents the standard wrapper that an API might use for its responses.
22
- * @template T The type of the core data payload.
23
- */
24
- interface ApiResponse<T = any> {
25
- success?: boolean;
26
- data: T;
27
- message?: string;
28
- meta?: PaginationMeta;
29
- }
30
- /**
31
- * Defines the structure for a single field validation error.
16
+ * يمثل خطأ تحقق واحد لحقل معين.
32
17
  */
33
18
  interface ValidationError {
34
19
  field: string;
35
20
  message: string;
36
21
  }
37
22
  /**
38
- * Represents the unified error object produced by the library for any failed request.
23
+ * يمثل كائن الخطأ الموحد الذي تنتجه المكتبة.
39
24
  */
40
25
  interface ApiError {
41
26
  message: string;
@@ -45,12 +30,14 @@ interface ApiError {
45
30
  requestId?: string;
46
31
  }
47
32
  /**
48
- * The standardized, final response object that every library function returns.
49
- * This is the primary type developers will interact with.
50
- * @template T The type of the final, unwrapped data.
33
+ * الكائن القياسي والموحد الذي تعيده جميع دوال المكتبة.
34
+ * هذا هو النوع الأساسي الذي سيتعامل معه المطورون.
35
+ * @template T نوع البيانات الأساسية.
51
36
  */
52
37
  interface StandardResponse<T> {
53
38
  data: T | null;
39
+ links?: Record<string, string | null>;
40
+ meta?: PaginationMeta | Record<string, any>;
54
41
  rawResponse: any;
55
42
  error: ApiError | null;
56
43
  loading: boolean;
@@ -58,125 +45,30 @@ interface StandardResponse<T> {
58
45
  message?: string;
59
46
  validationErrors?: ValidationError[];
60
47
  }
61
- /**
62
- * Represents the set of authentication tokens managed by the library.
63
- */
64
48
  interface Tokens {
65
49
  accessToken: string | null;
66
50
  refreshToken: string | null;
67
51
  expiresAt?: number;
68
52
  tokenType?: string;
69
53
  }
70
- /**
71
- * An interface for a token manager, allowing the logic for token storage to be decoupled.
72
- * Consumers of the library can provide their own implementation (e.g., LocalStorage, Cookies).
73
- */
74
54
  interface TokenManager {
75
55
  getTokens(): Promise<Tokens>;
76
56
  setTokens(tokens: Tokens): Promise<void>;
77
57
  clearTokens(): Promise<void>;
78
- /**
79
- * Determines the operating context.
80
- * @returns `true` if tokens are in secure httpOnly cookies (server-side context).
81
- * @returns `false` if tokens are accessible from the client (e.g., localStorage).
82
- */
83
58
  isHttpOnly(): boolean;
84
59
  }
85
- /**
86
- * The context object passed to each middleware function in the pipeline.
87
- */
88
60
  interface MiddlewareContext {
89
61
  req: InternalAxiosRequestConfig;
90
62
  res?: AxiosResponse;
91
63
  error?: any;
92
64
  custom?: Record<string, any>;
93
65
  }
94
- /**
95
- * Defines the signature for a middleware function.
96
- */
97
66
  type Middleware = (context: MiddlewareContext, next: () => Promise<void>) => Promise<void>;
98
- /**
99
- * Extends the default Axios request configuration with custom properties for the library.
100
- */
101
- interface RequestConfig extends AxiosRequestConfig {
102
- /** If true, the request will bypass the token injection logic. */
103
- isPublic?: boolean;
104
- /** A key for managing request cancellation. */
105
- cancelTokenKey?: string;
106
- /** Callback for upload progress events. */
107
- onUploadProgress?: (progressEvent: AxiosProgressEvent) => void;
108
- /** Callback for download progress events. */
109
- onDownloadProgress?: (progressEvent: AxiosProgressEvent) => void;
110
- }
111
- /**
112
- * Defines a flexible query options interface for pagination, sorting, filtering, and searching.
113
- * Supports standard keys as well as any custom top-level query parameters.
114
- * @example { page: 1, limit: 10, search: 'term', status: 'published' }
115
- */
116
- interface QueryOptions {
117
- page?: number;
118
- limit?: number;
119
- search?: string;
120
- sortBy?: {
121
- key: string;
122
- direction: 'asc' | 'desc';
123
- }[];
124
- filter?: Record<string, any>;
125
- [key: string]: any;
126
- }
127
- /**
128
- * Defines additional options for action methods like create, update, or delete.
129
- */
130
- interface ActionOptions extends RequestConfig {
131
- /**
132
- * Overrides the default endpoint for a specific action. Useful for specialized routes.
133
- * @example update('123', { status: 'active' }, { endpoint: '/items/123/activate' })
134
- */
135
- endpoint?: string;
136
- /**
137
- * Overrides the `refetchAfterChange` setting for a single action.
138
- */
139
- refetch?: boolean;
140
- }
141
- /**
142
- * The main configuration object for the `useApi` hook.
143
- * @template T The data type the hook will manage.
144
- */
145
- interface UseApiConfig<T> {
146
- /** The base API endpoint for the resource (e.g., '/users'). */
147
- endpoint: string;
148
- /** Initial data to populate the state before the first fetch. */
149
- initialData?: T | null;
150
- /** Default query options to use for the initial fetch. */
151
- initialQuery?: QueryOptions;
152
- /** If false, the hook will not fetch data automatically on mount. */
153
- enabled?: boolean;
154
- /** If true, data will be refetched automatically after a successful create, update, or delete action. */
155
- refetchAfterChange?: boolean;
156
- /** A default `RequestConfig` to apply to all GET requests made by the hook. */
157
- requestConfig?: RequestConfig;
158
- encodeQuery?: boolean;
159
- pathParams?: Record<string, string | number>;
160
- /** Callback function executed on a successful action. */
161
- onSuccess?: (message: string, data?: T) => void;
162
- /** Callback function executed on a failed action. */
163
- onError?: (message: string, error?: ApiError) => void;
164
- }
165
- /**
166
- * Defines the configuration for the automatic token refresh mechanism.
167
- */
67
+ type LogLevel = 'debug' | 'info' | 'warn' | 'error' | 'silent';
168
68
  interface RefreshTokenConfig {
169
- /** The API path for the token refresh endpoint (e.g., '/auth/refresh'). */
170
69
  path: string;
171
- /** A function to build the request body for the refresh call. */
172
70
  buildRequestBody?: (refreshToken: string) => Record<string, any>;
173
- /** A function to build any custom headers for the refresh call. */
174
71
  buildRequestHeaders?: (currentTokens: Tokens) => Record<string, string>;
175
- /**
176
- * A function to extract the new tokens from the refresh API's response data.
177
- * @param responseData The raw data from the refresh API response.
178
- * @returns An object containing the new token details.
179
- */
180
72
  extractTokens: (responseData: any) => {
181
73
  accessToken: string;
182
74
  refreshToken?: string;
@@ -184,95 +76,88 @@ interface RefreshTokenConfig {
184
76
  tokenType?: string;
185
77
  };
186
78
  }
187
- /**
188
- * Defines the available levels for logging.
189
- * 'debug': Logs everything.
190
- * 'info': Logs standard requests and responses.
191
- * 'warn': Logs warnings and errors.
192
- * 'error': Logs only critical errors.
193
- * 'silent': Disables all logging.
194
- */
195
- type LogLevel = 'debug' | 'info' | 'warn' | 'error' | 'silent';
196
- /**
197
- * An interface for a custom logger, compatible with the standard `console` object.
198
- * It now includes a `debug` method for more granular logging.
199
- */
200
- /**
201
- * The main configuration object for the `createApiClient` factory function.
202
- */
203
79
  interface ApiClientConfig {
204
- /** The base URL for all API requests. */
205
80
  baseURL?: string;
206
- /** The token manager instance responsible for handling token storage. */
207
81
  tokenManager: TokenManager;
208
- /** The request timeout in milliseconds. */
209
82
  timeout?: number;
210
- /** Default headers to be sent with every request. */
211
83
  headers?: Record<string, string>;
212
- /** If true, cookies will be sent with cross-origin requests. */
213
84
  withCredentials?: boolean;
214
- /** Configuration for the automatic token refresh mechanism. */
215
85
  refreshTokenConfig?: RefreshTokenConfig;
216
- /** A callback function executed if the token refresh process fails. */
217
86
  onRefreshError?: (error: any) => void;
218
- /** A custom logger instance. Defaults to the browser `console`. */
219
- /** An array of middleware functions to be executed with every request. */
220
87
  middleware?: Middleware[];
221
- /**
222
- * Sets the verbosity of the internal logger.
223
- * @default 'info'
224
- */
225
88
  logLevel?: LogLevel;
226
- /**
227
- * If true, all requests will be treated as public by default.
228
- * A request can override this by explicitly setting `isPublic: false`.
229
- * @default false
230
- */
231
89
  defaultIsPublic?: boolean;
232
90
  maxTokenRefreshRetries?: number;
233
91
  maxQueueSize?: number;
234
92
  }
235
-
236
- declare function createApiClient(config: ApiClientConfig): AxiosInstance;
237
-
238
- /**
239
- * @file src/hooks/useApi.types.ts
240
- * @description This file defines the professional, publicly-facing types for the `useApi` hook,
241
- * providing a clean and stable contract for consumers.
242
- */
243
-
244
- /**
245
- * Configuration object for the `useApi` hook.
246
- * @template T The type of the data entity.
247
- */
93
+ interface RequestConfig extends AxiosRequestConfig {
94
+ isPublic?: boolean;
95
+ cancelTokenKey?: string;
96
+ onUploadProgress?: (progressEvent: AxiosProgressEvent) => void;
97
+ onDownloadProgress?: (progressEvent: AxiosProgressEvent) => void;
98
+ }
99
+ interface QueryOptions {
100
+ page?: number;
101
+ limit?: number;
102
+ search?: string;
103
+ sortBy?: {
104
+ key: string;
105
+ direction: 'asc' | 'desc';
106
+ }[];
107
+ filter?: Record<string, any>;
108
+ [key: string]: any;
109
+ }
110
+ interface ActionOptions extends RequestConfig {
111
+ endpoint?: string;
112
+ refetch?: boolean;
113
+ }
248
114
  /**
249
- * The primary state object managed by the `useApi` hook.
250
- * It contains the fetched data, loading status, and any potential errors.
251
- * @template T The type of the data entity being managed.
115
+ * يمثل إعدادات إجراء واحد داخل الموديول.
252
116
  */
253
- type UseApiState<T> = StandardResponse<T>;
117
+ interface ActionConfig<TInput = any, TOutput = any> {
118
+ method: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
119
+ path: string;
120
+ description?: string;
121
+ isList?: boolean;
122
+ invalidates?: string[];
123
+ }
254
124
  /**
255
- * A collection of callable functions for performing CRUD and other operations.
256
- * These actions automatically handle state updates like loading and refetching.
257
- * @template T The type of the data entity being managed.
125
+ * [مُحدَّث] يمثل الحالة التفاعلية الكاملة لإجراء واحد.
126
+ * هذا هو النوع الذي يتم إرجاعه في `states` من الهوك.
258
127
  */
259
- interface UseApiActions<T, TListItem = T extends (infer U)[] ? U : T> {
260
- fetch: () => Promise<void>;
261
- create: (newItem: Partial<TListItem>, options?: ActionOptions) => Promise<StandardResponse<TListItem>>;
262
- put: (id: string | number, item: TListItem, options?: ActionOptions) => Promise<StandardResponse<TListItem>>;
263
- update: (id: string | number, updatedItem: Partial<TListItem>, options?: ActionOptions) => Promise<StandardResponse<TListItem>>;
264
- remove: (id: string | number, options?: ActionOptions) => Promise<StandardResponse<any>>;
265
- bulkRemove: (ids: Array<string | number>, options?: ActionOptions) => Promise<StandardResponse<any>>;
128
+ interface ActionStateModule<TOutput> {
129
+ data: TOutput | null;
130
+ links?: Record<string, string | null>;
131
+ meta?: PaginationMeta | Record<string, any>;
132
+ error: ApiError | null;
133
+ loading: boolean;
134
+ success: boolean;
135
+ called: boolean;
136
+ message?: string;
137
+ validationErrors?: ValidationError[];
138
+ rawResponse: any | null;
139
+ isStale?: boolean;
140
+ lastSuccessAt?: number;
266
141
  }
267
142
  /**
268
- * A collection of functions and properties for controlling the query parameters
269
- * used for fetching data, such as pagination, sorting, and filtering.
143
+ * الكائن الموحد الذي يتم إرجاعه لكل إجراء، ويحتوي على حالته ومنفذه وأدوات التحكم.
270
144
  */
145
+ interface ExecutableAction<TInput, TOutput> {
146
+ state: ActionStateModule<TOutput>;
147
+ execute: (input?: TInput, options?: {
148
+ pathParams?: Record<string, any>;
149
+ config?: AxiosRequestConfig;
150
+ query?: QueryOptions;
151
+ }) => Promise<StandardResponse<TOutput>>;
152
+ reset: () => void;
153
+ query?: UseApiQuery;
154
+ }
155
+ type UseApiState<T> = StandardResponse<T>;
271
156
  interface UseApiQuery {
272
157
  /** The current query options state. */
273
158
  options: QueryOptions;
274
159
  /** A function to set the entire query options object at once. */
275
- setOptions: React.Dispatch<React.SetStateAction<QueryOptions>>;
160
+ setOptions: React__default.Dispatch<React__default.SetStateAction<QueryOptions>>;
276
161
  /** Sets the current page number. */
277
162
  setPage: (page: number) => void;
278
163
  /** Sets the number of items per page and resets to the first page. */
@@ -291,68 +176,86 @@ interface UseApiQuery {
291
176
  /** Resets the query options to their initial state. */
292
177
  reset: () => void;
293
178
  }
294
- /**
295
- * The complete return type of the `useApi` hook.
296
- * It encapsulates the state, actions, and query controls for a given API resource.
297
- * @template T The type of the data entity being managed.
298
- */
299
- interface UseApiReturn<T> {
300
- state: UseApiState<T>;
301
- setState: React.Dispatch<React.SetStateAction<UseApiState<T>>>;
302
- actions: UseApiActions<T>;
303
- query: UseApiQuery;
179
+ interface UseApiConfig<T> {
180
+ endpoint: string;
181
+ initialData?: T | null;
182
+ initialQuery?: QueryOptions;
183
+ enabled?: boolean;
184
+ refetchAfterChange?: boolean;
185
+ requestConfig?: RequestConfig;
186
+ pathParams?: Record<string, string | number>;
187
+ encodeQuery?: boolean;
188
+ onSuccess?: (message: string, data?: T) => void;
189
+ onError?: (message: string, error?: ApiError) => void;
304
190
  }
305
191
 
306
- interface ActionConfig<TInput = any, TOutput = any> {
192
+ declare function createApiClient(config: ApiClientConfig): AxiosInstance;
193
+
194
+ /** @description Extends the base ActionState with an `isStale` flag for automatic refetching. */
195
+ interface ActionState<TOutput> extends ActionStateModule<TOutput> {
196
+ isStale?: boolean;
197
+ }
198
+ /** @description Defines the configuration for a single API action within a module. */
199
+ interface ActionConfigModule<TInput = unknown, TOutput = unknown> {
307
200
  method: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
308
201
  path: string;
309
202
  description?: string;
310
- isList?: boolean;
203
+ hasQuery?: boolean;
204
+ autoFetch?: boolean;
311
205
  invalidates?: string[];
206
+ _input?: TInput;
207
+ _output?: TOutput;
312
208
  }
313
- interface ApiModuleConfig {
209
+ /** @description Defines the complete structure of an API module. */
210
+ interface ApiModuleConfig<TActions extends Record<string, ActionConfigModule<any, any>>> {
314
211
  baseEndpoint: string;
315
- actions: Record<string, ActionConfig<any, any>>;
212
+ actions: TActions;
316
213
  }
214
+ /** @description Configuration options passed directly to the `useApiModule` hook. */
317
215
  interface UseApiModuleOptions {
318
- onSuccess?: (actionName: string, message: string, data: any) => void;
216
+ onSuccess?: (actionName: string, message: string, data: unknown) => void;
319
217
  onError?: (actionName: string, message: string, error?: ApiError | null) => void;
320
- staleTime?: number;
321
- cacheTime?: number;
322
218
  refetchOnWindowFocus?: boolean;
219
+ pathParams?: Record<string, any>;
220
+ enabled?: boolean;
221
+ hydratedState?: string;
323
222
  }
324
- interface ActionState<TOutput> {
325
- data: TOutput | null;
326
- error: ApiError | null;
327
- loading: boolean;
328
- success: boolean;
329
- called: boolean;
330
- }
331
- /**
332
- * The unified object for a single action, containing its state, executor, and controls.
333
- * This is the new, more ergonomic return structure.
334
- */
335
- interface ExecutableAction<TInput, TOutput> {
336
- /** The reactive state for this specific action. */
337
- state: ActionState<TOutput>;
338
- /** The stable function to execute the API call. */
339
- execute: (input?: TInput, options?: {
340
- pathParams?: Record<string, any>;
341
- config?: AxiosRequestConfig;
342
- query?: QueryOptions;
343
- }) => Promise<StandardResponse<TOutput>>;
344
- /** A stable function to reset the action's state to its initial value. */
345
- reset: () => void;
346
- /** Query controls (pagination, sorting, etc.) available only if `isList: true`. */
347
- query?: UseApiQuery;
223
+ /** A utility type to infer the Input type (`TInput`) from an ActionConfigModule. */
224
+ type InputOf<TActionConfig> = TActionConfig extends ActionConfigModule<infer TInput, any> ? TInput : never;
225
+ /** A utility type to infer the Output type (`TOutput`) from an ActionConfigModule. */
226
+ type OutputOf<TActionConfig> = TActionConfig extends ActionConfigModule<any, infer TOutput> ? TOutput : never;
227
+ /** @description Defines the options for the `execute` function, enabling optimistic updates. */
228
+ interface ExecuteOptions<TInput, TOutput, TContext = unknown> {
229
+ pathParams?: Record<string, any>;
230
+ config?: AxiosRequestConfig;
231
+ onMutate?: (variables: TInput) => TContext | Promise<TContext>;
232
+ onSuccess?: (data: TOutput, context?: TContext) => void;
233
+ onError?: (error: ApiError, context?: TContext) => void;
348
234
  }
349
- /**
350
- * The final, fully-typed object returned by the useApiModule hook.
351
- * It's a dictionary of executable actions.
352
- */
353
- type ModuleActions<TModule extends ApiModuleConfig> = {
354
- [K in keyof TModule['actions']]: TModule['actions'][K] extends ActionConfig<infer TInput, infer TOutput> ? ExecutableAction<TInput, TOutput> : never;
235
+ /** @description A fully-typed object representing the callable actions for a module. */
236
+ type ModuleActions<TActions extends Record<string, ActionConfigModule<any, any>>> = {
237
+ [K in keyof TActions]: {
238
+ execute: <TContext = unknown>(input?: InputOf<TActions[K]>, options?: ExecuteOptions<InputOf<TActions[K]>, OutputOf<TActions[K]>, TContext>) => Promise<StandardResponse<OutputOf<TActions[K]>>>;
239
+ reset: (input?: InputOf<TActions[K]>, options?: {
240
+ pathParams?: Record<string, any>;
241
+ }) => void;
242
+ };
243
+ };
244
+ /** @description A fully-typed object representing the reactive states for each action in a module. */
245
+ type ModuleStates<TActions extends Record<string, ActionConfigModule<any, any>>> = {
246
+ [K in keyof TActions]: ActionState<OutputOf<TActions[K]>>;
355
247
  };
248
+ /** @description The complete, fully-typed return object of the `useApiModule` hook. */
249
+ interface UseApiModuleReturn<TActions extends Record<string, ActionConfigModule<any, any>>> {
250
+ states: ModuleStates<TActions>;
251
+ actions: ModuleActions<TActions>;
252
+ queries: {
253
+ [K in keyof TActions]?: TActions[K] extends {
254
+ hasQuery: true;
255
+ } ? UseApiQuery : never;
256
+ };
257
+ dehydrate: () => string;
258
+ }
356
259
 
357
260
  /**
358
261
  * A factory function to create a reusable set of API services for a specific endpoint.
@@ -369,22 +272,30 @@ declare function createApiServices<T>(axiosInstance: AxiosInstance, baseEndpoint
369
272
  bulkDelete: (ids: Array<string | number>, config?: ActionOptions) => Promise<StandardResponse<any>>;
370
273
  upload: (file: File, additionalData?: Record<string, any>, config?: ActionOptions) => Promise<StandardResponse<any>>;
371
274
  };
372
-
373
275
  /**
374
- * @file src/core/utils.ts
375
- * @description
376
- * يحتوي هذا الملف على مجموعة من الدوال المساعدة المستخدمة في جميع أنحاء المكتبة،
377
- * مثل بناء سلاسل الاستعلام (query strings) وإدارة إلغاء الطلبات،
378
- * بالإضافة إلى دوال التحقق من الأنواع (type guards).
276
+ * [نسخة محدثة ومحسّنة]
277
+ * دالة عامة وصريحة لتنفيذ أي طلب API.
278
+ * تستقبل وسائط منظمة بدلاً من محاولة تخمينها.
279
+ *
280
+ * @param axiosInstance - نسخة Axios.
281
+ * @param baseEndpoint - نقطة النهاية الأساسية للموديول.
282
+ * @param actionConfig - إعدادات الإجراء المحدد.
283
+ * @param params - كائن يحتوي على جميع البارامترات اللازمة للطلب.
284
+ * @returns Promise<StandardResponse<any>>
379
285
  */
286
+ declare function callDynamicApi(axiosInstance: AxiosInstance, baseEndpoint: string, actionConfig: ActionConfigModule<any, any>, params: {
287
+ pathParams?: Record<string, string | number>;
288
+ body?: any;
289
+ config?: AxiosRequestConfig;
290
+ }): Promise<StandardResponse<any>>;
380
291
 
381
292
  /**
382
- * يبني سلسلة استعلام (query string) من كائن خيارات مرن.
383
- * يتعامل مع البارامترات القياسية والمخصصة.
384
- * @param query - كائن من نوع QueryOptions.
293
+ * [نسخة مطورة] يبني سلسلة استعلام (query string) من كائن الخيارات.
294
+ * يدعم الآن الفلاتر المتداخلة (filter[key]=value) والترتيب المتعدد.
295
+ * @param options - كائن خيارات الاستعلام (فلترة, ترتيب, ...).
385
296
  * @returns سلسلة استعلام جاهزة للإضافة للرابط.
386
297
  */
387
- declare function buildPaginateQuery(query: QueryOptions): string;
298
+ declare function buildPaginateQuery(options: QueryOptions): string;
388
299
 
389
300
  /**
390
301
  * Defines a single custom API action.
@@ -431,29 +342,23 @@ declare class CacheManager {
431
342
  set<T>(key: string, data: T, duration?: number): void;
432
343
  get<T>(key: string): T | null;
433
344
  /**
434
- * [دالة جديدة] تعيد عنصر الـ Cache بالكامل (البيانات + معلومات إضافية)
435
- * دون حذفه عند انتهاء الصلاحية. هذا يسمح لنا بتطبيق منطق stale-while-revalidate.
345
+ * [FIX] تم تحويلها إلى دالة عامة (generic) لتعيد النوع الصحيح.
346
+ * الآن بدلًا من إرجاع CacheItem<unknown>، ستُرجع CacheItem<T>.
436
347
  */
437
348
  getWithMeta<T>(key: string): CacheItem<T> | null;
438
349
  delete(key: string): void;
439
350
  clear(): void;
440
- /**
441
- * [دالة جديدة] تقوم بإبطال (حذف) جميع عناصر الـ Cache التي تبدأ ببادئة معينة.
442
- * أساسية لعملية invalidation التلقائية.
443
- */
444
351
  invalidateByPrefix(prefix: string): void;
445
352
  }
446
353
  declare const cacheManager: CacheManager;
447
354
 
448
- declare const processResponse: <T>(responseOrError: AxiosResponse<any> | ApiError) => StandardResponse<T>;
449
-
450
- declare function useApi<T>(axiosInstance: AxiosInstance, config: UseApiConfig<T>): UseApiReturn<T>;
451
-
452
355
  /**
453
- * هوك متقدم يقوم ببناء مجموعة من الإجراءات القابلة للتنفيذ من إعدادات موديول API،
454
- * مع فصل تام بين الدوال المستقرة والحالات المتغيرة لمنع الحلقات اللانهائية.
356
+ * [النسخة النهائية والمضمونة]
357
+ * تستخدم دوال حماية النوع المخصصة للقضاء على أخطاء 'never' بشكل نهائي.
455
358
  */
456
- declare function useApiModule<TModule extends ApiModuleConfig>(axiosInstance: AxiosInstance, moduleConfig: TModule, options?: UseApiModuleOptions): any;
359
+ declare const processResponse: <T>(responseOrError: AxiosResponse<any> | AxiosError) => StandardResponse<T>;
360
+
361
+ declare function useApi<T>(axiosInstance: AxiosInstance, config: UseApiConfig<T>): any;
457
362
 
458
363
  /**
459
364
  * Represents the internal state of the `useApiRecord` hook.
@@ -502,8 +407,17 @@ interface UseApiRecordActions<T> {
502
407
  * @template T The data type of the record.
503
408
  */
504
409
  interface UseApiRecordConfig<T> {
505
- /** The base API endpoint for the resource (e.g., '/users'). */
410
+ /**
411
+ * The base API endpoint template for the resource.
412
+ * Can contain placeholders like `{endpointName}`.
413
+ * @example 'v1/dynamic/{endpointName}'
414
+ */
506
415
  endpoint: string;
416
+ /**
417
+ * An object containing key-value pairs to replace placeholders in the endpoint template.
418
+ * @example { endpointName: 'products' }
419
+ */
420
+ pathParams?: Record<string, string | number>;
507
421
  /** The unique identifier of the record to fetch or modify. */
508
422
  recordId?: string | number | null;
509
423
  /** Optional initial data to populate the state before the first fetch is complete. */
@@ -535,7 +449,12 @@ interface UseApiRecordReturn<T> {
535
449
  /**
536
450
  * A React hook for managing the lifecycle of a single API resource (a record).
537
451
  * It handles fetching, updating, replacing, and deleting a record, while managing
538
- * loading, error, and data states.
452
+ * loading, error, and data states. It supports dynamic path parameters for flexible API routing.
453
+ *
454
+ * @template T The data type of the record being managed.
455
+ * @param {AxiosInstance} axiosInstance - The configured Axios instance for making API calls.
456
+ * @param {UseApiRecordConfig<T>} config - Configuration options for the hook.
457
+ * @returns {UseApiRecordReturn<T>} An object containing the state, actions, and setState function.
539
458
  */
540
459
  declare function useApiRecord<T>(axiosInstance: AxiosInstance, config: UseApiRecordConfig<T>): UseApiRecordReturn<T>;
541
460
 
@@ -543,6 +462,85 @@ type EffectCallback = () => (void | (() => void));
543
462
  type DependencyList = readonly any[];
544
463
  declare function useDeepCompareEffect(callback: EffectCallback, dependencies: DependencyList): void;
545
464
 
465
+ declare const ApiModuleProvider: React$1.Provider<UseApiModuleReturn<any> | null>;
466
+ declare function useModuleContext<TModule extends ApiModuleConfig<any>>(): UseApiModuleReturn<TModule['actions']>;
467
+ declare function useApiModule<TActions extends Record<string, ActionConfigModule<any, any>>>(axiosInstance: AxiosInstance, moduleConfig: ApiModuleConfig<TActions>, options?: UseApiModuleOptions): UseApiModuleReturn<TActions>;
468
+
469
+ declare class GlobalStateManager {
470
+ private store;
471
+ /**
472
+ * يحصل على لقطة (snapshot) للحالة الحالية لمفتاح معين.
473
+ */
474
+ getSnapshot<T>(key: string): ActionStateModule<T>;
475
+ /**
476
+ * يسجل دالة callback للاستماع إلى التغييرات على مفتاح معين.
477
+ * @returns دالة لإلغاء الاشتراك.
478
+ */
479
+ subscribe(key: string, callback: () => void): () => void;
480
+ /**
481
+ * يحدّث الحالة لمفتاح معين ويقوم بإعلام جميع المشتركين.
482
+ */
483
+ setState<T>(key: string, updater: (prevState: ActionStateModule<T>) => ActionStateModule<T>): void;
484
+ /**
485
+ * يجعل البيانات المرتبطة بمفتاح معين "قديمة" (stale).
486
+ */
487
+ invalidate(key: string): void;
488
+ /**
489
+ * [نسخة محدثة وأكثر قوة]
490
+ * يجعل كل البيانات التي تبدأ بمفتاح معين "قديمة" (stale).
491
+ * @example invalidateByPrefix('myModule/list::') سيبطل كل صفحات القائمة.
492
+ */
493
+ invalidateByPrefix(prefix: string): void;
494
+ /**
495
+ * Serializes the current state of the query store into a JSON string.
496
+ * This is used on the server to pass the initial state to the client.
497
+ * @returns A JSON string representing the dehydrated state.
498
+ */
499
+ dehydrate(): string;
500
+ /**
501
+ * Merges a dehydrated state object into the current store.
502
+ * This is used on the client to hydrate the state received from the server.
503
+ * @param hydratedState - A JSON string from the `dehydrate` method.
504
+ */
505
+ rehydrate(hydratedState: string): void;
506
+ }
507
+ declare const globalStateManager: GlobalStateManager;
508
+
509
+ /**
510
+ * @file src/hooks/useApi.types.ts
511
+ * @description This file defines the professional, publicly-facing types for the `useApi` hook,
512
+ * providing a clean and stable contract for consumers.
513
+ */
514
+
515
+ /**
516
+ * Configuration object for the `useApi` hook.
517
+ * @template T The type of the data entity.
518
+ */
519
+ /**
520
+ * A collection of callable functions for performing CRUD and other operations.
521
+ * These actions automatically handle state updates like loading and refetching.
522
+ * @template T The type of the data entity being managed.
523
+ */
524
+ interface UseApiActions<T, TListItem = T extends (infer U)[] ? U : T> {
525
+ fetch: (querryOptions?: QueryOptions) => Promise<void>;
526
+ create: (newItem: Partial<TListItem>, options?: ActionOptions) => Promise<StandardResponse<TListItem>>;
527
+ put: (id: string | number, item: TListItem, options?: ActionOptions) => Promise<StandardResponse<TListItem>>;
528
+ update: (id: string | number, updatedItem: Partial<TListItem>, options?: ActionOptions) => Promise<StandardResponse<TListItem>>;
529
+ remove: (id: string | number, options?: ActionOptions) => Promise<StandardResponse<any>>;
530
+ bulkRemove: (ids: Array<string | number>, options?: ActionOptions) => Promise<StandardResponse<any>>;
531
+ }
532
+ /**
533
+ * The complete return type of the `useApi` hook.
534
+ * It encapsulates the state, actions, and query controls for a given API resource.
535
+ * @template T The type of the data entity being managed.
536
+ */
537
+ interface UseApiReturn<T> {
538
+ state: StandardResponse<T>;
539
+ setState: React.Dispatch<React.SetStateAction<StandardResponse<T>>>;
540
+ actions: UseApiActions<T>;
541
+ query: UseApiQuery;
542
+ }
543
+
546
544
  type ApiResourceStatus = 'idle' | 'loading' | 'success' | 'error';
547
545
  interface UseApiResourceState<T> {
548
546
  data: T | T[] | null;
@@ -589,4 +587,4 @@ interface UseApiResourceReturn<T, TCreate, TUpdate, TPathParams> {
589
587
  setQuery: React.Dispatch<React.SetStateAction<QueryOptions>>;
590
588
  }
591
589
 
592
- export { type ActionConfig, type ActionOptions, type ActionState, type ApiClientConfig, type ApiError, type ApiModuleConfig, type ApiResourceStatus, type ApiResponse, type ExecutableAction, type LogLevel, type Middleware, type MiddlewareContext, type ModuleActions, type PaginationMeta, type QueryOptions, type RefreshTokenConfig, type RequestConfig, type StandardResponse, type TokenManager, type Tokens, type UseApiActions, type UseApiConfig, type UseApiModuleOptions, type UseApiQuery, type UseApiRecordActions, type UseApiRecordConfig, type UseApiRecordReturn, type UseApiRecordState, type UseApiResourceActions, type UseApiResourceConfig, type UseApiResourceReturn, type UseApiResourceState, type UseApiReturn, type UseApiState, type ValidationError, buildPaginateQuery, cacheManager, createApiActions, createApiClient, createApiServices, processResponse, useApi, useApiModule, useApiRecord, useDeepCompareEffect };
590
+ export { type ActionConfig, type ActionConfigModule, type ActionOptions, type ActionState, type ActionStateModule, type ApiClientConfig, type ApiError, type ApiModuleConfig, ApiModuleProvider, type ApiResourceStatus, type ExecutableAction, type ExecuteOptions, type InputOf, type LogLevel, type Middleware, type MiddlewareContext, type ModuleActions, type ModuleStates, type OutputOf, type PaginationMeta, type QueryOptions, type RefreshTokenConfig, type RequestConfig, type StandardResponse, type TokenManager, type Tokens, type UseApiActions, type UseApiConfig, type UseApiModuleOptions, type UseApiModuleReturn, type UseApiQuery, type UseApiRecordActions, type UseApiRecordConfig, type UseApiRecordReturn, type UseApiRecordState, type UseApiResourceActions, type UseApiResourceConfig, type UseApiResourceReturn, type UseApiResourceState, type UseApiReturn, type UseApiState, type ValidationError, buildPaginateQuery, cacheManager, callDynamicApi, createApiActions, createApiClient, createApiServices, globalStateManager, processResponse, useApi, useApiModule, useApiRecord, useDeepCompareEffect, useModuleContext };