@nocios/crudify-ui 1.2.36 → 1.3.1

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
@@ -2,6 +2,7 @@ import crudify__default from '@nocios/crudify-browser';
2
2
  export * from '@nocios/crudify-browser';
3
3
  export { default as crudify } from '@nocios/crudify-browser';
4
4
  import React, { ReactNode } from 'react';
5
+ import * as react_jsx_runtime from 'react/jsx-runtime';
5
6
 
6
7
  type BoxScreenType = "login" | "signUp" | "forgotPassword" | "resetPassword" | "checkCode";
7
8
  interface CrudifyLoginConfig {
@@ -917,4 +918,416 @@ declare function parseJavaScriptError(error: unknown): ParsedError;
917
918
  */
918
919
  declare function handleCrudifyError(error: unknown): ParsedError[];
919
920
 
920
- export { type ApiError, type BoxScreenType, type CrudifyApiResponse, type CrudifyConfig, type CrudifyDataContextState, CrudifyDataProvider, type CrudifyDataProviderProps, CrudifyLogin, type CrudifyLoginConfig, type CrudifyLoginProps, type CrudifyLoginTranslations, type CrudifyTransactionResponse, type CrudifyUserData, ERROR_CODES, ERROR_SEVERITY_MAP, type ErrorCode, type ErrorSeverity, type ForgotPasswordRequest, type JWTPayload$1 as JWTPayload, type JwtPayload, type LoginRequest, type LoginResponse, type ParsedError, type ResetPasswordRequest, type ResolvedConfig, type TransactionResponseData, type UseCrudifyAuthReturn, type UseCrudifyConfigReturn, type UseCrudifyDataReturn, type UseCrudifyInstanceReturn, type UseCrudifyUserOptions, type UseCrudifyUserReturn, type UserLoginData, type UserProfile, UserProfileDisplay, type ValidateCodeRequest, type ValidationError, configurationManager, crudifyInitializer, decodeJwtSafely, getCookie, getCrudifyInstanceAsync, getCrudifyInstanceSync, getCurrentUserEmail, getErrorMessage, handleCrudifyError, isTokenExpired, parseApiError, parseJavaScriptError, parseTransactionError, secureLocalStorage, secureSessionStorage, tokenManager, useCrudifyAuth, useCrudifyConfig, useCrudifyData, useCrudifyDataContext, useCrudifyInstance, useCrudifyLogin, useCrudifyUser, useUserProfile };
921
+ type TokenData = {
922
+ accessToken: string;
923
+ refreshToken: string;
924
+ expiresAt: number;
925
+ refreshExpiresAt: number;
926
+ };
927
+ type StorageType = 'localStorage' | 'sessionStorage' | 'none';
928
+ declare class TokenStorage {
929
+ private static readonly TOKEN_KEY;
930
+ private static readonly ENCRYPTION_KEY;
931
+ private static storageType;
932
+ /**
933
+ * Configurar tipo de almacenamiento
934
+ */
935
+ static setStorageType(type: StorageType): void;
936
+ /**
937
+ * Verificar si el storage está disponible
938
+ */
939
+ private static isStorageAvailable;
940
+ /**
941
+ * Obtener instancia de storage
942
+ */
943
+ private static getStorage;
944
+ /**
945
+ * Encriptar datos sensibles
946
+ */
947
+ private static encrypt;
948
+ /**
949
+ * Desencriptar datos
950
+ */
951
+ private static decrypt;
952
+ /**
953
+ * Guardar tokens de forma segura
954
+ */
955
+ static saveTokens(tokens: TokenData): void;
956
+ /**
957
+ * Obtener tokens guardados
958
+ */
959
+ static getTokens(): TokenData | null;
960
+ /**
961
+ * Limpiar tokens almacenados
962
+ */
963
+ static clearTokens(): void;
964
+ /**
965
+ * Verificar si hay tokens válidos guardados
966
+ */
967
+ static hasValidTokens(): boolean;
968
+ /**
969
+ * Obtener información de expiración
970
+ */
971
+ static getExpirationInfo(): {
972
+ accessExpired: boolean;
973
+ refreshExpired: boolean;
974
+ accessExpiresIn: number;
975
+ refreshExpiresIn: number;
976
+ } | null;
977
+ /**
978
+ * Actualizar solo el access token (después de refresh)
979
+ */
980
+ static updateAccessToken(newAccessToken: string, newExpiresAt: number): void;
981
+ }
982
+
983
+ type SessionConfig = {
984
+ storageType?: StorageType;
985
+ autoRestore?: boolean;
986
+ enableLogging?: boolean;
987
+ onSessionExpired?: () => void;
988
+ onSessionRestored?: (tokens: TokenData) => void;
989
+ onLoginSuccess?: (tokens: TokenData) => void;
990
+ onLogout?: () => void;
991
+ };
992
+ type LoginResult = {
993
+ success: boolean;
994
+ tokens?: TokenData;
995
+ error?: string;
996
+ };
997
+ declare class SessionManager {
998
+ private static instance;
999
+ private config;
1000
+ private initialized;
1001
+ private constructor();
1002
+ static getInstance(): SessionManager;
1003
+ /**
1004
+ * Inicializar el SessionManager
1005
+ */
1006
+ initialize(config?: SessionConfig): Promise<void>;
1007
+ /**
1008
+ * Login con persistencia automática
1009
+ */
1010
+ login(email: string, password: string): Promise<LoginResult>;
1011
+ /**
1012
+ * Logout con limpieza de tokens
1013
+ */
1014
+ logout(): Promise<void>;
1015
+ /**
1016
+ * Restaurar sesión desde storage
1017
+ */
1018
+ restoreSession(): Promise<boolean>;
1019
+ /**
1020
+ * Verificar si el usuario está autenticado
1021
+ */
1022
+ isAuthenticated(): boolean;
1023
+ /**
1024
+ * Obtener información de tokens actuales
1025
+ */
1026
+ getTokenInfo(): {
1027
+ isLoggedIn: boolean;
1028
+ crudifyTokens: {
1029
+ accessToken: string;
1030
+ refreshToken: string;
1031
+ expiresAt: number;
1032
+ refreshExpiresAt: number;
1033
+ isExpired: boolean;
1034
+ isRefreshExpired: boolean;
1035
+ };
1036
+ storageInfo: {
1037
+ accessExpired: boolean;
1038
+ refreshExpired: boolean;
1039
+ accessExpiresIn: number;
1040
+ refreshExpiresIn: number;
1041
+ } | null;
1042
+ hasValidTokens: boolean;
1043
+ };
1044
+ /**
1045
+ * Refrescar tokens manualmente
1046
+ */
1047
+ refreshTokens(): Promise<boolean>;
1048
+ /**
1049
+ * Configurar interceptor de respuesta para manejo automático de errores
1050
+ */
1051
+ setupResponseInterceptor(): void;
1052
+ /**
1053
+ * Limpiar sesión completamente
1054
+ */
1055
+ clearSession(): void;
1056
+ private log;
1057
+ private formatError;
1058
+ }
1059
+
1060
+ type SessionState = {
1061
+ isAuthenticated: boolean;
1062
+ isLoading: boolean;
1063
+ isInitialized: boolean;
1064
+ tokens: TokenData | null;
1065
+ error: string | null;
1066
+ };
1067
+ type UseSessionOptions = {
1068
+ autoRestore?: boolean;
1069
+ enableLogging?: boolean;
1070
+ onSessionExpired?: () => void;
1071
+ onSessionRestored?: (tokens: TokenData) => void;
1072
+ };
1073
+ declare function useSession(options?: UseSessionOptions): {
1074
+ login: (email: string, password: string) => Promise<LoginResult>;
1075
+ logout: () => Promise<void>;
1076
+ refreshTokens: () => Promise<boolean>;
1077
+ clearError: () => void;
1078
+ getTokenInfo: () => {
1079
+ isLoggedIn: boolean;
1080
+ crudifyTokens: {
1081
+ accessToken: string;
1082
+ refreshToken: string;
1083
+ expiresAt: number;
1084
+ refreshExpiresAt: number;
1085
+ isExpired: boolean;
1086
+ isRefreshExpired: boolean;
1087
+ };
1088
+ storageInfo: {
1089
+ accessExpired: boolean;
1090
+ refreshExpired: boolean;
1091
+ accessExpiresIn: number;
1092
+ refreshExpiresIn: number;
1093
+ } | null;
1094
+ hasValidTokens: boolean;
1095
+ };
1096
+ isExpiringSoon: boolean;
1097
+ expiresIn: number;
1098
+ refreshExpiresIn: number;
1099
+ isAuthenticated: boolean;
1100
+ isLoading: boolean;
1101
+ isInitialized: boolean;
1102
+ tokens: TokenData | null;
1103
+ error: string | null;
1104
+ };
1105
+
1106
+ type SessionData = {
1107
+ _id: string;
1108
+ email: string;
1109
+ subscriberKey: string;
1110
+ [key: string]: any;
1111
+ } | null;
1112
+ type SessionContextType = {
1113
+ isAuthenticated: boolean;
1114
+ isLoading: boolean;
1115
+ isInitialized: boolean;
1116
+ tokens: TokenData | null;
1117
+ error: string | null;
1118
+ sessionData: SessionData;
1119
+ login: (email: string, password: string) => Promise<LoginResult>;
1120
+ logout: () => Promise<void>;
1121
+ refreshTokens: () => Promise<boolean>;
1122
+ clearError: () => void;
1123
+ getTokenInfo: () => any;
1124
+ isExpiringSoon: boolean;
1125
+ expiresIn: number;
1126
+ refreshExpiresIn: number;
1127
+ };
1128
+ type SessionProviderProps = {
1129
+ children: ReactNode;
1130
+ options?: UseSessionOptions;
1131
+ };
1132
+ /**
1133
+ * Provider de sesión para envolver la aplicación
1134
+ */
1135
+ declare function SessionProvider({ children, options }: SessionProviderProps): react_jsx_runtime.JSX.Element;
1136
+ /**
1137
+ * Hook para usar el contexto de sesión
1138
+ */
1139
+ declare function useSessionContext(): SessionContextType;
1140
+ /**
1141
+ * HOC para proteger rutas que requieren autenticación
1142
+ */
1143
+ type ProtectedRouteProps = {
1144
+ children: ReactNode;
1145
+ fallback?: ReactNode;
1146
+ redirectTo?: () => void;
1147
+ };
1148
+ declare function ProtectedRoute({ children, fallback, redirectTo }: ProtectedRouteProps): react_jsx_runtime.JSX.Element | null;
1149
+ /**
1150
+ * Componente para mostrar información de la sesión (debug)
1151
+ */
1152
+ declare function SessionDebugInfo(): react_jsx_runtime.JSX.Element;
1153
+
1154
+ declare function LoginComponent(): react_jsx_runtime.JSX.Element;
1155
+ /**
1156
+ * Componente simple de estado de sesión para mostrar en cualquier lugar
1157
+ */
1158
+ declare function SessionStatus(): react_jsx_runtime.JSX.Element;
1159
+
1160
+ /**
1161
+ * Complete user data structure (compatible con legacy)
1162
+ */
1163
+ interface UserData {
1164
+ session: any | null;
1165
+ data: UserProfile | null;
1166
+ }
1167
+ /**
1168
+ * Return type compatible con useCrudifyUser legacy
1169
+ */
1170
+ interface UseUserDataReturn {
1171
+ user: UserData;
1172
+ loading: boolean;
1173
+ error: string | null;
1174
+ refreshProfile: () => Promise<void>;
1175
+ clearProfile: () => void;
1176
+ }
1177
+ /**
1178
+ * Options compatible con useCrudifyUser legacy
1179
+ */
1180
+ interface UseUserDataOptions {
1181
+ autoFetch?: boolean;
1182
+ retryOnError?: boolean;
1183
+ maxRetries?: number;
1184
+ }
1185
+ /**
1186
+ * useUserData - Hook completo que reemplaza useCrudifyUser del sistema legacy
1187
+ *
1188
+ * Funcionalidades completas:
1189
+ * - Auto-fetch de datos del usuario desde la base de datos
1190
+ * - Manejo inteligente de caché y deduplicación
1191
+ * - Mecanismo de retry para errores de red
1192
+ * - Sincronización cross-tab vía SessionProvider
1193
+ * - Formateo extendido de datos para display
1194
+ * - Limpieza apropiada y gestión de memoria
1195
+ * - Compatible 100% con API de useCrudifyUser legacy
1196
+ * - Usa el nuevo sistema de refresh tokens por debajo
1197
+ */
1198
+ declare const useUserData: (options?: UseUserDataOptions) => UseUserDataReturn;
1199
+
1200
+ /**
1201
+ * Return type compatible con useCrudifyAuth legacy
1202
+ */
1203
+ interface UseAuthReturn {
1204
+ isAuthenticated: boolean;
1205
+ loading: boolean;
1206
+ error: string | null;
1207
+ token: string | null;
1208
+ user: any | null;
1209
+ tokenExpiration: Date | null;
1210
+ setToken: (token: string | null) => void;
1211
+ logout: () => Promise<void>;
1212
+ refreshToken: () => Promise<boolean>;
1213
+ login: (email: string, password: string) => Promise<any>;
1214
+ isExpiringSoon: boolean;
1215
+ expiresIn: number;
1216
+ refreshExpiresIn: number;
1217
+ getTokenInfo: () => any;
1218
+ clearError: () => void;
1219
+ }
1220
+ /**
1221
+ * useAuth - Hook de autenticación completo
1222
+ *
1223
+ * Este hook reemplaza completamente a useCrudifyAuth del sistema legacy
1224
+ * manteniendo 100% compatibilidad de API pero usando el nuevo SessionProvider
1225
+ * que incluye Refresh Token Pattern, almacenamiento seguro, y gestión automática
1226
+ * de expiración de tokens.
1227
+ *
1228
+ * Funcionalidades completas:
1229
+ * - Estado de autenticación en tiempo real
1230
+ * - Validación automática de tokens
1231
+ * - Sincronización cross-tab
1232
+ * - Acciones simples login/logout
1233
+ * - Acceso al payload JWT vía sessionData
1234
+ * - Refresh automático de tokens
1235
+ * - Gestión de expiración de sesiones
1236
+ * - Almacenamiento seguro y encriptado
1237
+ * - Compatibilidad 100% con API legacy
1238
+ *
1239
+ * @example
1240
+ * ```tsx
1241
+ * function LoginComponent() {
1242
+ * const { isAuthenticated, login, logout, user } = useAuth();
1243
+ *
1244
+ * if (isAuthenticated) {
1245
+ * return (
1246
+ * <div>
1247
+ * Welcome {user?.email}!
1248
+ * <button onClick={logout}>Logout</button>
1249
+ * </div>
1250
+ * );
1251
+ * }
1252
+ *
1253
+ * return <LoginForm onLogin={login} />;
1254
+ * }
1255
+ * ```
1256
+ */
1257
+ declare const useAuth: () => UseAuthReturn;
1258
+
1259
+ /**
1260
+ * Return type compatible con useCrudifyData legacy
1261
+ */
1262
+ interface UseDataReturn {
1263
+ readItems: (moduleKey: string, filter?: object, options?: any) => Promise<CrudifyApiResponse>;
1264
+ readItem: (moduleKey: string, filter: object, options?: any) => Promise<CrudifyApiResponse>;
1265
+ createItem: (moduleKey: string, data: object, options?: any) => Promise<CrudifyApiResponse>;
1266
+ updateItem: (moduleKey: string, data: object, options?: any) => Promise<CrudifyApiResponse>;
1267
+ deleteItem: (moduleKey: string, id: string, options?: any) => Promise<CrudifyApiResponse>;
1268
+ transaction: (operations: any[], options?: any) => Promise<CrudifyApiResponse>;
1269
+ login: (email: string, password: string) => Promise<CrudifyApiResponse>;
1270
+ isInitialized: boolean;
1271
+ isInitializing: boolean;
1272
+ initializationError: string | null;
1273
+ isReady: () => boolean;
1274
+ waitForReady: () => Promise<void>;
1275
+ }
1276
+ /**
1277
+ * useData - Hook completo para operaciones de datos
1278
+ *
1279
+ * Este hook reemplaza completamente a useCrudifyData del sistema legacy
1280
+ * manteniendo 100% compatibilidad de API pero usando el nuevo SessionProvider
1281
+ * que proporciona mejor manejo de estados y errores.
1282
+ *
1283
+ * Funcionalidades completas:
1284
+ * - Verificación automática de inicialización
1285
+ * - Operaciones CRUD type-safe
1286
+ * - Soporte para transacciones
1287
+ * - Operaciones de login
1288
+ * - Gestión de estados ready
1289
+ * - Manejo apropiado de errores
1290
+ * - Compatible 100% con API legacy
1291
+ *
1292
+ * Todas las operaciones verifican que el sistema esté inicializado correctamente,
1293
+ * asegurando integridad de datos y previniendo fallas silenciosas.
1294
+ *
1295
+ * @example
1296
+ * ```tsx
1297
+ * function DataComponent() {
1298
+ * const {
1299
+ * readItems,
1300
+ * createItem,
1301
+ * isInitialized,
1302
+ * isReady
1303
+ * } = useData();
1304
+ *
1305
+ * const loadUsers = async () => {
1306
+ * if (!isReady()) {
1307
+ * console.warn("System not ready yet");
1308
+ * return;
1309
+ * }
1310
+ *
1311
+ * try {
1312
+ * const response = await readItems("users", { limit: 10 });
1313
+ * if (response.success) {
1314
+ * console.log("Users:", response.data);
1315
+ * }
1316
+ * } catch (error) {
1317
+ * console.error("Error loading users:", error);
1318
+ * }
1319
+ * };
1320
+ *
1321
+ * return (
1322
+ * <div>
1323
+ * <button onClick={loadUsers} disabled={!isInitialized}>
1324
+ * Load Users
1325
+ * </button>
1326
+ * </div>
1327
+ * );
1328
+ * }
1329
+ * ```
1330
+ */
1331
+ declare const useData: () => UseDataReturn;
1332
+
1333
+ export { type ApiError, type BoxScreenType, type CrudifyApiResponse, type CrudifyConfig, type CrudifyDataContextState, CrudifyDataProvider, type CrudifyDataProviderProps, CrudifyLogin, type CrudifyLoginConfig, type CrudifyLoginProps, type CrudifyLoginTranslations, type CrudifyTransactionResponse, type CrudifyUserData, ERROR_CODES, ERROR_SEVERITY_MAP, type ErrorCode, type ErrorSeverity, type ForgotPasswordRequest, type JWTPayload$1 as JWTPayload, type JwtPayload, LoginComponent, type LoginRequest, type LoginResponse, type LoginResult, type ParsedError, ProtectedRoute, type ProtectedRouteProps, type ResetPasswordRequest, type ResolvedConfig, type SessionConfig, SessionDebugInfo, SessionManager, SessionProvider, type SessionProviderProps, type SessionState, SessionStatus, type StorageType, type TokenData, TokenStorage, type TransactionResponseData, type UseAuthReturn, type UseCrudifyAuthReturn, type UseCrudifyConfigReturn, type UseCrudifyDataReturn, type UseCrudifyInstanceReturn, type UseCrudifyUserOptions, type UseCrudifyUserReturn, type UseDataReturn, type UseSessionOptions, type UseUserDataOptions, type UseUserDataReturn, type UserData, type UserLoginData, type UserProfile, UserProfileDisplay, type ValidateCodeRequest, type ValidationError, configurationManager, crudifyInitializer, decodeJwtSafely, getCookie, getCrudifyInstanceAsync, getCrudifyInstanceSync, getCurrentUserEmail, getErrorMessage, handleCrudifyError, isTokenExpired, parseApiError, parseJavaScriptError, parseTransactionError, secureLocalStorage, secureSessionStorage, tokenManager, useAuth, useCrudifyAuth, useCrudifyConfig, useCrudifyData, useCrudifyDataContext, useCrudifyInstance, useCrudifyLogin, useCrudifyUser, useData, useSession, useSessionContext, useUserData, useUserProfile };