api-core-lib 9.9.8 → 10.9.9

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
@@ -259,6 +259,195 @@ interface ApiClientConfig {
259
259
  */
260
260
  declare function createApiClient(config: ApiClientConfig): AxiosInstance;
261
261
 
262
+ /**
263
+ * @file src/hooks/useApi.types.ts
264
+ * @description This file defines the professional, publicly-facing types for the `useApi` hook,
265
+ * providing a clean and stable contract for consumers.
266
+ */
267
+
268
+ /**
269
+ * Configuration object for the `useApi` hook.
270
+ * @template T The type of the data entity.
271
+ */
272
+ /**
273
+ * The primary state object managed by the `useApi` hook.
274
+ * It contains the fetched data, loading status, and any potential errors.
275
+ * @template T The type of the data entity being managed.
276
+ */
277
+ type UseApiState<T> = StandardResponse<T>;
278
+ /**
279
+ * A collection of callable functions for performing CRUD and other operations.
280
+ * These actions automatically handle state updates like loading and refetching.
281
+ * @template T The type of the data entity being managed.
282
+ */
283
+ interface UseApiActions<T, TListItem = T extends (infer U)[] ? U : T> {
284
+ fetch: () => Promise<void>;
285
+ create: (newItem: Partial<TListItem>, options?: ActionOptions) => Promise<StandardResponse<TListItem>>;
286
+ put: (id: string | number, item: TListItem, options?: ActionOptions) => Promise<StandardResponse<TListItem>>;
287
+ update: (id: string | number, updatedItem: Partial<TListItem>, options?: ActionOptions) => Promise<StandardResponse<TListItem>>;
288
+ remove: (id: string | number, options?: ActionOptions) => Promise<StandardResponse<any>>;
289
+ bulkRemove: (ids: Array<string | number>, options?: ActionOptions) => Promise<StandardResponse<any>>;
290
+ }
291
+ /**
292
+ * A collection of functions and properties for controlling the query parameters
293
+ * used for fetching data, such as pagination, sorting, and filtering.
294
+ */
295
+ interface UseApiQuery {
296
+ /** The current query options state. */
297
+ options: QueryOptions;
298
+ /** A function to set the entire query options object at once. */
299
+ setOptions: React.Dispatch<React.SetStateAction<QueryOptions>>;
300
+ /** Sets the current page number. */
301
+ setPage: (page: number) => void;
302
+ /** Sets the number of items per page and resets to the first page. */
303
+ setLimit: (limit: number) => void;
304
+ /** Sets the search term and resets to the first page. */
305
+ setSearchTerm: (search: string) => void;
306
+ /** Sets the sorting configuration. */
307
+ setSorting: (sortBy: {
308
+ key: string;
309
+ direction: 'asc' | 'desc';
310
+ }[]) => void;
311
+ /** Sets the filter object and resets to the first page. */
312
+ setFilters: (filter: Record<string, any>) => void;
313
+ /** Sets a single, custom query parameter. */
314
+ setQueryParam: (key: string, value: any) => void;
315
+ /** Resets the query options to their initial state. */
316
+ reset: () => void;
317
+ }
318
+ /**
319
+ * The complete return type of the `useApi` hook.
320
+ * It encapsulates the state, actions, and query controls for a given API resource.
321
+ * @template T The type of the data entity being managed.
322
+ */
323
+ interface UseApiReturn<T> {
324
+ state: UseApiState<T>;
325
+ setState: React.Dispatch<React.SetStateAction<UseApiState<T>>>;
326
+ actions: UseApiActions<T>;
327
+ query: UseApiQuery;
328
+ }
329
+
330
+ /**
331
+ * يصف إجراءً واحدًا داخل وحدة API، مع أنواع دقيقة للإدخال والإخراج.
332
+ * @template TInput نوع بيانات الإدخال (الجسم أو معاملات الاستعلام).
333
+ * @template TOutput نوع البيانات التي يتم إرجاعها في `data` عند النجاح.
334
+ */
335
+ interface ActionConfig<TInput = any, TOutput = any> {
336
+ /** نوع طلب HTTP. */
337
+ method: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
338
+ /**
339
+ * المسار النسبي للإجراء. يمكن أن يحتوي على متغيرات مثل `{id}` أو `{tenantId}`.
340
+ * مثال: '/{id}/activate'
341
+ */
342
+ path: string;
343
+ /**
344
+ * وصف للإجراء، مفيد للتوثيق وتلميحات محرر الكود.
345
+ */
346
+ description?: string;
347
+ /**
348
+ * إذا كان `true`، فهذا يعني أن الإجراء يجلب قائمة بيانات ويدعم معاملات الاستعلام (pagination, sorting).
349
+ * سيتم تزويد هذا الإجراء بأدوات التحكم `query` تلقائيًا.
350
+ */
351
+ isList?: boolean;
352
+ /**
353
+ * قائمة بأسماء الإجراءات (من نفس الموديول) التي يجب إبطال بياناتها في الـ Cache بعد نجاح هذا الإجراء.
354
+ * أساسي لمزامنة البيانات تلقائيًا بعد عمليات التعديل (Mutations).
355
+ * مثال: إجراء `update` يجب أن يبطل `getOne` و `list`.
356
+ */
357
+ invalidates?: string[];
358
+ }
359
+ /**
360
+ * يمثل الإعداد الكامل لوحدة API. هذا هو "مصدر الحقيقة" لمجموعة من نقاط النهاية.
361
+ */
362
+ interface ApiModuleConfig {
363
+ /** نقطة النهاية الأساسية للموديول (مثل '/api/v1/products'). */
364
+ baseEndpoint: string;
365
+ /** قاموس يحتوي على جميع الإجراءات المتاحة في هذا الموديول. المفتاح هو اسم الإجراء. */
366
+ actions: Record<string, ActionConfig<any, any>>;
367
+ }
368
+ /**
369
+ * إعدادات اختيارية لتخصيص سلوك الهوك `useApiModule`.
370
+ */
371
+ interface UseApiModuleOptions {
372
+ /**
373
+ * دالة callback تُنفذ عند نجاح أي إجراء.
374
+ * @param actionName اسم الإجراء الذي نجح.
375
+ * @param message رسالة النجاح من الـ API.
376
+ * @param data البيانات المُرجعة.
377
+ */
378
+ onSuccess?: (actionName: string, message: string, data: any) => void;
379
+ /**
380
+ * دالة callback تُنفذ عند فشل أي إجراء.
381
+ * @param actionName اسم الإجراء الذي فشل.
382
+ * @param message رسالة الخطأ من الـ API.
383
+ * @param error كائن الخطأ الموحد.
384
+ */
385
+ onError?: (actionName: string, message: string, error?: ApiError | null) => void;
386
+ /**
387
+ * المدة التي تعتبر فيها البيانات "حية" (fresh) بالمللي ثانية.
388
+ * خلال هذه المدة، لن يتم إرسال طلب شبكة جديد لنفس البيانات.
389
+ * الافتراضي: `0` (مما يعني أنها تعتبر "قديمة" stale فورًا).
390
+ */
391
+ staleTime?: number;
392
+ /**
393
+ * مدة بقاء البيانات في الـ Cache (بالمللي ثانية) قبل أن يتم حذفها تلقائيًا.
394
+ * يمرر إلى `cacheManager.set`. إذا لم يتم تحديده، يستخدم `CacheManager` قيمته الافتراضية.
395
+ */
396
+ cacheTime?: number;
397
+ /**
398
+ * إذا كان `true`، سيتم إعادة جلب جميع الإجراءات التي تم استدعاؤها عند عودة المستخدم إلى نافذة التطبيق.
399
+ * الافتراضي: `true`.
400
+ */
401
+ refetchOnWindowFocus?: boolean;
402
+ }
403
+ /**
404
+ * الحالة التي يديرها كل إجراء على حدة.
405
+ * @template TOutput نوع بيانات الإخراج.
406
+ */
407
+ interface ActionState<TOutput> {
408
+ /** البيانات التي تم جلبها بنجاح. تكون `null` في البداية أو عند حدوث خطأ. */
409
+ data: TOutput | null;
410
+ /** كائن الخطأ في حال فشل الطلب. */
411
+ error: ApiError | null;
412
+ /** `true` أثناء تنفيذ طلب الشبكة. */
413
+ loading: boolean;
414
+ /** `true` إذا كان آخر طلب قد نجح. */
415
+ success: boolean;
416
+ /** `true` إذا تم استدعاء الإجراء مرة واحدة على الأقل. مفيد للتمييز بين الحالة الأولية وحالة "لم يتم العثور على بيانات". */
417
+ called: boolean;
418
+ }
419
+ /**
420
+ * الكائن التنفيذي للإجراء، يجمع بين دالة التنفيذ وحالته الخاصة.
421
+ * @template TInput نوع بيانات الإدخال.
422
+ * @template TOutput نوع بيانات الإخراج.
423
+ */
424
+ interface ExecutableAction<TInput, TOutput> {
425
+ /**
426
+ * الدالة الرئيسية لتنفيذ الإجراء.
427
+ * @param input بيانات الإدخال (الجسم أو معاملات الاستعلام).
428
+ * @param options خيارات إضافية للطلب مثل `pathParams` و `config` Axios.
429
+ * @returns `Promise` يحتوي على الاستجابة الموحدة `StandardResponse`.
430
+ */
431
+ execute: (input?: TInput, options?: {
432
+ pathParams?: Record<string, any>;
433
+ config?: AxiosRequestConfig;
434
+ query?: QueryOptions;
435
+ }) => Promise<StandardResponse<TOutput>>;
436
+ /** الحالة الحالية لهذا الإجراء المحدد. */
437
+ state: ActionState<TOutput>;
438
+ /** دالة لإعادة حالة هذا الإجراء إلى وضعها الأولي. */
439
+ reset: () => void;
440
+ /** أدوات التحكم بالاستعلام (pagination, sorting) متاحة فقط للإجراءات المعرفة بـ `isList: true`. */
441
+ query?: UseApiQuery;
442
+ }
443
+ /**
444
+ * النوع النهائي الذي يتم إرجاعه من الهوك `useApiModule`.
445
+ * وهو عبارة عن قاموس من الإجراءات القابلة للتنفيذ، مع أنواع مستنتجة بالكامل.
446
+ */
447
+ type ModuleActions<TModule extends ApiModuleConfig> = {
448
+ [K in keyof TModule['actions']]: TModule['actions'][K] extends ActionConfig<infer TInput, infer TOutput> ? ExecutableAction<TInput, TOutput> : never;
449
+ };
450
+
262
451
  /**
263
452
  * A factory function to create a reusable set of API services for a specific endpoint.
264
453
  * It provides full CRUD operations plus advanced features like bulk deletion and file uploads,
@@ -325,13 +514,28 @@ declare function createApiActions<TActions extends Record<string, {
325
514
  [K in keyof TActions]: ApiAction<TActions[K]['requestType'], TActions[K]['responseType']>;
326
515
  };
327
516
 
517
+ interface CacheItem<T> {
518
+ data: T;
519
+ timestamp: number;
520
+ duration: number;
521
+ }
328
522
  declare class CacheManager {
329
523
  private cache;
330
524
  private defaultDuration;
331
525
  set<T>(key: string, data: T, duration?: number): void;
332
526
  get<T>(key: string): T | null;
527
+ /**
528
+ * [دالة جديدة] تعيد عنصر الـ Cache بالكامل (البيانات + معلومات إضافية)
529
+ * دون حذفه عند انتهاء الصلاحية. هذا يسمح لنا بتطبيق منطق stale-while-revalidate.
530
+ */
531
+ getWithMeta<T>(key: string): CacheItem<T> | null;
333
532
  delete(key: string): void;
334
533
  clear(): void;
534
+ /**
535
+ * [دالة جديدة] تقوم بإبطال (حذف) جميع عناصر الـ Cache التي تبدأ ببادئة معينة.
536
+ * أساسية لعملية invalidation التلقائية.
537
+ */
538
+ invalidateByPrefix(prefix: string): void;
335
539
  }
336
540
  declare const cacheManager: CacheManager;
337
541
 
@@ -346,74 +550,54 @@ declare const cacheManager: CacheManager;
346
550
  */
347
551
  declare const processResponse: <T>(responseOrError: AxiosResponse<any> | ApiError, log?: boolean) => StandardResponse<T>;
348
552
 
349
- /**
350
- * @file src/hooks/useApi.types.ts
351
- * @description This file defines the professional, publicly-facing types for the `useApi` hook,
352
- * providing a clean and stable contract for consumers.
353
- */
553
+ declare function useApi<T>(axiosInstance: AxiosInstance, config: UseApiConfig<T>): UseApiReturn<T>;
354
554
 
355
- /**
356
- * Configuration object for the `useApi` hook.
357
- * @template T The type of the data entity.
358
- */
359
- /**
360
- * The primary state object managed by the `useApi` hook.
361
- * It contains the fetched data, loading status, and any potential errors.
362
- * @template T The type of the data entity being managed.
363
- */
364
- type UseApiState<T> = StandardResponse<T>;
365
- /**
366
- * A collection of callable functions for performing CRUD and other operations.
367
- * These actions automatically handle state updates like loading and refetching.
368
- * @template T The type of the data entity being managed.
369
- */
370
- interface UseApiActions<T, TListItem = T extends (infer U)[] ? U : T> {
371
- fetch: () => Promise<void>;
372
- create: (newItem: Partial<TListItem>, options?: ActionOptions) => Promise<StandardResponse<TListItem>>;
373
- put: (id: string | number, item: TListItem, options?: ActionOptions) => Promise<StandardResponse<TListItem>>;
374
- update: (id: string | number, updatedItem: Partial<TListItem>, options?: ActionOptions) => Promise<StandardResponse<TListItem>>;
375
- remove: (id: string | number, options?: ActionOptions) => Promise<StandardResponse<any>>;
376
- bulkRemove: (ids: Array<string | number>, options?: ActionOptions) => Promise<StandardResponse<any>>;
555
+ declare function useApiModule<TModule extends ApiModuleConfig>(axiosInstance: AxiosInstance, moduleConfig: TModule, options?: UseApiModuleOptions): ModuleActions<TModule>;
556
+
557
+ type ApiResourceStatus = 'idle' | 'loading' | 'success' | 'error';
558
+ interface UseApiResourceState<T> {
559
+ data: T | T[] | null;
560
+ error: ApiError | null;
561
+ status: ApiResourceStatus;
562
+ isFetching: boolean;
563
+ isMutating: boolean;
564
+ isSuccess: boolean;
565
+ lastResponse?: StandardResponse<any>;
377
566
  }
378
- /**
379
- * A collection of functions and properties for controlling the query parameters
380
- * used for fetching data, such as pagination, sorting, and filtering.
381
- */
382
- interface UseApiQuery {
383
- /** The current query options state. */
384
- options: QueryOptions;
385
- /** A function to set the entire query options object at once. */
386
- setOptions: React.Dispatch<React.SetStateAction<QueryOptions>>;
387
- /** Sets the current page number. */
388
- setPage: (page: number) => void;
389
- /** Sets the number of items per page and resets to the first page. */
390
- setLimit: (limit: number) => void;
391
- /** Sets the search term and resets to the first page. */
392
- setSearchTerm: (search: string) => void;
393
- /** Sets the sorting configuration. */
394
- setSorting: (sortBy: {
395
- key: string;
396
- direction: 'asc' | 'desc';
397
- }[]) => void;
398
- /** Sets the filter object and resets to the first page. */
399
- setFilters: (filter: Record<string, any>) => void;
400
- /** Sets a single, custom query parameter. */
401
- setQueryParam: (key: string, value: any) => void;
402
- /** Resets the query options to their initial state. */
567
+ interface UseApiResourceActions<T, TCreate, TUpdate, TPathParams> {
568
+ fetch: (pathParams?: TPathParams, queryOptions?: QueryOptions) => Promise<StandardResponse<T[]>>;
569
+ fetchOne: (pathParams: TPathParams & {
570
+ id: string | number;
571
+ }, queryOptions?: QueryOptions) => Promise<StandardResponse<T>>;
572
+ create: (newItem: TCreate, pathParams?: TPathParams, options?: ActionOptions) => Promise<StandardResponse<T>>;
573
+ update: (id: string | number, updatedItem: TUpdate, pathParams?: TPathParams, options?: ActionOptions) => Promise<StandardResponse<T>>;
574
+ remove: (id: string | number, pathParams?: TPathParams, options?: ActionOptions) => Promise<StandardResponse<any>>;
403
575
  reset: () => void;
404
576
  }
405
- /**
406
- * The complete return type of the `useApi` hook.
407
- * It encapsulates the state, actions, and query controls for a given API resource.
408
- * @template T The type of the data entity being managed.
409
- */
410
- interface UseApiReturn<T> {
411
- state: UseApiState<T>;
412
- setState: React.Dispatch<React.SetStateAction<UseApiState<T>>>;
413
- actions: UseApiActions<T>;
577
+ interface UseApiResourceConfig<TPathParams> {
578
+ /**
579
+ * The API endpoint template. Can be a static string or a function
580
+ * that builds the URL from parameters.
581
+ * @example '/users'
582
+ * @example (params) => `/modules/${params.moduleName}/records`
583
+ */
584
+ endpoint: string | ((params: TPathParams) => string);
585
+ /** Initial data to populate the state. */
586
+ initialData?: any;
587
+ /** Controls the verbosity of console logs for debugging. */
588
+ logLevel?: LogLevel;
589
+ /** Unique identifier for this hook instance, used in logging. */
590
+ logKey?: string;
591
+ /** Callback for success */
592
+ onSuccess?: (message: string, data?: any) => void;
593
+ /** Callback for error */
594
+ onError?: (message: string, error?: ApiError) => void;
595
+ }
596
+ interface UseApiResourceReturn<T, TCreate, TUpdate, TPathParams> {
597
+ state: UseApiResourceState<T>;
598
+ actions: UseApiResourceActions<T, TCreate, TUpdate, TPathParams>;
414
599
  query: UseApiQuery;
600
+ setQuery: React.Dispatch<React.SetStateAction<QueryOptions>>;
415
601
  }
416
602
 
417
- declare function useApi<T>(axiosInstance: AxiosInstance, config: UseApiConfig<T>): UseApiReturn<T>;
418
-
419
- export { type ActionOptions, type ApiClientConfig, type ApiError, type ApiResponse, type LogLevel, type Logger, type Middleware, type MiddlewareContext, type PaginationMeta, type QueryOptions, type RefreshTokenConfig, type RequestConfig, type StandardResponse, type TokenManager, type Tokens, type UseApiActions, type UseApiConfig, type UseApiQuery, type UseApiReturn, type UseApiState, type ValidationError, buildPaginateQuery, cacheManager, createApiActions, createApiClient, createApiServices, processResponse, useApi };
603
+ export { type ActionConfig, type ActionOptions, type ActionState, type ApiClientConfig, type ApiError, type ApiModuleConfig, type ApiResourceStatus, type ApiResponse, type ExecutableAction, type LogLevel, type Logger, 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 UseApiResourceActions, type UseApiResourceConfig, type UseApiResourceReturn, type UseApiResourceState, type UseApiReturn, type UseApiState, type ValidationError, buildPaginateQuery, cacheManager, createApiActions, createApiClient, createApiServices, processResponse, useApi, useApiModule };