@nocios/crudify-ui 4.0.8 → 4.0.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.
@@ -0,0 +1,427 @@
1
+ import { U as UserProfile, C as CrudifyApiResponse } from './api-Djqihi4n.js';
2
+ import { b as NotificationSeverity } from './GlobalNotificationProvider-C3iWgM1z.js';
3
+ import { CrudifyResponse } from '@nocios/crudify-browser';
4
+
5
+ type TokenData = {
6
+ accessToken: string;
7
+ refreshToken: string;
8
+ expiresAt: number;
9
+ refreshExpiresAt: number;
10
+ };
11
+ type StorageType = "localStorage" | "sessionStorage" | "none";
12
+ declare class TokenStorage {
13
+ private static readonly TOKEN_KEY;
14
+ private static readonly ENCRYPTION_KEY_STORAGE;
15
+ private static encryptionKey;
16
+ private static storageType;
17
+ /**
18
+ * Configurar tipo de almacenamiento
19
+ */
20
+ static setStorageType(type: StorageType): void;
21
+ /**
22
+ * Generar clave de encriptación única y persistente
23
+ */
24
+ private static generateEncryptionKey;
25
+ /**
26
+ * Obtener o generar clave de encriptación
27
+ */
28
+ private static getEncryptionKey;
29
+ /**
30
+ * Verificar si el storage está disponible
31
+ */
32
+ private static isStorageAvailable;
33
+ /**
34
+ * Obtener instancia de storage
35
+ */
36
+ private static getStorage;
37
+ /**
38
+ * Encriptar datos sensibles
39
+ */
40
+ private static encrypt;
41
+ /**
42
+ * Desencriptar datos
43
+ */
44
+ private static decrypt;
45
+ /**
46
+ * Guardar tokens de forma segura
47
+ */
48
+ static saveTokens(tokens: TokenData): void;
49
+ /**
50
+ * Obtener tokens guardados
51
+ */
52
+ static getTokens(): TokenData | null;
53
+ /**
54
+ * Limpiar tokens almacenados
55
+ */
56
+ static clearTokens(): void;
57
+ /**
58
+ * Rotar clave de encriptación (limpia tokens existentes por seguridad)
59
+ */
60
+ static rotateEncryptionKey(): void;
61
+ /**
62
+ * Verificar si hay tokens válidos guardados
63
+ */
64
+ static hasValidTokens(): boolean;
65
+ /**
66
+ * Obtener información de expiración
67
+ */
68
+ static getExpirationInfo(): {
69
+ accessExpired: boolean;
70
+ refreshExpired: boolean;
71
+ accessExpiresIn: number;
72
+ refreshExpiresIn: number;
73
+ } | null;
74
+ /**
75
+ * Actualizar solo el access token (después de refresh)
76
+ */
77
+ static updateAccessToken(newAccessToken: string, newExpiresAt: number): void;
78
+ }
79
+
80
+ type SessionConfig = {
81
+ storageType?: StorageType;
82
+ autoRestore?: boolean;
83
+ enableLogging?: boolean;
84
+ onSessionExpired?: () => void;
85
+ onSessionRestored?: (tokens: TokenData) => void;
86
+ onLoginSuccess?: (tokens: TokenData) => void;
87
+ onLogout?: () => void;
88
+ showNotification?: (message: string, severity?: "error" | "info" | "success" | "warning") => void;
89
+ translateFn?: (key: string) => string;
90
+ };
91
+ type LoginResult = {
92
+ success: boolean;
93
+ tokens?: TokenData;
94
+ data?: any;
95
+ error?: string;
96
+ rawResponse?: any;
97
+ };
98
+ declare class SessionManager {
99
+ private static instance;
100
+ private config;
101
+ private initialized;
102
+ private constructor();
103
+ static getInstance(): SessionManager;
104
+ /**
105
+ * Inicializar el SessionManager
106
+ */
107
+ initialize(config?: SessionConfig): Promise<void>;
108
+ /**
109
+ * Login con persistencia automática
110
+ */
111
+ login(email: string, password: string): Promise<LoginResult>;
112
+ /**
113
+ * Logout con limpieza de tokens
114
+ */
115
+ logout(): Promise<void>;
116
+ /**
117
+ * Restaurar sesión desde storage
118
+ */
119
+ restoreSession(): Promise<boolean>;
120
+ /**
121
+ * Verificar si el usuario está autenticado
122
+ */
123
+ isAuthenticated(): boolean;
124
+ /**
125
+ * Obtener información de tokens actuales
126
+ */
127
+ getTokenInfo(): {
128
+ isLoggedIn: boolean;
129
+ crudifyTokens: {
130
+ accessToken: string;
131
+ refreshToken: string;
132
+ expiresAt: number;
133
+ refreshExpiresAt: number;
134
+ isExpired: boolean;
135
+ isRefreshExpired: boolean;
136
+ };
137
+ storageInfo: {
138
+ accessExpired: boolean;
139
+ refreshExpired: boolean;
140
+ accessExpiresIn: number;
141
+ refreshExpiresIn: number;
142
+ } | null;
143
+ hasValidTokens: boolean;
144
+ };
145
+ /**
146
+ * Refrescar tokens manualmente
147
+ */
148
+ refreshTokens(): Promise<boolean>;
149
+ /**
150
+ * Configurar interceptor de respuesta para manejo automático de errores
151
+ */
152
+ setupResponseInterceptor(): void;
153
+ /**
154
+ * Detectar errores de autorización en todos los formatos posibles
155
+ */
156
+ private detectAuthorizationError;
157
+ /**
158
+ * Limpiar sesión completamente
159
+ */
160
+ clearSession(): void;
161
+ /**
162
+ * Obtener mensaje de sesión expirada traducido
163
+ */
164
+ private getSessionExpiredMessage;
165
+ private log;
166
+ private formatError;
167
+ }
168
+
169
+ type SessionState = {
170
+ isAuthenticated: boolean;
171
+ isLoading: boolean;
172
+ isInitialized: boolean;
173
+ tokens: TokenData | null;
174
+ error: string | null;
175
+ };
176
+ type UseSessionOptions = {
177
+ autoRestore?: boolean;
178
+ enableLogging?: boolean;
179
+ onSessionExpired?: () => void;
180
+ onSessionRestored?: (tokens: TokenData) => void;
181
+ showNotification?: (message: string, severity?: "error" | "info" | "success" | "warning") => void;
182
+ translateFn?: (key: string) => string;
183
+ };
184
+ declare function useSession(options?: UseSessionOptions): {
185
+ login: (email: string, password: string) => Promise<LoginResult>;
186
+ logout: () => Promise<void>;
187
+ refreshTokens: () => Promise<boolean>;
188
+ clearError: () => void;
189
+ getTokenInfo: () => {
190
+ isLoggedIn: boolean;
191
+ crudifyTokens: {
192
+ accessToken: string;
193
+ refreshToken: string;
194
+ expiresAt: number;
195
+ refreshExpiresAt: number;
196
+ isExpired: boolean;
197
+ isRefreshExpired: boolean;
198
+ };
199
+ storageInfo: {
200
+ accessExpired: boolean;
201
+ refreshExpired: boolean;
202
+ accessExpiresIn: number;
203
+ refreshExpiresIn: number;
204
+ } | null;
205
+ hasValidTokens: boolean;
206
+ };
207
+ isExpiringSoon: boolean;
208
+ expiresIn: number;
209
+ refreshExpiresIn: number;
210
+ isAuthenticated: boolean;
211
+ isLoading: boolean;
212
+ isInitialized: boolean;
213
+ tokens: TokenData | null;
214
+ error: string | null;
215
+ };
216
+
217
+ /**
218
+ * Complete user data structure (compatible con legacy)
219
+ */
220
+ interface UserData {
221
+ session: any | null;
222
+ data: UserProfile | null;
223
+ }
224
+ /**
225
+ * Return type compatible con useCrudifyUser legacy
226
+ */
227
+ interface UseUserDataReturn {
228
+ user: UserData;
229
+ loading: boolean;
230
+ error: string | null;
231
+ refreshProfile: () => Promise<void>;
232
+ clearProfile: () => void;
233
+ }
234
+ /**
235
+ * Options compatible con useCrudifyUser legacy
236
+ */
237
+ interface UseUserDataOptions {
238
+ autoFetch?: boolean;
239
+ retryOnError?: boolean;
240
+ maxRetries?: number;
241
+ }
242
+ /**
243
+ * useUserData - Hook completo que reemplaza useCrudifyUser del sistema legacy
244
+ *
245
+ * Funcionalidades completas:
246
+ * - Auto-fetch de datos del usuario desde la base de datos
247
+ * - Manejo inteligente de caché y deduplicación
248
+ * - Mecanismo de retry para errores de red
249
+ * - Sincronización cross-tab vía SessionProvider
250
+ * - Formateo extendido de datos para display
251
+ * - Limpieza apropiada y gestión de memoria
252
+ * - Compatible 100% con API de useCrudifyUser legacy
253
+ * - Usa el nuevo sistema de refresh tokens por debajo
254
+ */
255
+ declare const useUserData: (options?: UseUserDataOptions) => UseUserDataReturn;
256
+
257
+ /**
258
+ * Return type compatible con useCrudifyAuth legacy
259
+ */
260
+ interface UseAuthReturn {
261
+ isAuthenticated: boolean;
262
+ loading: boolean;
263
+ error: string | null;
264
+ token: string | null;
265
+ user: any | null;
266
+ tokenExpiration: Date | null;
267
+ setToken: (token: string | null) => void;
268
+ logout: () => Promise<void>;
269
+ refreshToken: () => Promise<boolean>;
270
+ login: (email: string, password: string) => Promise<any>;
271
+ isExpiringSoon: boolean;
272
+ expiresIn: number;
273
+ refreshExpiresIn: number;
274
+ getTokenInfo: () => any;
275
+ clearError: () => void;
276
+ }
277
+ /**
278
+ * useAuth - Hook de autenticación completo
279
+ *
280
+ * Este hook reemplaza completamente a useCrudifyAuth del sistema legacy
281
+ * manteniendo 100% compatibilidad de API pero usando el nuevo SessionProvider
282
+ * que incluye Refresh Token Pattern, almacenamiento seguro, y gestión automática
283
+ * de expiración de tokens.
284
+ *
285
+ * Funcionalidades completas:
286
+ * - Estado de autenticación en tiempo real
287
+ * - Validación automática de tokens
288
+ * - Sincronización cross-tab
289
+ * - Acciones simples login/logout
290
+ * - Acceso al payload JWT vía sessionData
291
+ * - Refresh automático de tokens
292
+ * - Gestión de expiración de sesiones
293
+ * - Almacenamiento seguro y encriptado
294
+ * - Compatibilidad 100% con API legacy
295
+ *
296
+ * @example
297
+ * ```tsx
298
+ * function LoginComponent() {
299
+ * const { isAuthenticated, login, logout, user } = useAuth();
300
+ *
301
+ * if (isAuthenticated) {
302
+ * return (
303
+ * <div>
304
+ * Welcome {user?.email}!
305
+ * <button onClick={logout}>Logout</button>
306
+ * </div>
307
+ * );
308
+ * }
309
+ *
310
+ * return <LoginForm onLogin={login} />;
311
+ * }
312
+ * ```
313
+ */
314
+ declare const useAuth: () => UseAuthReturn;
315
+
316
+ /**
317
+ * Return type compatible con useCrudifyData legacy
318
+ */
319
+ interface UseDataReturn {
320
+ readItems: (moduleKey: string, filter?: object, options?: any) => Promise<CrudifyApiResponse>;
321
+ readItem: (moduleKey: string, filter: object, options?: any) => Promise<CrudifyApiResponse>;
322
+ createItem: (moduleKey: string, data: object, options?: any) => Promise<CrudifyApiResponse>;
323
+ updateItem: (moduleKey: string, data: object, options?: any) => Promise<CrudifyApiResponse>;
324
+ deleteItem: (moduleKey: string, id: string, options?: any) => Promise<CrudifyApiResponse>;
325
+ transaction: (operations: any[], options?: any) => Promise<CrudifyApiResponse>;
326
+ login: (email: string, password: string) => Promise<CrudifyApiResponse>;
327
+ isInitialized: boolean;
328
+ isInitializing: boolean;
329
+ initializationError: string | null;
330
+ isReady: () => boolean;
331
+ waitForReady: () => Promise<void>;
332
+ }
333
+ /**
334
+ * useData - Hook completo para operaciones de datos
335
+ *
336
+ * Este hook reemplaza completamente a useCrudifyData del sistema legacy
337
+ * manteniendo 100% compatibilidad de API pero usando el nuevo SessionProvider
338
+ * que proporciona mejor manejo de estados y errores.
339
+ *
340
+ * Funcionalidades completas:
341
+ * - Verificación automática de inicialización
342
+ * - Operaciones CRUD type-safe
343
+ * - Soporte para transacciones
344
+ * - Operaciones de login
345
+ * - Gestión de estados ready
346
+ * - Manejo apropiado de errores
347
+ * - Compatible 100% con API legacy
348
+ *
349
+ * Todas las operaciones verifican que el sistema esté inicializado correctamente,
350
+ * asegurando integridad de datos y previniendo fallas silenciosas.
351
+ *
352
+ * @example
353
+ * ```tsx
354
+ * function DataComponent() {
355
+ * const {
356
+ * readItems,
357
+ * createItem,
358
+ * isInitialized,
359
+ * isReady
360
+ * } = useData();
361
+ *
362
+ * const loadUsers = async () => {
363
+ * if (!isReady()) {
364
+ * console.warn("System not ready yet");
365
+ * return;
366
+ * }
367
+ *
368
+ * try {
369
+ * const response = await readItems("users", { limit: 10 });
370
+ * if (response.success) {
371
+ * console.log("Users:", response.data);
372
+ * }
373
+ * } catch (error) {
374
+ * console.error("Error loading users:", error);
375
+ * }
376
+ * };
377
+ *
378
+ * return (
379
+ * <div>
380
+ * <button onClick={loadUsers} disabled={!isInitialized}>
381
+ * Load Users
382
+ * </button>
383
+ * </div>
384
+ * );
385
+ * }
386
+ * ```
387
+ */
388
+ declare const useData: () => UseDataReturn;
389
+
390
+ interface UseUserProfileOptions {
391
+ autoFetch?: boolean;
392
+ retryOnError?: boolean;
393
+ maxRetries?: number;
394
+ }
395
+ interface UseUserProfileReturn {
396
+ userProfile: UserProfile | null;
397
+ loading: boolean;
398
+ error: string | null;
399
+ extendedData: Record<string, any>;
400
+ refreshProfile: () => Promise<void>;
401
+ clearProfile: () => void;
402
+ }
403
+ declare const useUserProfile: (options?: UseUserProfileOptions) => UseUserProfileReturn;
404
+
405
+ interface CrudifyWithNotificationsOptions {
406
+ showSuccessNotifications?: boolean;
407
+ showErrorNotifications?: boolean;
408
+ customErrorMessages?: Record<string, string>;
409
+ defaultErrorMessage?: string;
410
+ autoHideDuration?: number;
411
+ appStructure?: any[];
412
+ translateFn?: (key: string, options?: any) => string;
413
+ }
414
+ declare const useCrudifyWithNotifications: (options?: CrudifyWithNotificationsOptions) => {
415
+ createItem: (moduleKey: string, data: object, options?: any) => Promise<CrudifyResponse>;
416
+ updateItem: (moduleKey: string, data: object, options?: any) => Promise<CrudifyResponse>;
417
+ deleteItem: (moduleKey: string, id: string, options?: any) => Promise<CrudifyResponse>;
418
+ readItem: (moduleKey: string, filter: object, options?: any) => Promise<CrudifyResponse>;
419
+ readItems: (moduleKey: string, filter: object, options?: any) => Promise<CrudifyResponse>;
420
+ transaction: (data: any, options?: any) => Promise<CrudifyResponse>;
421
+ handleResponse: (response: CrudifyResponse, successMessage?: string) => CrudifyResponse;
422
+ getErrorMessage: (response: CrudifyResponse) => string;
423
+ getErrorSeverity: (response: CrudifyResponse) => NotificationSeverity;
424
+ shouldShowNotification: (response: CrudifyResponse) => boolean;
425
+ };
426
+
427
+ export { type LoginResult as L, SessionManager as S, type TokenData as T, type UseSessionOptions as U, type SessionConfig as a, TokenStorage as b, type StorageType as c, type SessionState as d, useUserData as e, type UseUserDataReturn as f, type UseUserDataOptions as g, type UserData as h, useAuth as i, type UseAuthReturn as j, useData as k, type UseDataReturn as l, useUserProfile as m, useCrudifyWithNotifications as n, useSession as u };
@@ -0,0 +1,78 @@
1
+ import React from 'react';
2
+ import './GlobalNotificationProvider-C3iWgM1z.js';
3
+ import * as react_jsx_runtime from 'react/jsx-runtime';
4
+
5
+ type BoxScreenType = "login" | "signUp" | "forgotPassword" | "resetPassword" | "checkCode";
6
+ interface CrudifyLoginConfig {
7
+ publicApiKey?: string | null;
8
+ env?: "dev" | "stg" | "api" | "prod";
9
+ appName?: string;
10
+ logo?: string;
11
+ loginActions?: string[];
12
+ }
13
+ interface CrudifyLoginTranslations {
14
+ [key: string]: string | CrudifyLoginTranslations;
15
+ }
16
+ interface UserLoginData {
17
+ token: string;
18
+ username?: string;
19
+ email?: string;
20
+ userId?: string;
21
+ profile?: any;
22
+ [key: string]: any;
23
+ }
24
+ interface CrudifyLoginProps {
25
+ onScreenChange?: (screen: BoxScreenType, params?: Record<string, string>) => void;
26
+ onExternalNavigate?: (path: string) => void;
27
+ onLoginSuccess?: (userData: UserLoginData, redirectUrl?: string) => void;
28
+ onError?: (error: string) => void;
29
+ initialScreen?: BoxScreenType;
30
+ redirectUrl?: string;
31
+ autoReadFromCookies?: boolean;
32
+ translations?: CrudifyLoginTranslations;
33
+ translationsUrl?: string;
34
+ language?: string;
35
+ }
36
+
37
+ declare const CrudifyLogin: React.FC<CrudifyLoginProps>;
38
+
39
+ interface UserProfileDisplayProps {
40
+ showExtendedData?: boolean;
41
+ showProfileCard?: boolean;
42
+ autoRefresh?: boolean;
43
+ }
44
+ declare const UserProfileDisplay: React.FC<UserProfileDisplayProps>;
45
+
46
+ declare const POLICY_ACTIONS: readonly ["create", "read", "update", "delete"];
47
+ type PolicyAction = typeof POLICY_ACTIONS[number];
48
+ declare const PREFERRED_POLICY_ORDER: PolicyAction[];
49
+
50
+ type Policy = {
51
+ id: string;
52
+ action: PolicyAction;
53
+ fields?: {
54
+ allow: string[];
55
+ owner_allow: string[];
56
+ deny: string[];
57
+ };
58
+ permission?: string;
59
+ };
60
+ type FieldErrorMap = string | ({
61
+ _error?: string;
62
+ } & Record<string, string | undefined>);
63
+ interface PoliciesProps {
64
+ policies: Policy[];
65
+ onChange: (next: Policy[]) => void;
66
+ availableFields: string[];
67
+ errors?: FieldErrorMap;
68
+ isSubmitting?: boolean;
69
+ }
70
+ declare const Policies: React.FC<PoliciesProps>;
71
+
72
+ declare function LoginComponent(): react_jsx_runtime.JSX.Element;
73
+ /**
74
+ * Componente simple de estado de sesión para mostrar en cualquier lugar
75
+ */
76
+ declare function SessionStatus(): react_jsx_runtime.JSX.Element;
77
+
78
+ export { type BoxScreenType as B, CrudifyLogin as C, LoginComponent as L, Policies as P, SessionStatus as S, UserProfileDisplay as U, POLICY_ACTIONS as a, PREFERRED_POLICY_ORDER as b, type PolicyAction as c, type CrudifyLoginConfig as d, type CrudifyLoginProps as e, type CrudifyLoginTranslations as f, type UserLoginData as g };