@arex95/vue-core 1.1.43 → 3.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.
- package/README.md +90 -57
- package/dist/composables/auth/useAuth.d.ts +20 -6
- package/dist/composables/axios/axiosFetch.d.ts +7 -5
- package/dist/composables/axios/index.d.ts +0 -1
- package/dist/composables/axios/useFetch.d.ts +14 -5
- package/dist/composables/breakpoints/useBreakpoint.d.ts +11 -2
- package/dist/composables/filters/useFilter.d.ts +13 -8
- package/dist/composables/monitoring/useApiActivity.d.ts +17 -6
- package/dist/composables/monitoring/useUserActivity.d.ts +20 -5
- package/dist/composables/paginators/usePaginator.d.ts +13 -5
- package/dist/composables/sorters/useSorter.d.ts +13 -7
- package/dist/config/auth/authFetcher.d.ts +30 -0
- package/dist/config/auth/index.d.ts +1 -0
- package/dist/config/axios/axiosConfig.d.ts +30 -0
- package/dist/config/axios/axiosInstance.d.ts +14 -0
- package/dist/config/global/endpointsConfig.d.ts +9 -13
- package/dist/config/global/keyConfig.d.ts +7 -10
- package/dist/config/global/sessionConfig.d.ts +15 -17
- package/dist/config/global/tokenPathsConfig.d.ts +17 -18
- package/dist/config/global/tokensConfig.d.ts +9 -9
- package/dist/config/index.d.ts +1 -0
- package/dist/enums/breakpointsEnums.d.ts +7 -4
- package/dist/enums/errorsEnums.d.ts +26 -19
- package/dist/enums/fileTypesEnums.d.ts +33 -1
- package/dist/enums/httpExceptionsEnums.d.ts +3 -1
- package/dist/enums/keyCodesEnums.d.ts +2 -4
- package/dist/enums/storageEnums.d.ts +4 -4
- package/dist/errors/AuthError.d.ts +10 -0
- package/dist/errors/BaseError.d.ts +16 -0
- package/dist/errors/NetworkError.d.ts +9 -0
- package/dist/errors/ServerError.d.ts +10 -0
- package/dist/errors/ValidationError.d.ts +14 -0
- package/dist/errors/index.d.ts +5 -0
- package/dist/fetchers/axios.d.ts +22 -0
- package/dist/fetchers/index.d.ts +2 -0
- package/dist/fetchers/ofetch.d.ts +33 -0
- package/dist/index.d.ts +8 -6
- package/dist/index.mjs +1633 -875
- package/dist/rest/RestStd.d.ts +146 -102
- package/dist/services/credentials.d.ts +24 -29
- package/dist/services/extractTokens.d.ts +7 -6
- package/dist/services/refreshTokens.d.ts +11 -12
- package/dist/services/storeTokens.d.ts +8 -6
- package/dist/types/AppKeyConfig.d.ts +7 -0
- package/dist/types/ArexVueCoreOptions.d.ts +20 -0
- package/dist/types/Auth.d.ts +15 -0
- package/dist/types/AxiosOptionsParameter.d.ts +14 -7
- package/dist/types/AxiosServiceOptions.d.ts +9 -0
- package/dist/types/DecodedJwtPayload.d.ts +12 -0
- package/dist/types/EndpointsConfig.d.ts +7 -0
- package/dist/types/ErrorType.d.ts +4 -2
- package/dist/types/ExtendedQueryOptions.d.ts +10 -0
- package/dist/types/Fetcher.d.ts +24 -0
- package/dist/types/RestStdOptions.d.ts +62 -0
- package/dist/types/SessionConfig.d.ts +25 -1
- package/dist/types/TokenConfig.d.ts +7 -0
- package/dist/types/TokenValidationResult.d.ts +7 -0
- package/dist/types/index.d.ts +2 -0
- package/dist/utils/browser.d.ts +20 -14
- package/dist/utils/dates.d.ts +47 -34
- package/dist/utils/debounces.d.ts +54 -32
- package/dist/utils/encryption.d.ts +28 -24
- package/dist/utils/errors.d.ts +27 -8
- package/dist/utils/exports.d.ts +24 -19
- package/dist/utils/files.d.ts +33 -25
- package/dist/utils/index.d.ts +3 -0
- package/dist/utils/io.d.ts +70 -54
- package/dist/utils/objects.d.ts +78 -60
- package/dist/utils/retry.d.ts +8 -0
- package/dist/utils/ssr.d.ts +27 -0
- package/dist/utils/storage.d.ts +20 -14
- package/dist/utils/strings.d.ts +42 -31
- package/dist/utils/validations.d.ts +76 -57
- package/package.json +7 -16
package/README.md
CHANGED
|
@@ -1,64 +1,97 @@
|
|
|
1
1
|
# @arex95/vue-core
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
A comprehensive Vue.js core library designed to streamline the development of Vue applications. It provides a set of composables, utilities, and services for handling common tasks such as API communication, authentication, and data management.
|
|
4
4
|
|
|
5
|
-
##
|
|
5
|
+
## Features
|
|
6
6
|
|
|
7
|
-
|
|
7
|
+
- **RESTful Standard**: A standardized RESTful class (`RestStd`) that you can extend directly from your models for clean, semantic API calls (e.g., `User.getOne()`).
|
|
8
|
+
- **Fetching Agnostic**: Works with any fetching system (Axios, ofetch, fetch API, or custom fetchers).
|
|
9
|
+
- **Flexible Authentication**: JWT-based authentication system that works with any fetcher (not tied to Axios).
|
|
10
|
+
- **Enhanced Error Handling**: Custom error classes (`NetworkError`, `AuthError`, `ValidationError`, etc.) with structured error information.
|
|
11
|
+
- **Retry Logic**: Built-in retry mechanism with exponential backoff for failed requests.
|
|
12
|
+
- **Secure Storage**: Support for localStorage, sessionStorage, and cookies with encryption and security options (Secure, SameSite).
|
|
13
|
+
- **SSR/SSG Support**: Full support for server-side rendering with automatic cookie fallback.
|
|
14
|
+
- **Type Safety**: Improved generic types for better TypeScript inference and autocompletion.
|
|
15
|
+
- **Utility Functions**: A rich collection of utilities for dates, strings, validations, encryption, and more.
|
|
8
16
|
|
|
9
|
-
##
|
|
10
|
-
|
|
11
|
-
Esta arquitectura está diseñada para seguir principios sólidos de `separación de responsabilidades` y `modularidad`, implementando una estructura en la que `los servicios gestionan la lógica de negocio` relacionada con la interacción con APIs, mientras que `las vistas se encargan exclusivamente de la presentación`.
|
|
12
|
-
|
|
13
|
-
## Concepto General de la Arquitectura
|
|
14
|
-
|
|
15
|
-
1. **Separación de Responsabilidades**:
|
|
16
|
-
En este diseño, las vistas no tienen que ocuparse de la lógica de obtención o mutación de datos. Esta responsabilidad está delegada a los **servicios**, que gestionan todo el proceso de interactuar con las APIs, realizar solicitudes HTTP y manipular los modelos. Las vistas simplemente se encargan de la **presentación de los datos** y de gestionar las interacciones del usuario, como capturar eventos o mostrar resultados.
|
|
17
|
-
|
|
18
|
-
- `Vistas`: Su tarea principal es mostrar los datos que obtienen de los servicios. Se centran en la parte visual y en las interacciones de usuario.
|
|
19
|
-
- `Servicios`: Son responsables de gestionar cómo y desde dónde se obtienen los datos. Aquí es donde se realiza toda la lógica de acceso a las APIs, manejo de respuestas y errores, y mutación de modelos.
|
|
20
|
-
|
|
21
|
-
Este enfoque reduce la complejidad de las vistas, las cuales permanecen limpias y fáciles de entender. Cualquier cambio en la forma de hacer las solicitudes (como cambiar la estructura de la API o el cliente HTTP) no requiere modificaciones en las vistas, lo que mejora la mantenibilidad.
|
|
22
|
-
|
|
23
|
-
2. **Desacoplamiento de la Lógica de la API**:
|
|
24
|
-
|
|
25
|
-
Los servicios encapsulan completamente la lógica de interacción con las APIs. Las vistas no necesitan saber nada sobre cómo se hace la solicitud a la API o cómo se gestionan las respuestas. Este desacoplamiento permite que las vistas sean **más limpias** y **menos propensas a errores**, ya que no necesitan manejar la lógica de negocio ni los detalles de las peticiones HTTP. Si en el futuro la forma de interactuar con la API cambia (por ejemplo, si se cambia el cliente HTTP o se agrega un middleware), solo será necesario modificar los servicios, no las vistas.
|
|
26
|
-
|
|
27
|
-
Este enfoque también permite que los servicios sean **reutilizables** en diferentes partes de la aplicación. Por ejemplo, si varias vistas necesitan autenticar al usuario, todas pueden utilizar el servicio `AuthService`, sin necesidad de duplicar la lógica de autenticación.
|
|
28
|
-
|
|
29
|
-
3. **Reusabilidad y Modularidad**:
|
|
30
|
-
|
|
31
|
-
Al centralizar la lógica de negocio en servicios, estos pueden ser fácilmente **reutilizados** en diferentes vistas y componentes de la aplicación. Cada servicio está diseñado para encargarse de una única funcionalidad o módulo del sistema, como la autenticación, gestión de productos, gestión de categorías, etc. Este enfoque modular hace que la aplicación sea **más fácil de escalar**.
|
|
32
|
-
|
|
33
|
-
Además, la modularidad permite que cada servicio evolucione y cambie de forma independiente sin afectar a otros módulos o partes de la aplicación. Si un nuevo servicio debe ser agregado, como uno para manejar un módulo adicional (por ejemplo, pagos o notificaciones), se puede hacer sin interrumpir el flujo de trabajo de los demás servicios.
|
|
34
|
-
|
|
35
|
-
4. **Mejora en la Escalabilidad**:
|
|
36
|
-
|
|
37
|
-
Esta arquitectura facilita la escalabilidad, ya que cualquier servicio puede ser **ampliado o modificado de forma independiente** sin necesidad de reestructurar la aplicación completa. Por ejemplo, si el servicio de productos necesita cambios en la lógica de consulta, esto no afectará al servicio de autenticación o a las vistas que consumen esos servicios. Esta flexibilidad es crucial cuando el sistema crece y se añaden nuevas funcionalidades.
|
|
38
|
-
|
|
39
|
-
5. **Facilidad de Pruebas Unitarias**:
|
|
40
|
-
|
|
41
|
-
Al estar los servicios desacoplados de las vistas, es mucho más fácil realizar **pruebas unitarias** de cada servicio de manera aislada. Las vistas no necesitan ser simuladas ni involucradas en las pruebas de negocio, lo que facilita la escritura de pruebas unitarias puras para la lógica de las APIs y el manejo de los datos.
|
|
42
|
-
|
|
43
|
-
Por ejemplo, el servicio `AuthService` puede probarse por separado para verificar si maneja correctamente el proceso de inicio de sesión o si responde correctamente a los errores de autenticación, sin necesidad de preocuparse por el diseño de las vistas o la interacción con el usuario.
|
|
44
|
-
|
|
45
|
-
6. **Mantenimiento Sostenible**:
|
|
46
|
-
|
|
47
|
-
En un proyecto grande o en evolución, esta arquitectura facilita el mantenimiento del código. Si hay un error relacionado con la autenticación, se puede solucionar directamente en el servicio `AuthService`, sin tener que revisar todas las vistas que consumen este servicio. Esto hace que el código sea más fácil de entender y más fácil de depurar.
|
|
48
|
-
|
|
49
|
-
Además, si es necesario cambiar la lógica de la API (como cambiar el formato de las respuestas), solo es necesario modificar los servicios afectados. Las vistas seguirán funcionando de la misma manera, ya que están desacopladas de esta lógica.
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
## Estructura del Proyecto
|
|
53
|
-
|
|
54
|
-
- **src/composables**: Contiene composables reutilizables para Axios, filtros, paginadores y ordenadores.
|
|
55
|
-
- **src/config**: Configuraciones para Axios.
|
|
56
|
-
- **src/constants**: Constantes utilizadas en el proyecto, como enumeraciones de breakpoints, excepciones, tipos de archivos, etc.
|
|
57
|
-
- **src/rest**: Implementación estándar de una interfaz REST para operaciones CRUD. Proporciona una forma sencilla y estandarizada de interactuar con APIs RESTful, facilitando la creación de servicios que pueden realizar operaciones como crear, leer, actualizar y eliminar recursos.
|
|
58
|
-
- **src/types**: Tipos TypeScript utilizados en el proyecto.
|
|
59
|
-
- **src/utils**: Utilidades varias, como funciones para manejar fechas, validaciones, manipulación de strings, etc.
|
|
60
|
-
|
|
61
|
-
## Instalación
|
|
17
|
+
## Installation
|
|
62
18
|
|
|
63
19
|
```sh
|
|
64
|
-
npm install @arex95/vue-core
|
|
20
|
+
npm install @arex95/vue-core
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
## Quick Start
|
|
24
|
+
|
|
25
|
+
To get started, you need to configure the library in your main `main.ts` file.
|
|
26
|
+
|
|
27
|
+
```typescript
|
|
28
|
+
import { createApp } from 'vue';
|
|
29
|
+
import App from './App.vue';
|
|
30
|
+
import { ArexVueCore } from '@arex95/vue-core';
|
|
31
|
+
|
|
32
|
+
const app = createApp(App);
|
|
33
|
+
|
|
34
|
+
app.use(ArexVueCore, {
|
|
35
|
+
appKey: 'your-secret-key',
|
|
36
|
+
endpoints: {
|
|
37
|
+
login: '/api/login',
|
|
38
|
+
refresh: '/api/refresh',
|
|
39
|
+
logout: '/api/logout',
|
|
40
|
+
},
|
|
41
|
+
tokenKeys: {
|
|
42
|
+
accessToken: 'ACCESS_TOKEN',
|
|
43
|
+
refreshToken: 'REFRESH_TOKEN',
|
|
44
|
+
},
|
|
45
|
+
tokenPaths: {
|
|
46
|
+
accessToken: 'data.access_token',
|
|
47
|
+
refreshToken: 'data.refresh_token',
|
|
48
|
+
},
|
|
49
|
+
refreshTokenPaths: {
|
|
50
|
+
accessToken: 'data.access_token',
|
|
51
|
+
refreshToken: 'data.refresh_token',
|
|
52
|
+
},
|
|
53
|
+
axios: {
|
|
54
|
+
baseURL: 'https://api.example.com',
|
|
55
|
+
},
|
|
56
|
+
});
|
|
57
|
+
|
|
58
|
+
app.mount('#app');
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
**Create a model:**
|
|
62
|
+
|
|
63
|
+
```typescript
|
|
64
|
+
import { RestStd } from '@arex95/vue-core';
|
|
65
|
+
|
|
66
|
+
export interface UserData {
|
|
67
|
+
id: number;
|
|
68
|
+
name: string;
|
|
69
|
+
email: string;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export class User extends RestStd {
|
|
73
|
+
static override resource = 'users';
|
|
74
|
+
// fetchFn is optional if you configured Axios with configAxios()
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
// Use directly in components
|
|
78
|
+
const { data: users } = useQuery({
|
|
79
|
+
queryKey: ['users'],
|
|
80
|
+
queryFn: () => User.getAll<UserData[]>(),
|
|
81
|
+
});
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
For more detailed usage examples, please refer to the [documentation](./docs/getting-started.md) and [EXAMPLES.md](./EXAMPLES.md) file.
|
|
85
|
+
|
|
86
|
+
## Project Structure
|
|
87
|
+
|
|
88
|
+
- **`src/composables`**: Reusable Vue composables for various functionalities.
|
|
89
|
+
- **`src/config`**: Global configuration for Axios, API endpoints, and tokens.
|
|
90
|
+
- **`src/enums`**: Enums for constants used throughout the library.
|
|
91
|
+
- **`src/fetchers`**: Optional helpers for creating fetchers (Axios, ofetch).
|
|
92
|
+
- **`src/rest`**: A standardized RESTful class (`RestStd`) for CRUD operations.
|
|
93
|
+
- **`src/services`**: Services for authentication and token management.
|
|
94
|
+
- **`src/types`**: TypeScript type definitions.
|
|
95
|
+
- **`src/utils`**: A collection of utility functions.
|
|
96
|
+
|
|
97
|
+
For a more in-depth explanation of the project's architecture, please see the [ARCHITECTURE.md](./ARCHITECTURE.md) file.
|
|
@@ -1,11 +1,25 @@
|
|
|
1
|
-
import { AuthResponse, AuthTokenPaths, LocationPreference } from "@/types";
|
|
1
|
+
import { AuthResponse, AuthTokenPaths, LocationPreference, Fetcher } from "@/types";
|
|
2
2
|
/**
|
|
3
3
|
* Custom hook for authentication logic, including login, logout, token management, and session preference.
|
|
4
|
+
* Accepts an optional fetcher function. If not provided, uses the default configured fetcher or falls back to Axios.
|
|
4
5
|
*
|
|
5
|
-
* @param {
|
|
6
|
-
* @returns {
|
|
6
|
+
* @param {Fetcher} [fetcher] - Optional fetcher function to use for auth requests. If not provided, uses the default configured fetcher.
|
|
7
|
+
* @returns {{
|
|
8
|
+
* logout: (params?: Record<string, unknown>) => Promise<void>,
|
|
9
|
+
* login: (params: Record<string, unknown>, persistence: LocationPreference, tokenPaths?: AuthTokenPaths) => Promise<AuthResponse>
|
|
10
|
+
* }} An object containing authentication functions.
|
|
11
|
+
*
|
|
12
|
+
* @example
|
|
13
|
+
* ```typescript
|
|
14
|
+
* // Using default fetcher (Axios)
|
|
15
|
+
* const auth = useAuth();
|
|
16
|
+
*
|
|
17
|
+
* // Using custom fetcher
|
|
18
|
+
* const customFetcher = createOfetchFetcher();
|
|
19
|
+
* const auth = useAuth(customFetcher);
|
|
20
|
+
* ```
|
|
7
21
|
*/
|
|
8
|
-
export declare function useAuth(): {
|
|
9
|
-
logout: (params?:
|
|
10
|
-
login: (params:
|
|
22
|
+
export declare function useAuth(fetcher?: Fetcher): {
|
|
23
|
+
logout: (params?: Record<string, unknown>) => Promise<void>;
|
|
24
|
+
login: (params: Record<string, unknown> | undefined, persistence: LocationPreference, tokenPaths?: AuthTokenPaths) => Promise<AuthResponse>;
|
|
11
25
|
};
|
|
@@ -1,10 +1,12 @@
|
|
|
1
1
|
import { AxiosInstance, AxiosRequestConfig } from 'axios';
|
|
2
2
|
/**
|
|
3
|
-
*
|
|
3
|
+
* A composable function that executes an Axios request and returns the response data.
|
|
4
|
+
* It simplifies making API calls by wrapping the Axios request in a reusable function.
|
|
4
5
|
*
|
|
5
|
-
* @template T The expected
|
|
6
|
-
* @param {AxiosInstance} axios - The Axios instance for making
|
|
7
|
-
* @param {AxiosRequestConfig} axiosRequest -
|
|
8
|
-
* @returns {Promise<T>} A promise with the
|
|
6
|
+
* @template T The expected type of the response data.
|
|
7
|
+
* @param {AxiosInstance} axios - The Axios instance to use for making the request.
|
|
8
|
+
* @param {AxiosRequestConfig} axiosRequest - The configuration for the Axios request (e.g., URL, method, headers).
|
|
9
|
+
* @returns {Promise<T>} A promise that resolves with the data from the Axios response.
|
|
10
|
+
* @throws {Error} Throws an error if the Axios request fails.
|
|
9
11
|
*/
|
|
10
12
|
export declare function axiosFetch<T>(axios: AxiosInstance, axiosRequest: AxiosRequestConfig): Promise<T>;
|
|
@@ -1,9 +1,18 @@
|
|
|
1
1
|
import { AxiosInstance, AxiosRequestConfig } from 'axios';
|
|
2
2
|
import { UseQueryOptions } from '@tanstack/vue-query';
|
|
3
3
|
/**
|
|
4
|
-
*
|
|
5
|
-
*
|
|
6
|
-
*
|
|
7
|
-
*
|
|
4
|
+
* A factory function that creates a reusable query function for making API requests.
|
|
5
|
+
* It abstracts the Axios instance creation and allows for a custom instance to be provided.
|
|
6
|
+
* This is particularly useful for creating typed query functions for use with libraries like Vue Query.
|
|
7
|
+
*
|
|
8
|
+
* @template TQueryFnData The expected data type of the query function's response.
|
|
9
|
+
* @template TData The expected data type of the transformed data.
|
|
10
|
+
* @param {Function} fetchFn - The underlying function that will be called to perform the fetch operation.
|
|
11
|
+
* This function should accept an Axios instance, Axios request configuration, and optional query options.
|
|
12
|
+
* @param {AxiosInstance} [axiosCustomInstance] - An optional custom Axios instance to use for the request.
|
|
13
|
+
* If not provided, a default configured instance will be used.
|
|
14
|
+
* @returns {(axiosRequestConfig: AxiosRequestConfig, options?: UseQueryOptions<TQueryFnData, Error, TData>) => any}
|
|
15
|
+
* A new function that takes Axios request configuration and optional query options, and when executed,
|
|
16
|
+
* performs the API request using the configured `fetchFn`.
|
|
8
17
|
*/
|
|
9
|
-
export declare function useFetch(fetchFn: Function, axiosCustomInstance?: AxiosInstance): (axiosRequestConfig: AxiosRequestConfig, options?: UseQueryOptions) => any;
|
|
18
|
+
export declare function useFetch<TQueryFnData = unknown, TData = TQueryFnData>(fetchFn: Function, axiosCustomInstance?: AxiosInstance): (axiosRequestConfig: AxiosRequestConfig, options?: UseQueryOptions) => any;
|
|
@@ -1,7 +1,16 @@
|
|
|
1
1
|
/**
|
|
2
|
-
*
|
|
2
|
+
* A composable that provides a reactive interface to Tailwind CSS breakpoints using `@vueuse/core`.
|
|
3
|
+
* It simplifies working with responsive layouts by offering a set of reactive booleans for different
|
|
4
|
+
* screen sizes and combinations. On its first invocation, it also logs the current device type (Mobile,
|
|
5
|
+
* Tablet, Laptop, or Desktop) to the console for easier debugging during development.
|
|
3
6
|
*
|
|
4
|
-
* @returns {
|
|
7
|
+
* @returns {object} An object containing various reactive properties for screen sizes, window dimensions, and breakpoint utilities, including:
|
|
8
|
+
* - `current`: A ref to the current breakpoint name.
|
|
9
|
+
* - `active`: A ref to the currently active breakpoint name.
|
|
10
|
+
* - `sm_S`, `md_GE`, etc.: A series of refs indicating if the screen is smaller than, greater than or equal to, or between specific breakpoints.
|
|
11
|
+
* - `mobile`, `tablet`, `laptop`, `desktop`: Refs that are true for common device width ranges.
|
|
12
|
+
* - `windowWidth`, `windowHeight`: Reactive refs for the window's width and height.
|
|
13
|
+
* - `breakpoints`: The original `useBreakpoints` return object from `@vueuse/core`.
|
|
5
14
|
*/
|
|
6
15
|
export declare function useBreakpoint(): {
|
|
7
16
|
current: import("vue").ComputedRef<("sm" | "md" | "lg" | "xl" | "2xl")[]>;
|
|
@@ -1,13 +1,18 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* A composable function that filters objects based on a
|
|
2
|
+
* A composable function that filters an array of objects based on a specified field, data type, and criteria.
|
|
3
|
+
* It supports filtering by date range, string matching (case-insensitive and diacritic-insensitive), number range, and boolean values.
|
|
3
4
|
*
|
|
4
|
-
* @
|
|
5
|
-
* @param {
|
|
6
|
-
* @param {
|
|
7
|
-
* @param {string} filterConfig.
|
|
8
|
-
* @param {
|
|
9
|
-
*
|
|
10
|
-
*
|
|
5
|
+
* @template T A generic type that extends a record of string keys to any value, representing the objects in the array.
|
|
6
|
+
* @param {T[]} items - The array of objects to be filtered.
|
|
7
|
+
* @param {object} filterConfig - The configuration object for filtering.
|
|
8
|
+
* @param {string} filterConfig.field - The name of the field in the objects to filter by.
|
|
9
|
+
* @param {'date' | 'string' | 'number' | 'boolean'} filterConfig.type - The data type of the field to be filtered.
|
|
10
|
+
* @param {any} filterConfig.criteria - The criteria for filtering, which varies based on the `type`:
|
|
11
|
+
* - For 'date': An object `{ startDate: string, endDate: string }`.
|
|
12
|
+
* - For 'string': A string to search for.
|
|
13
|
+
* - For 'number': An object `{ min: number, max: number }`.
|
|
14
|
+
* - For 'boolean': A boolean value.
|
|
15
|
+
* @returns {T[]} The filtered array of objects. If the criteria are invalid or not provided, the original array is returned.
|
|
11
16
|
*/
|
|
12
17
|
export declare function useFilter<T extends Record<string, any>>(items: T[], filterConfig: {
|
|
13
18
|
field: string;
|
|
@@ -1,10 +1,21 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* A
|
|
3
|
-
*
|
|
4
|
-
* if
|
|
5
|
-
*
|
|
6
|
-
*
|
|
7
|
-
* @
|
|
2
|
+
* A composable that monitors API activity to manage session timeouts. It automatically
|
|
3
|
+
* updates an activity timestamp on each outgoing API request and checks periodically
|
|
4
|
+
* if the session has expired due to inactivity. If the session times out, it will
|
|
5
|
+
* automatically log the user out.
|
|
6
|
+
*
|
|
7
|
+
* @param {number} [sessionTimeoutMin=SESSION_TIMEOUT_MINUTES] - The session timeout period in minutes.
|
|
8
|
+
* Defaults to 30 minutes.
|
|
9
|
+
* @param {number} [checkIntervalSec=CHECK_INTERVAL_SECONDS] - The interval in seconds at which to check for
|
|
10
|
+
* session expiry. Defaults to 60 seconds.
|
|
11
|
+
* @returns {{
|
|
12
|
+
* pause: () => void,
|
|
13
|
+
* resume: () => void,
|
|
14
|
+
* updateTimestamp: () => void
|
|
15
|
+
* }} An object with functions to control the activity monitoring:
|
|
16
|
+
* - `pause`: Pauses the periodic session check.
|
|
17
|
+
* - `resume`: Resumes the periodic session check.
|
|
18
|
+
* - `updateTimestamp`: Manually updates the last activity timestamp.
|
|
8
19
|
*/
|
|
9
20
|
export declare function useApiActivity(sessionTimeoutMin?: number, checkIntervalSec?: number): {
|
|
10
21
|
pause: import("@vueuse/core").Fn;
|
|
@@ -1,9 +1,24 @@
|
|
|
1
1
|
/**
|
|
2
|
-
*
|
|
3
|
-
*
|
|
4
|
-
*
|
|
5
|
-
* @param
|
|
6
|
-
* @
|
|
2
|
+
* A composable to detect user inactivity. It tracks user interactions and triggers a timeout
|
|
3
|
+
* if no activity is detected for a specified duration.
|
|
4
|
+
*
|
|
5
|
+
* @param {number} [timeout=300000] - The time in milliseconds before the user is considered inactive. Defaults to 5 minutes.
|
|
6
|
+
* @param {boolean} [useDefaultEvents=true] - Whether to use the default events (mousemove, keydown, scroll, touchstart) to detect activity.
|
|
7
|
+
* @param {Array<keyof WindowEventMap>} [customEvents=[]] - A list of custom events to detect activity, in addition to the default ones if `useDefaultEvents` is true.
|
|
8
|
+
* @returns {{
|
|
9
|
+
* isInactive: import('vue').Ref<boolean>,
|
|
10
|
+
* startInactivityTimer: () => void,
|
|
11
|
+
* stopInactivityTimer: () => void,
|
|
12
|
+
* resetInactivityTimer: () => void,
|
|
13
|
+
* onTimeout: (callback: () => void) => void,
|
|
14
|
+
* removeTimeoutCallback: (callback: () => void) => void
|
|
15
|
+
* }} An object containing:
|
|
16
|
+
* - `isInactive`: A ref that becomes `true` when the user is inactive.
|
|
17
|
+
* - `startInactivityTimer`: A function to start the inactivity timer.
|
|
18
|
+
* - `stopInactivityTimer`: A function to stop the inactivity timer.
|
|
19
|
+
* - `resetInactivityTimer`: A function to reset the inactivity timer.
|
|
20
|
+
* - `onTimeout`: A function to register a callback that will be executed on timeout.
|
|
21
|
+
* - `removeTimeoutCallback`: A function to remove a previously registered callback.
|
|
7
22
|
*/
|
|
8
23
|
export declare function useUserInactivity(timeout?: number, useDefaultEvents?: boolean, customEvents?: Array<keyof WindowEventMap>): {
|
|
9
24
|
isInactive: import("vue").Ref<boolean, boolean>;
|
|
@@ -1,11 +1,19 @@
|
|
|
1
1
|
import { Ref } from "vue";
|
|
2
2
|
/**
|
|
3
|
-
*
|
|
3
|
+
* A composable that provides pagination logic based on reactive refs for the current page,
|
|
4
|
+
* total number of items, and items per page.
|
|
4
5
|
*
|
|
5
|
-
* @param page -
|
|
6
|
-
* @param total -
|
|
7
|
-
* @param pageSize -
|
|
8
|
-
* @returns
|
|
6
|
+
* @param {Ref<number>} page - A reactive ref representing the current page number.
|
|
7
|
+
* @param {Ref<number>} total - A reactive ref representing the total number of items to be paginated.
|
|
8
|
+
* @param {Ref<number>} pageSize - A reactive ref representing the number of items per page.
|
|
9
|
+
* @returns {{
|
|
10
|
+
* totalPages: import('vue').ComputedRef<number>,
|
|
11
|
+
* canFetchNextPage: () => boolean,
|
|
12
|
+
* canFetchPreviousPage: () => boolean
|
|
13
|
+
* }} An object containing:
|
|
14
|
+
* - `totalPages`: A computed property that calculates the total number of pages.
|
|
15
|
+
* - `canFetchNextPage`: A function that returns `true` if there is a next page.
|
|
16
|
+
* - `canFetchPreviousPage`: A function that returns `true` if there is a previous page.
|
|
9
17
|
*/
|
|
10
18
|
export declare function usePagination(page: Ref<number>, total: Ref<number>, pageSize: Ref<number>): {
|
|
11
19
|
totalPages: import("vue").ComputedRef<number>;
|
|
@@ -1,14 +1,20 @@
|
|
|
1
|
+
import { ComputedRef } from "vue";
|
|
1
2
|
/**
|
|
2
|
-
*
|
|
3
|
-
*
|
|
4
|
-
*
|
|
5
|
-
* @
|
|
6
|
-
* @
|
|
3
|
+
* A composable that sorts an array of objects based on a selected criterion from a list of predefined sorting options.
|
|
4
|
+
* It supports sorting by number, date, boolean, and string fields, in both ascending and descending order.
|
|
5
|
+
*
|
|
6
|
+
* @template T The type of items in the array.
|
|
7
|
+
* @param {T[]} items - The array of objects to sort.
|
|
8
|
+
* @param {Array<{value: number, label: string, field: string, order: string, type: string}>} criteriaList - A list of
|
|
9
|
+
* sorting criteria objects. Each object defines a sorting option with a unique `value`, a `label` for display, the `field`
|
|
10
|
+
* to sort by, the `order` ('asc' or 'desc'), and the data `type` ('number', 'date', 'boolean', 'string').
|
|
11
|
+
* @param {number} selectedCriteria - The `value` of the currently selected sorting criterion from the `criteriaList`.
|
|
12
|
+
* @returns {ComputedRef<T[]>} A computed ref containing the sorted items. If the selected criterion is not found, the original array is returned.
|
|
7
13
|
*/
|
|
8
|
-
export declare function useSorter(items:
|
|
14
|
+
export declare function useSorter<T extends Record<string, any>>(items: T[], criteriaList: {
|
|
9
15
|
value: number;
|
|
10
16
|
label: string;
|
|
11
17
|
field: string;
|
|
12
18
|
order: string;
|
|
13
19
|
type: string;
|
|
14
|
-
}[], selectedCriteria: number):
|
|
20
|
+
}[], selectedCriteria: number): ComputedRef<T[]>;
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { Fetcher } from '@/types/Fetcher';
|
|
2
|
+
/**
|
|
3
|
+
* Configures a default fetcher for authentication operations.
|
|
4
|
+
* If not configured, useAuth will use the default Axios fetcher.
|
|
5
|
+
*
|
|
6
|
+
* @param fetcher - The fetcher function to use for auth operations
|
|
7
|
+
*
|
|
8
|
+
* @example
|
|
9
|
+
* ```typescript
|
|
10
|
+
* import { configAuthFetcher, createOfetchFetcher } from '@arex95/vue-core';
|
|
11
|
+
*
|
|
12
|
+
* const ofetchFetcher = createOfetchFetcher();
|
|
13
|
+
* configAuthFetcher(ofetchFetcher);
|
|
14
|
+
* ```
|
|
15
|
+
*/
|
|
16
|
+
export declare function configAuthFetcher(fetcher: Fetcher): void;
|
|
17
|
+
/**
|
|
18
|
+
* Configures a factory function to create the default fetcher lazily.
|
|
19
|
+
* This is used internally to avoid circular dependencies.
|
|
20
|
+
*
|
|
21
|
+
* @param factory - Factory function that creates a fetcher
|
|
22
|
+
*/
|
|
23
|
+
export declare function setDefaultAuthFetcherFactory(factory: () => Fetcher): void;
|
|
24
|
+
/**
|
|
25
|
+
* Gets the default auth fetcher, creating one from Axios if not configured.
|
|
26
|
+
* This allows lazy initialization to avoid circular dependencies.
|
|
27
|
+
*
|
|
28
|
+
* @returns The fetcher function to use
|
|
29
|
+
*/
|
|
30
|
+
export declare function getDefaultAuthFetcher(): Fetcher;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export * from './authFetcher';
|
|
@@ -5,6 +5,12 @@ declare module "axios" {
|
|
|
5
5
|
_retry?: boolean;
|
|
6
6
|
}
|
|
7
7
|
}
|
|
8
|
+
/**
|
|
9
|
+
* A service class that encapsulates a customizable Axios instance with built-in interceptors
|
|
10
|
+
* for handling authentication, token refreshing, and request cancellation. It is designed to
|
|
11
|
+
* streamline API communication by automatically attaching authorization headers and managing
|
|
12
|
+
* token refresh logic for 401 Unauthorized responses.
|
|
13
|
+
*/
|
|
8
14
|
export declare class AxiosService {
|
|
9
15
|
private readonly instance;
|
|
10
16
|
private cancelTokenSource;
|
|
@@ -12,13 +18,37 @@ export declare class AxiosService {
|
|
|
12
18
|
private readonly refreshTokenUrl;
|
|
13
19
|
private isRefreshing;
|
|
14
20
|
private failedQueue;
|
|
21
|
+
/**
|
|
22
|
+
* Creates an instance of AxiosService.
|
|
23
|
+
* @param {AxiosServiceOptions} options - Configuration options for the Axios instance, such as `baseURL`, `timeout`, and custom `headers`.
|
|
24
|
+
*/
|
|
15
25
|
constructor(options: AxiosServiceOptions);
|
|
16
26
|
private processQueue;
|
|
17
27
|
private setAuthHeader;
|
|
18
28
|
private initializeInterceptors;
|
|
29
|
+
/**
|
|
30
|
+
* Returns the number of active (in-flight) requests.
|
|
31
|
+
* @returns {number} The number of active requests.
|
|
32
|
+
*/
|
|
19
33
|
getActiveRequests(): number;
|
|
34
|
+
/**
|
|
35
|
+
* Returns the underlying Axios instance.
|
|
36
|
+
* @returns {AxiosInstance} The Axios instance.
|
|
37
|
+
*/
|
|
20
38
|
getAxiosInstance(): AxiosInstance;
|
|
39
|
+
/**
|
|
40
|
+
* Cancels all ongoing requests made by this Axios instance.
|
|
41
|
+
*/
|
|
21
42
|
cancelAllRequests(): void;
|
|
43
|
+
/**
|
|
44
|
+
* Sets a default header for all subsequent requests.
|
|
45
|
+
* @param {string} key - The header key.
|
|
46
|
+
* @param {string} value - The header value.
|
|
47
|
+
*/
|
|
22
48
|
setHeader(key: string, value: string): void;
|
|
49
|
+
/**
|
|
50
|
+
* Removes a default header.
|
|
51
|
+
* @param {string} key - The header key to remove.
|
|
52
|
+
*/
|
|
23
53
|
removeHeader(key: string): void;
|
|
24
54
|
}
|
|
@@ -1,4 +1,18 @@
|
|
|
1
1
|
import { AxiosServiceOptions } from "@/types/AxiosServiceOptions";
|
|
2
2
|
import { AxiosInstance } from "axios";
|
|
3
|
+
/**
|
|
4
|
+
* Configures the singleton Axios service instance for the application.
|
|
5
|
+
* This function should be called once at the application's entry point to set up
|
|
6
|
+
* the base URL, headers, and other default configurations for all API requests.
|
|
7
|
+
*
|
|
8
|
+
* @param {AxiosServiceOptions} config - The configuration options for the Axios service.
|
|
9
|
+
*/
|
|
3
10
|
export declare const configAxios: (config: AxiosServiceOptions) => void;
|
|
11
|
+
/**
|
|
12
|
+
* Retrieves the configured singleton Axios instance.
|
|
13
|
+
* If not configured yet, creates a default instance with minimal configuration.
|
|
14
|
+
* This allows lazy initialization to avoid dependency circular issues in Nuxt and other frameworks.
|
|
15
|
+
*
|
|
16
|
+
* @returns {AxiosInstance} The configured Axios instance.
|
|
17
|
+
*/
|
|
4
18
|
export declare const getConfiguredAxiosInstance: () => AxiosInstance;
|
|
@@ -8,24 +8,20 @@ interface EndpointConfig {
|
|
|
8
8
|
logoutEndpoint: string;
|
|
9
9
|
}
|
|
10
10
|
/**
|
|
11
|
-
* Configures authentication endpoint URLs
|
|
12
|
-
* This function
|
|
11
|
+
* Configures the global authentication endpoint URLs for the application.
|
|
12
|
+
* This function should be called once at startup to define the API endpoints for login,
|
|
13
|
+
* token refresh, and logout. The configuration is then frozen to prevent changes.
|
|
13
14
|
*
|
|
14
|
-
* @param {EndpointConfig} config - An object containing the authentication
|
|
15
|
-
* @param {string} config.loginEndpoint - URL
|
|
16
|
-
* @param {string} config.refreshEndpoint - URL
|
|
17
|
-
* @param {string} config.logoutEndpoint - URL
|
|
18
|
-
*
|
|
19
|
-
* @returns {void} Does not return anything but freezes the endpoint configuration object.
|
|
15
|
+
* @param {EndpointConfig} config - An object containing the URLs for the authentication endpoints.
|
|
16
|
+
* @param {string} config.loginEndpoint - The URL for the login endpoint.
|
|
17
|
+
* @param {string} config.refreshEndpoint - The URL for the token refresh endpoint.
|
|
18
|
+
* @param {string} config.logoutEndpoint - The URL for the logout endpoint.
|
|
20
19
|
*/
|
|
21
20
|
export declare function configEndpoints(config: EndpointConfig): void;
|
|
22
21
|
/**
|
|
23
|
-
* Retrieves the configured authentication endpoint URLs.
|
|
22
|
+
* Retrieves the globally configured authentication endpoint URLs.
|
|
24
23
|
*
|
|
25
|
-
* @returns {EndpointsConfig}
|
|
26
|
-
* @property {string} LOGIN - URL of the login endpoint.
|
|
27
|
-
* @property {string} REFRESH - URL of the refresh token endpoint.
|
|
28
|
-
* @property {string} LOGOUT - URL of the logout endpoint.
|
|
24
|
+
* @returns {EndpointsConfig} A frozen object containing the configured `LOGIN`, `REFRESH`, and `LOGOUT` endpoints.
|
|
29
25
|
*/
|
|
30
26
|
export declare function getEndpointsConfig(): EndpointsConfig;
|
|
31
27
|
export {};
|
|
@@ -1,20 +1,17 @@
|
|
|
1
1
|
import { AppKeyConfig } from "../../types/AppKeyConfig";
|
|
2
2
|
/**
|
|
3
|
-
* Sets the main application encryption
|
|
4
|
-
* This
|
|
3
|
+
* Sets the main application key, which is intended for use in encryption and signing operations.
|
|
4
|
+
* This function should be called once at application startup to configure the key.
|
|
5
5
|
*
|
|
6
|
-
* @param {AppKeyConfig} config - An object containing the application
|
|
7
|
-
* @param {string} config.
|
|
8
|
-
*
|
|
9
|
-
* @returns {void} Does not return anything, but updates the application key.
|
|
6
|
+
* @param {AppKeyConfig} config - An object containing the application key.
|
|
7
|
+
* @param {string} config.appKey - The application key.
|
|
10
8
|
* @throws {Error} If the provided key is null, undefined, or an empty string.
|
|
11
9
|
*/
|
|
12
10
|
export declare function configAppKey(config: AppKeyConfig): void;
|
|
13
11
|
/**
|
|
14
|
-
* Retrieves the
|
|
15
|
-
* Throws an error if the application key has not been configured.
|
|
12
|
+
* Retrieves the configured application key.
|
|
16
13
|
*
|
|
17
|
-
* @returns {string} The configured application
|
|
18
|
-
* @throws {Error} If the application
|
|
14
|
+
* @returns {string} The configured application key.
|
|
15
|
+
* @throws {Error} If the application key has not been set by calling `configAppKey` first.
|
|
19
16
|
*/
|
|
20
17
|
export declare function getAppKey(): string;
|
|
@@ -1,34 +1,32 @@
|
|
|
1
1
|
import { LocationPreference, SessionConfigObject, SessionConfig } from "@/types/SessionConfig";
|
|
2
2
|
/**
|
|
3
|
-
* Configures the session
|
|
4
|
-
*
|
|
3
|
+
* Configures the session ID and persistence preference for the application.
|
|
4
|
+
* This function allows setting a custom session ID and specifying whether session-related
|
|
5
|
+
* data should be stored in `localStorage` or `sessionStorage`. The configuration is
|
|
6
|
+
* then encrypted and saved to the chosen storage.
|
|
5
7
|
*
|
|
6
|
-
*
|
|
7
|
-
*
|
|
8
|
-
*
|
|
9
|
-
*
|
|
10
|
-
* the
|
|
11
|
-
* @returns {Promise<void>} A promise that resolves when the session has been configured and saved.
|
|
8
|
+
* @param {SessionConfigObject} config - An object containing the session configuration.
|
|
9
|
+
* @param {string} [config.sessionId] - A unique identifier for the session. If not provided, the existing one is maintained.
|
|
10
|
+
* @param {LocationPreference} [config.persistencePreference] - The storage location ('local' or 'session').
|
|
11
|
+
* If not provided, the existing preference is maintained.
|
|
12
|
+
* @returns {Promise<void>} A promise that resolves once the session has been configured and saved.
|
|
12
13
|
*/
|
|
13
14
|
export declare function configSession(config: SessionConfigObject): Promise<void>;
|
|
14
15
|
/**
|
|
15
|
-
* Retrieves the current session identifier.
|
|
16
|
-
* Always attempts to load the configuration from storage. If it fails, it uses the internal state.
|
|
16
|
+
* Retrieves the current session identifier, loading it from storage if available.
|
|
17
17
|
*
|
|
18
|
-
* @returns {Promise<string>} A promise that resolves with the
|
|
18
|
+
* @returns {Promise<string>} A promise that resolves with the session ID.
|
|
19
19
|
*/
|
|
20
20
|
export declare function getSessionId(): Promise<string>;
|
|
21
21
|
/**
|
|
22
|
-
* Retrieves the current data persistence preference.
|
|
23
|
-
* Always attempts to load the configuration from storage. If it fails, it uses the internal state.
|
|
22
|
+
* Retrieves the current data persistence preference, loading it from storage if available.
|
|
24
23
|
*
|
|
25
|
-
* @returns {Promise<
|
|
24
|
+
* @returns {Promise<LocationPreference>} A promise that resolves with the persistence preference ('local' or 'session').
|
|
26
25
|
*/
|
|
27
26
|
export declare function getSessionPersistence(): Promise<LocationPreference>;
|
|
28
27
|
/**
|
|
29
|
-
* Retrieves the complete session configuration.
|
|
30
|
-
* Always attempts to load the configuration from storage. If it fails, it uses the internal state.
|
|
28
|
+
* Retrieves the complete session configuration object, loading it from storage if available.
|
|
31
29
|
*
|
|
32
|
-
* @returns {Promise<SessionConfig>} A promise that resolves with the session configuration
|
|
30
|
+
* @returns {Promise<SessionConfig>} A promise that resolves with the full session configuration.
|
|
33
31
|
*/
|
|
34
32
|
export declare function getSessionConfig(): Promise<SessionConfig>;
|