@nocios/crudify-ui 4.0.92 → 4.0.96

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/utils.d.ts CHANGED
@@ -1,124 +1,55 @@
1
- import { J as JwtPayload } from './api-Djqihi4n.js';
1
+ export { E as ERROR_CODES, j as ERROR_SEVERITY_MAP, k as ErrorCode, l as ErrorSeverity, q as ErrorTranslationConfig, P as ParsedError, o as createErrorTranslator, d as decodeJwtSafely, a as getCookie, g as getCurrentUserEmail, f as getErrorMessage, h as handleCrudifyError, i as isTokenExpired, p as parseApiError, e as parseJavaScriptError, c as parseTransactionError, b as secureLocalStorage, s as secureSessionStorage, n as translateError, t as translateErrorCode, m as translateErrorCodes } from './errorTranslation-CBbQYNWR.js';
2
+ import './api-Djqihi4n.js';
2
3
 
3
- interface JWTPayload extends JwtPayload {
4
- "cognito:username"?: string;
5
- }
6
- declare const decodeJwtSafely: (token: string) => JWTPayload | null;
7
- declare const getCurrentUserEmail: () => string | null;
8
- declare const isTokenExpired: (token: string) => boolean;
9
-
10
- declare const getCookie: (name: string) => string | null;
11
-
12
- declare class SecureStorage {
13
- private readonly encryptionKey;
14
- private readonly storage;
15
- constructor(storageType?: "localStorage" | "sessionStorage");
16
- private generateEncryptionKey;
17
- setItem(key: string, value: string, expiryMinutes?: number): void;
18
- getItem(key: string): string | null;
19
- removeItem(key: string): void;
20
- setToken(token: string): void;
21
- getToken(): string | null;
22
- }
23
- declare const secureSessionStorage: SecureStorage;
24
- declare const secureLocalStorage: SecureStorage;
25
-
26
- declare const ERROR_CODES: {
27
- readonly INVALID_CREDENTIALS: "INVALID_CREDENTIALS";
28
- readonly UNAUTHORIZED: "UNAUTHORIZED";
29
- readonly INVALID_API_KEY: "INVALID_API_KEY";
30
- readonly USER_NOT_FOUND: "USER_NOT_FOUND";
31
- readonly USER_NOT_ACTIVE: "USER_NOT_ACTIVE";
32
- readonly NO_PERMISSION: "NO_PERMISSION";
33
- readonly ITEM_NOT_FOUND: "ITEM_NOT_FOUND";
34
- readonly NOT_FOUND: "NOT_FOUND";
35
- readonly IN_USE: "IN_USE";
36
- readonly FIELD_ERROR: "FIELD_ERROR";
37
- readonly BAD_REQUEST: "BAD_REQUEST";
38
- readonly INVALID_EMAIL: "INVALID_EMAIL";
39
- readonly INVALID_CODE: "INVALID_CODE";
40
- readonly INTERNAL_SERVER_ERROR: "INTERNAL_SERVER_ERROR";
41
- readonly DATABASE_CONNECTION_ERROR: "DATABASE_CONNECTION_ERROR";
42
- readonly INVALID_CONFIGURATION: "INVALID_CONFIGURATION";
43
- readonly UNKNOWN_OPERATION: "UNKNOWN_OPERATION";
44
- readonly TOO_MANY_REQUESTS: "TOO_MANY_REQUESTS";
45
- readonly NETWORK_ERROR: "NETWORK_ERROR";
46
- readonly TIMEOUT_ERROR: "TIMEOUT_ERROR";
47
- };
48
- type ErrorCode = (typeof ERROR_CODES)[keyof typeof ERROR_CODES];
49
- type ErrorSeverity = "info" | "warning" | "error" | "critical";
50
- declare const ERROR_SEVERITY_MAP: Record<ErrorCode, ErrorSeverity>;
51
- interface ParsedError {
52
- code: ErrorCode;
53
- message: string;
54
- severity: ErrorSeverity;
55
- field?: string;
56
- details?: Record<string, unknown>;
57
- }
58
- /**
59
- * Parse a Crudify API response and extract standardized error information
60
- */
61
- declare function parseApiError(response: unknown): ParsedError[];
62
- /**
63
- * Parse transaction response errors
64
- */
65
- declare function parseTransactionError(response: unknown): ParsedError[];
66
- /**
67
- * Get a human-readable error message for an error code
68
- */
69
- declare function getErrorMessage(code: ErrorCode): string;
70
- /**
71
- * Handle JavaScript/Network errors and convert to ParsedError
72
- */
73
- declare function parseJavaScriptError(error: unknown): ParsedError;
74
4
  /**
75
- * Universal error handler that can process any type of error from Crudify APIs
5
+ * Event Bus para coordinar acciones de autenticación
6
+ * Previene race conditions y asegura respuesta única a errores
7
+ *
8
+ * Uso:
9
+ * - Emitir eventos cuando hay errores de autenticación
10
+ * - Suscribirse para recibir notificaciones de eventos
11
+ * - Debounce automático para evitar múltiples disparos
76
12
  */
77
- declare function handleCrudifyError(error: unknown): ParsedError[];
78
-
79
- /**
80
- * Utilidad robusta para traducir códigos de error con fallbacks inteligentes
81
- * Busca en múltiples namespaces y devuelve la traducción más específica disponible
82
- */
83
- interface ErrorTranslationConfig {
84
- /** Función de traducción de i18next */
85
- translateFn: (key: string) => string;
86
- /** Idioma actual (opcional, para logging) */
87
- currentLanguage?: string;
88
- /** Habilitar logs de debug */
89
- enableDebug?: boolean;
90
- }
91
- /**
92
- * Traduce un código de error usando jerarquía de fallbacks
93
- */
94
- declare function translateErrorCode(errorCode: string, config: ErrorTranslationConfig): string;
95
- /**
96
- * Traduce múltiples códigos de error
97
- */
98
- declare function translateErrorCodes(errorCodes: string[], config: ErrorTranslationConfig): string[];
99
- /**
100
- * Traduce un error completo (código + mensaje personalizado)
101
- */
102
- declare function translateError(error: {
103
- code: string;
13
+ type AuthEventType = "SESSION_EXPIRED" | "TOKEN_REFRESH_FAILED" | "UNAUTHORIZED";
14
+ type AuthEventDetails = {
104
15
  message?: string;
105
- field?: string;
106
- }, config: ErrorTranslationConfig): string;
107
- /**
108
- * Hook para usar en componentes React con i18next
109
- */
110
- declare function createErrorTranslator(translateFn: (key: string) => string, options?: {
111
- currentLanguage?: string;
112
- enableDebug?: boolean;
113
- }): {
114
- translateErrorCode: (code: string) => string;
115
- translateErrorCodes: (codes: string[]) => string[];
116
- translateError: (error: {
117
- code: string;
118
- message?: string;
119
- field?: string;
120
- }) => string;
121
- translateApiError: (apiResponse: any) => string;
16
+ error?: any;
17
+ source?: string;
18
+ };
19
+ type AuthEvent = {
20
+ type: AuthEventType;
21
+ details?: AuthEventDetails;
22
+ timestamp: number;
122
23
  };
24
+ type AuthEventListener = (event: AuthEvent) => void;
25
+ declare class AuthEventBus {
26
+ private static instance;
27
+ private listeners;
28
+ private isHandlingAuthError;
29
+ private lastErrorTime;
30
+ private lastEventType;
31
+ private readonly DEBOUNCE_TIME;
32
+ private constructor();
33
+ static getInstance(): AuthEventBus;
34
+ /**
35
+ * Emitir evento de error de autenticación
36
+ * Con debounce para evitar múltiples disparos
37
+ */
38
+ emit(type: AuthEventType, details?: AuthEventDetails): void;
39
+ /**
40
+ * Suscribirse a eventos de autenticación
41
+ * @returns Función de cleanup para desuscribirse
42
+ */
43
+ subscribe(listener: AuthEventListener): () => void;
44
+ /**
45
+ * Limpiar todos los listeners
46
+ */
47
+ clear(): void;
48
+ /**
49
+ * Verificar si hay un evento siendo manejado
50
+ */
51
+ isHandling(): boolean;
52
+ }
53
+ declare const authEventBus: AuthEventBus;
123
54
 
124
- export { ERROR_CODES, ERROR_SEVERITY_MAP, type ErrorCode, type ErrorSeverity, type ErrorTranslationConfig, type ParsedError, createErrorTranslator, decodeJwtSafely, getCookie, getCurrentUserEmail, getErrorMessage, handleCrudifyError, isTokenExpired, parseApiError, parseJavaScriptError, parseTransactionError, secureLocalStorage, secureSessionStorage, translateError, translateErrorCode, translateErrorCodes };
55
+ export { type AuthEvent, type AuthEventDetails, type AuthEventType, authEventBus };
package/dist/utils.js CHANGED
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true});var _chunkNNY4A73Vjs = require('./chunk-NNY4A73V.js');var _chunkYIIUEOXCjs = require('./chunk-YIIUEOXC.js');var _chunk6EBMA4HZjs = require('./chunk-6EBMA4HZ.js');exports.ERROR_CODES = _chunkYIIUEOXCjs.a; exports.ERROR_SEVERITY_MAP = _chunkYIIUEOXCjs.b; exports.createErrorTranslator = _chunk6EBMA4HZjs.e; exports.decodeJwtSafely = _chunk6EBMA4HZjs.f; exports.getCookie = _chunk6EBMA4HZjs.a; exports.getCurrentUserEmail = _chunk6EBMA4HZjs.g; exports.getErrorMessage = _chunkYIIUEOXCjs.e; exports.handleCrudifyError = _chunkYIIUEOXCjs.g; exports.isTokenExpired = _chunk6EBMA4HZjs.h; exports.parseApiError = _chunkYIIUEOXCjs.c; exports.parseJavaScriptError = _chunkYIIUEOXCjs.f; exports.parseTransactionError = _chunkYIIUEOXCjs.d; exports.secureLocalStorage = _chunkNNY4A73Vjs.b; exports.secureSessionStorage = _chunkNNY4A73Vjs.a; exports.translateError = _chunk6EBMA4HZjs.d; exports.translateErrorCode = _chunk6EBMA4HZjs.b; exports.translateErrorCodes = _chunk6EBMA4HZjs.c;
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true});var _chunkNNY4A73Vjs = require('./chunk-NNY4A73V.js');var _chunkYIIUEOXCjs = require('./chunk-YIIUEOXC.js');var _chunkATAGEVFKjs = require('./chunk-ATAGEVFK.js');exports.ERROR_CODES = _chunkYIIUEOXCjs.a; exports.ERROR_SEVERITY_MAP = _chunkYIIUEOXCjs.b; exports.authEventBus = _chunkATAGEVFKjs.f; exports.createErrorTranslator = _chunkATAGEVFKjs.e; exports.decodeJwtSafely = _chunkATAGEVFKjs.g; exports.getCookie = _chunkATAGEVFKjs.a; exports.getCurrentUserEmail = _chunkATAGEVFKjs.h; exports.getErrorMessage = _chunkYIIUEOXCjs.e; exports.handleCrudifyError = _chunkYIIUEOXCjs.g; exports.isTokenExpired = _chunkATAGEVFKjs.i; exports.parseApiError = _chunkYIIUEOXCjs.c; exports.parseJavaScriptError = _chunkYIIUEOXCjs.f; exports.parseTransactionError = _chunkYIIUEOXCjs.d; exports.secureLocalStorage = _chunkNNY4A73Vjs.b; exports.secureSessionStorage = _chunkNNY4A73Vjs.a; exports.translateError = _chunkATAGEVFKjs.d; exports.translateErrorCode = _chunkATAGEVFKjs.b; exports.translateErrorCodes = _chunkATAGEVFKjs.c;
package/dist/utils.mjs CHANGED
@@ -1 +1 @@
1
- import{a as C,b as S}from"./chunk-T2CPA46I.mjs";import{a as p,b as i,c as l,d,e as f,f as m,g as x}from"./chunk-BJ6PIVZR.mjs";import{a as r,b as e,c as o,d as a,e as t,f as s,g as E,h as n}from"./chunk-YS3C7YG5.mjs";export{p as ERROR_CODES,i as ERROR_SEVERITY_MAP,t as createErrorTranslator,s as decodeJwtSafely,r as getCookie,E as getCurrentUserEmail,f as getErrorMessage,x as handleCrudifyError,n as isTokenExpired,l as parseApiError,m as parseJavaScriptError,d as parseTransactionError,S as secureLocalStorage,C as secureSessionStorage,a as translateError,e as translateErrorCode,o as translateErrorCodes};
1
+ import{a as C,b as S}from"./chunk-T2CPA46I.mjs";import{a as i,b as f,c as l,d as u,e as d,f as m,g as x}from"./chunk-BJ6PIVZR.mjs";import{a as r,b as e,c as o,d as t,e as a,f as E,g as s,h as n,i as p}from"./chunk-HMJY3MMZ.mjs";export{i as ERROR_CODES,f as ERROR_SEVERITY_MAP,E as authEventBus,a as createErrorTranslator,s as decodeJwtSafely,r as getCookie,n as getCurrentUserEmail,d as getErrorMessage,x as handleCrudifyError,p as isTokenExpired,l as parseApiError,m as parseJavaScriptError,u as parseTransactionError,S as secureLocalStorage,C as secureSessionStorage,t as translateError,e as translateErrorCode,o as translateErrorCodes};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nocios/crudify-ui",
3
- "version": "4.0.92",
3
+ "version": "4.0.96",
4
4
  "description": "Biblioteca de componentes UI para Crudify",
5
5
  "author": "Nocios",
6
6
  "license": "MIT",
@@ -36,7 +36,7 @@
36
36
  "prepublishOnly": "npm run build"
37
37
  },
38
38
  "dependencies": {
39
- "@nocios/crudify-browser": "^4.0.1",
39
+ "@nocios/crudify-browser": "^4.0.6",
40
40
  "crypto-js": "^4.2.0",
41
41
  "dompurify": "^3.2.7",
42
42
  "uuid": "^13.0.0"
@@ -1 +0,0 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }var m=e=>{let n=document.cookie.match(new RegExp("(^|;)\\s*"+e+"=([^;]+)"));return n?n[2]:null};var R=["errors.{category}.{code}","errors.{code}","login.{code}","error.{code}","messages.{code}","{code}"],T={INVALID_CREDENTIALS:"auth",UNAUTHORIZED:"auth",INVALID_API_KEY:"auth",USER_NOT_FOUND:"auth",USER_NOT_ACTIVE:"auth",NO_PERMISSION:"auth",SESSION_EXPIRED:"auth",ITEM_NOT_FOUND:"data",NOT_FOUND:"data",IN_USE:"data",DUPLICATE_ENTRY:"data",FIELD_ERROR:"validation",BAD_REQUEST:"validation",INVALID_EMAIL:"validation",INVALID_CODE:"validation",REQUIRED_FIELD:"validation",INTERNAL_SERVER_ERROR:"system",DATABASE_CONNECTION_ERROR:"system",INVALID_CONFIGURATION:"system",UNKNOWN_OPERATION:"system",TIMEOUT_ERROR:"system",NETWORK_ERROR:"system",TOO_MANY_REQUESTS:"rate_limit"},f={INVALID_CREDENTIALS:"Invalid username or password",UNAUTHORIZED:"You are not authorized to perform this action",SESSION_EXPIRED:"Your session has expired. Please log in again.",USER_NOT_FOUND:"User not found",ITEM_NOT_FOUND:"Item not found",FIELD_ERROR:"Invalid field value",INTERNAL_SERVER_ERROR:"An internal error occurred",NETWORK_ERROR:"Network connection error",TIMEOUT_ERROR:"Request timeout",UNKNOWN_OPERATION:"Unknown operation",INVALID_EMAIL:"Invalid email format",INVALID_CODE:"Invalid code",TOO_MANY_REQUESTS:"Too many requests, please try again later"};function l(e,n){let{translateFn:r,currentLanguage:t,enableDebug:a}=n;a&&console.log(`\u{1F50D} [ErrorTranslation] Translating error code: ${e} (lang: ${t||"unknown"})`);let i=e.toUpperCase(),d=T[i],c=R.map(o=>o.replace("{category}",d||"general").replace("{code}",i));a&&console.log("\u{1F511} [ErrorTranslation] Searching keys:",c);for(let o of c){let s=r(o);if(a&&console.log(`\u{1F50D} [ErrorTranslation] Checking key: "${o}" -> result: "${s}" (same as key: ${s===o})`),s&&s!==o)return a&&console.log(`\u2705 [ErrorTranslation] Found translation at key: ${o} = "${s}"`),s}let g=f[i];if(g)return a&&console.log(`\u{1F504} [ErrorTranslation] Using default message: "${g}"`),g;let u=i.replace(/_/g," ").toLowerCase().replace(/\b\w/g,o=>o.toUpperCase());return a&&console.log(`\u26A0\uFE0F [ErrorTranslation] No translation found, using friendly code: "${u}"`),u}function I(e,n){return e.map(r=>l(r,n))}function N(e,n){let{enableDebug:r}=n;r&&console.log("\u{1F50D} [ErrorTranslation] Translating error:",e);let t=l(e.code,n);return t!==e.code.toUpperCase()&&t!==e.code?(r&&console.log(`\u2705 [ErrorTranslation] Using hierarchical translation: "${t}"`),e.field?`${e.field}: ${t}`:t):e.message&&!e.message.includes("Error:")&&e.message.length>0&&e.message!==e.code?(r&&console.log(`\u{1F504} [ErrorTranslation] No hierarchical translation found, using API message: "${e.message}"`),e.message):(r&&console.log(`\u26A0\uFE0F [ErrorTranslation] Using final fallback: "${t}"`),e.field?`${e.field}: ${t}`:t)}function O(e,n={}){let r={translateFn:e,currentLanguage:n.currentLanguage,enableDebug:n.enableDebug||!1};return{translateErrorCode:t=>l(t,r),translateErrorCodes:t=>I(t,r),translateError:t=>N(t,r),translateApiError:t=>_optionalChain([t, 'optionalAccess', _ => _.data, 'optionalAccess', _2 => _2.response, 'optionalAccess', _3 => _3.status])?l(t.data.response.status,r):_optionalChain([t, 'optionalAccess', _4 => _4.status])?l(t.status,r):_optionalChain([t, 'optionalAccess', _5 => _5.code])?l(t.code,r):"Unknown error"}}var E=e=>{try{let n=e.split(".");if(n.length!==3)return console.warn("Invalid JWT format: token must have 3 parts"),null;let r=n[1],t=r+"=".repeat((4-r.length%4)%4);return JSON.parse(atob(t))}catch(n){return console.warn("Failed to decode JWT token:",n),null}},y= exports.g =()=>{try{let e=null;if(e=sessionStorage.getItem("authToken"),console.log("\u{1F50D} getCurrentUserEmail - authToken:",e?`${e.substring(0,20)}...`:null),e||(e=sessionStorage.getItem("token"),console.log("\u{1F50D} getCurrentUserEmail - token:",e?`${e.substring(0,20)}...`:null)),e||(e=localStorage.getItem("authToken")||localStorage.getItem("token"),console.log("\u{1F50D} getCurrentUserEmail - localStorage:",e?`${e.substring(0,20)}...`:null)),!e)return console.warn("\u{1F50D} getCurrentUserEmail - No token found in any storage"),null;let n=E(e);if(!n)return console.warn("\u{1F50D} getCurrentUserEmail - Failed to decode token"),null;let r=n.email||n["cognito:username"]||null;return console.log("\u{1F50D} getCurrentUserEmail - Extracted email:",r),r}catch(e){return console.warn("Failed to get current user email:",e),null}},A= exports.h =e=>{try{let n=E(e);if(!n||!n.exp)return!0;let r=Math.floor(Date.now()/1e3);return n.exp<r}catch (e2){return!0}};exports.a = m; exports.b = l; exports.c = I; exports.d = N; exports.e = O; exports.f = E; exports.g = y; exports.h = A;
@@ -1 +0,0 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }var _chunk6EBMA4HZjs = require('./chunk-6EBMA4HZ.js');var _cryptojs = require('crypto-js'); var _cryptojs2 = _interopRequireDefault(_cryptojs);var i=class i{static setStorageType(e){i.storageType=e}static generateEncryptionKey(){let e=[navigator.userAgent,navigator.language,navigator.platform,screen.width,screen.height,Date.now().toString(),Math.random().toString(36)].join("|");return _cryptojs2.default.SHA256(e).toString()}static getEncryptionKey(){if(i.encryptionKey)return i.encryptionKey;let e=window.localStorage;if(!e)return i.encryptionKey=i.generateEncryptionKey(),i.encryptionKey;try{let t=e.getItem(i.ENCRYPTION_KEY_STORAGE);return(!t||t.length<32)&&(t=i.generateEncryptionKey(),e.setItem(i.ENCRYPTION_KEY_STORAGE,t)),i.encryptionKey=t,t}catch (e2){return console.warn("Crudify: Cannot persist encryption key, using temporary key"),i.encryptionKey=i.generateEncryptionKey(),i.encryptionKey}}static isStorageAvailable(e){try{let t=window[e],r="__storage_test__";return t.setItem(r,"test"),t.removeItem(r),!0}catch (e3){return!1}}static getStorage(){return i.storageType==="none"?null:i.isStorageAvailable(i.storageType)?window[i.storageType]:(console.warn(`Crudify: ${i.storageType} not available, tokens won't persist`),null)}static encrypt(e){try{let t=i.getEncryptionKey();return _cryptojs2.default.AES.encrypt(e,t).toString()}catch(t){return console.error("Crudify: Encryption failed",t),e}}static decrypt(e){try{let t=i.getEncryptionKey();return _cryptojs2.default.AES.decrypt(e,t).toString(_cryptojs2.default.enc.Utf8)||e}catch(t){return console.error("Crudify: Decryption failed",t),e}}static saveTokens(e){let t=i.getStorage();if(t)try{let r={accessToken:e.accessToken,refreshToken:e.refreshToken,expiresAt:e.expiresAt,refreshExpiresAt:e.refreshExpiresAt,savedAt:Date.now()},s=i.encrypt(JSON.stringify(r));t.setItem(i.TOKEN_KEY,s),console.debug("Crudify: Tokens saved successfully")}catch(r){console.error("Crudify: Failed to save tokens",r)}}static getTokens(){let e=i.getStorage();if(!e)return null;try{let t=e.getItem(i.TOKEN_KEY);if(!t)return null;let r=i.decrypt(t),s=JSON.parse(r);return!s.accessToken||!s.refreshToken||!s.expiresAt||!s.refreshExpiresAt?(console.warn("Crudify: Incomplete token data found, clearing storage"),i.clearTokens(),null):Date.now()>=s.refreshExpiresAt?(console.info("Crudify: Refresh token expired, clearing storage"),i.clearTokens(),null):{accessToken:s.accessToken,refreshToken:s.refreshToken,expiresAt:s.expiresAt,refreshExpiresAt:s.refreshExpiresAt}}catch(t){return console.error("Crudify: Failed to retrieve tokens",t),i.clearTokens(),null}}static clearTokens(){let e=i.getStorage();if(e)try{e.removeItem(i.TOKEN_KEY),console.debug("Crudify: Tokens cleared from storage")}catch(t){console.error("Crudify: Failed to clear tokens",t)}}static rotateEncryptionKey(){try{i.clearTokens(),i.encryptionKey=null;let e=window.localStorage;e&&e.removeItem(i.ENCRYPTION_KEY_STORAGE),console.info("Crudify: Encryption key rotated successfully")}catch(e){console.error("Crudify: Failed to rotate encryption key",e)}}static hasValidTokens(){return i.getTokens()!==null}static getExpirationInfo(){let e=i.getTokens();if(!e)return null;let t=Date.now();return{accessExpired:t>=e.expiresAt,refreshExpired:t>=e.refreshExpiresAt,accessExpiresIn:Math.max(0,e.expiresAt-t),refreshExpiresIn:Math.max(0,e.refreshExpiresAt-t)}}static updateAccessToken(e,t){let r=i.getTokens();if(!r){console.warn("Crudify: Cannot update access token, no existing tokens found");return}i.saveTokens({...r,accessToken:e,expiresAt:t})}};i.TOKEN_KEY="crudify_tokens",i.ENCRYPTION_KEY_STORAGE="crudify_enc_key",i.encryptionKey=null,i.storageType="localStorage";var g=i;var _crudifybrowser = require('@nocios/crudify-browser'); var _crudifybrowser2 = _interopRequireDefault(_crudifybrowser);var L=class n{constructor(){this.config={};this.initialized=!1}static getInstance(){return n.instance||(n.instance=new n),n.instance}async initialize(e={}){if(this.initialized){console.warn("SessionManager: Already initialized");return}this.config={storageType:"localStorage",autoRestore:!0,enableLogging:!1,...e},g.setStorageType(this.config.storageType||"localStorage"),this.config.enableLogging,this.config.autoRestore&&await this.restoreSession(),this.initialized=!0,this.log("SessionManager initialized successfully")}async login(e,t){try{this.log("Attempting login...");let r=await _crudifybrowser2.default.login(e,t);if(!r.success)return this.log("Login failed:",r.errors),{success:!1,error:this.formatError(r.errors),rawResponse:r};let s={accessToken:r.data.token,refreshToken:r.data.refreshToken,expiresAt:r.data.expiresAt,refreshExpiresAt:r.data.refreshExpiresAt};return g.saveTokens(s),this.log("Login successful, tokens saved"),_optionalChain([this, 'access', _2 => _2.config, 'access', _3 => _3.onLoginSuccess, 'optionalCall', _4 => _4(s)]),{success:!0,tokens:s,data:r.data}}catch(r){return this.log("Login error:",r),{success:!1,error:r instanceof Error?r.message:"Unknown error"}}}async logout(){try{this.log("Logging out..."),await _crudifybrowser2.default.logout(),g.clearTokens(),this.log("Logout successful"),_optionalChain([this, 'access', _5 => _5.config, 'access', _6 => _6.onLogout, 'optionalCall', _7 => _7()])}catch(e){this.log("Logout error:",e),g.clearTokens()}}async restoreSession(){try{this.log("Attempting to restore session...");let e=g.getTokens();if(!e)return this.log("No valid tokens found in storage"),!1;if(Date.now()>=e.refreshExpiresAt)return this.log("Refresh token expired, clearing storage"),g.clearTokens(),!1;if(_crudifybrowser2.default.setTokens({accessToken:e.accessToken,refreshToken:e.refreshToken,expiresAt:e.expiresAt,refreshExpiresAt:e.refreshExpiresAt}),_crudifybrowser2.default.getTokenData().isValid===!1){if(this.log("Restored access token is invalid or expired"),Date.now()<e.refreshExpiresAt&&(this.log("Access token expired but refresh is valid, attempting refresh..."),await this.refreshTokens())){this.log("Session restored successfully via token refresh");let s=g.getTokens();return s&&_optionalChain([this, 'access', _8 => _8.config, 'access', _9 => _9.onSessionRestored, 'optionalCall', _10 => _10(s)]),!0}return g.clearTokens(),await _crudifybrowser2.default.logout(),!1}return this.log("Session restored successfully"),_optionalChain([this, 'access', _11 => _11.config, 'access', _12 => _12.onSessionRestored, 'optionalCall', _13 => _13(e)]),!0}catch(e){return this.log("Session restore error:",e),g.clearTokens(),await _crudifybrowser2.default.logout(),!1}}isAuthenticated(){return _crudifybrowser2.default.isLogin()||g.hasValidTokens()}getTokenInfo(){let e=_crudifybrowser2.default.getTokenData(),t=g.getExpirationInfo();return{isLoggedIn:this.isAuthenticated(),crudifyTokens:e,storageInfo:t,hasValidTokens:g.hasValidTokens()}}async refreshTokens(){try{this.log("Manually refreshing tokens...");let e=await _crudifybrowser2.default.refreshAccessToken();if(!e.success)return this.log("Token refresh failed:",e.errors),g.clearTokens(),_optionalChain([this, 'access', _14 => _14.config, 'access', _15 => _15.showNotification, 'optionalCall', _16 => _16(this.getSessionExpiredMessage(),"warning")]),_optionalChain([this, 'access', _17 => _17.config, 'access', _18 => _18.onSessionExpired, 'optionalCall', _19 => _19()]),!1;let t={accessToken:e.data.token,refreshToken:e.data.refreshToken,expiresAt:e.data.expiresAt,refreshExpiresAt:e.data.refreshExpiresAt};return g.saveTokens(t),this.log("Tokens refreshed and saved successfully"),!0}catch(e){return this.log("Token refresh error:",e),g.clearTokens(),_optionalChain([this, 'access', _20 => _20.config, 'access', _21 => _21.showNotification, 'optionalCall', _22 => _22(this.getSessionExpiredMessage(),"warning")]),_optionalChain([this, 'access', _23 => _23.config, 'access', _24 => _24.onSessionExpired, 'optionalCall', _25 => _25()]),!1}}setupResponseInterceptor(){_crudifybrowser2.default.setResponseInterceptor(async e=>{let t=this.detectAuthorizationError(e);if(t.isAuthError){if(console.warn("\u{1F6A8} SessionManager - Authorization error detected:",{errorType:t.errorType,errorDetails:t.errorDetails,fullResponse:e}),t.isRefreshTokenInvalid||t.isTokenRefreshFailed)return this.log("Refresh token invalid or refresh already failed, clearing session"),g.clearTokens(),_optionalChain([this, 'access', _26 => _26.config, 'access', _27 => _27.showNotification, 'optionalCall', _28 => _28(this.getSessionExpiredMessage(),"warning")]),_optionalChain([this, 'access', _29 => _29.config, 'access', _30 => _30.onSessionExpired, 'optionalCall', _31 => _31()]),e;g.hasValidTokens()&&!t.isIrrecoverable?(this.log("Auth error detected, attempting token refresh..."),await this.refreshTokens()||(this.log("Token refresh failed, triggering session expired"),_optionalChain([this, 'access', _32 => _32.config, 'access', _33 => _33.onSessionExpired, 'optionalCall', _34 => _34()]))):(this.log("Auth error with no valid tokens or irrecoverable error, triggering session expired"),g.clearTokens(),_optionalChain([this, 'access', _35 => _35.config, 'access', _36 => _36.showNotification, 'optionalCall', _37 => _37(this.getSessionExpiredMessage(),"warning")]),_optionalChain([this, 'access', _38 => _38.config, 'access', _39 => _39.onSessionExpired, 'optionalCall', _40 => _40()]))}return e}),this.log("Response interceptor configured")}detectAuthorizationError(e){let t={isAuthError:!1,isRefreshTokenInvalid:!1,isTokenRefreshFailed:!1,isIrrecoverable:!1,errorType:"",errorDetails:null};if(e.errors){if(Array.isArray(e.errors))e.errors.some(s=>s.errorType==="Unauthorized"||_optionalChain([s, 'access', _41 => _41.message, 'optionalAccess', _42 => _42.includes, 'call', _43 => _43("Unauthorized")])||_optionalChain([s, 'access', _44 => _44.message, 'optionalAccess', _45 => _45.includes, 'call', _46 => _46("Not Authorized")])||_optionalChain([s, 'access', _47 => _47.message, 'optionalAccess', _48 => _48.includes, 'call', _49 => _49("Token")])||_optionalChain([s, 'access', _50 => _50.extensions, 'optionalAccess', _51 => _51.code])==="UNAUTHENTICATED"||_optionalChain([s, 'access', _52 => _52.message, 'optionalAccess', _53 => _53.includes, 'call', _54 => _54("NOT_AUTHORIZED")]))&&(t.isAuthError=!0,t.errorType="GraphQL Array Format",t.errorDetails=e.errors);else if(typeof e.errors=="object"){let r=Object.values(e.errors).flat();r.some(l=>typeof l=="string"&&(l.includes("NOT_AUTHORIZED")||l.includes("TOKEN_REFRESH_FAILED")||l.includes("PLEASE_LOGIN")||l.includes("Unauthorized")||l.includes("UNAUTHENTICATED")||l.includes("Token")))&&(t.isAuthError=!0,t.errorType="GraphQL Object Format",t.errorDetails=e.errors,t.isTokenRefreshFailed=r.some(l=>typeof l=="string"&&l.includes("TOKEN_REFRESH_FAILED")))}}if(!t.isAuthError&&_optionalChain([e, 'access', _55 => _55.data, 'optionalAccess', _56 => _56.response, 'optionalAccess', _57 => _57.status])==="UNAUTHORIZED"&&(t.isAuthError=!0,t.errorType="Status UNAUTHORIZED",t.errorDetails=e.data.response,t.isIrrecoverable=!0),!t.isAuthError&&_optionalChain([e, 'access', _58 => _58.data, 'optionalAccess', _59 => _59.response, 'optionalAccess', _60 => _60.data]))try{let r=JSON.parse(e.data.response.data);(r.error==="REFRESH_TOKEN_INVALID"||r.error==="TOKEN_EXPIRED")&&(t.isAuthError=!0,t.errorType="Parsed Data Format",t.errorDetails=r,t.isRefreshTokenInvalid=!0,t.isIrrecoverable=!0)}catch (e4){}if(!t.isAuthError&&e.errorCode){let r=e.errorCode;(r==="UNAUTHORIZED"||r==="UNAUTHENTICATED"||r==="TOKEN_EXPIRED")&&(t.isAuthError=!0,t.errorType="Error Code Format",t.errorDetails={errorCode:r})}return t}clearSession(){g.clearTokens(),_crudifybrowser2.default.logout(),this.log("Session cleared completely")}getSessionExpiredMessage(){return this.config.translateFn?_chunk6EBMA4HZjs.b.call(void 0, "SESSION_EXPIRED",{translateFn:this.config.translateFn,enableDebug:this.config.enableLogging}):"Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente."}log(e,...t){this.config.enableLogging&&console.log(`[SessionManager] ${e}`,...t)}formatError(e){return e?typeof e=="string"?e:typeof e=="object"?Object.values(e).flat().join(", "):"Authentication failed":"Unknown error"}};var _react = require('react'); var _react2 = _interopRequireDefault(_react);function V(n={}){let[e,t]=_react.useState.call(void 0, {isAuthenticated:!1,isLoading:!0,isInitialized:!1,tokens:null,error:null}),r=L.getInstance(),s=_react.useCallback.call(void 0, async()=>{try{t(a=>({...a,isLoading:!0,error:null}));let c={autoRestore:_nullishCoalesce(n.autoRestore, () => (!0)),enableLogging:_nullishCoalesce(n.enableLogging, () => (!1)),showNotification:n.showNotification,translateFn:n.translateFn,onSessionExpired:()=>{t(a=>({...a,isAuthenticated:!1,tokens:null,error:"Session expired"})),_optionalChain([n, 'access', _61 => _61.onSessionExpired, 'optionalCall', _62 => _62()])},onSessionRestored:a=>{t(d=>({...d,isAuthenticated:!0,tokens:a,error:null})),_optionalChain([n, 'access', _63 => _63.onSessionRestored, 'optionalCall', _64 => _64(a)])},onLoginSuccess:a=>{t(d=>({...d,isAuthenticated:!0,tokens:a,error:null}))},onLogout:()=>{t(a=>({...a,isAuthenticated:!1,tokens:null,error:null}))}};await r.initialize(c),r.setupResponseInterceptor();let f=r.isAuthenticated(),o=r.getTokenInfo();t(a=>({...a,isAuthenticated:f,isInitialized:!0,isLoading:!1,tokens:o.crudifyTokens.accessToken?{accessToken:o.crudifyTokens.accessToken,refreshToken:o.crudifyTokens.refreshToken,expiresAt:o.crudifyTokens.expiresAt,refreshExpiresAt:o.crudifyTokens.refreshExpiresAt}:null}))}catch(c){let f=c instanceof Error?c.message:"Initialization failed";t(o=>({...o,isLoading:!1,isInitialized:!0,error:f}))}},[n.autoRestore,n.enableLogging,n.onSessionExpired,n.onSessionRestored]),l=_react.useCallback.call(void 0, async(c,f)=>{t(o=>({...o,isLoading:!0,error:null}));try{let o=await r.login(c,f);return o.success&&o.tokens?t(a=>({...a,isAuthenticated:!0,tokens:o.tokens,isLoading:!1,error:null})):t(a=>({...a,isAuthenticated:!1,tokens:null,isLoading:!1,error:null})),o}catch(o){let a=o instanceof Error?o.message:"Login failed",d=a.includes("INVALID_CREDENTIALS")||a.includes("Invalid email")||a.includes("Invalid password")||a.includes("credentials");return t(k=>({...k,isAuthenticated:!1,tokens:null,isLoading:!1,error:d?null:a})),{success:!1,error:a}}},[r]),v=_react.useCallback.call(void 0, async()=>{t(c=>({...c,isLoading:!0}));try{await r.logout(),t(c=>({...c,isAuthenticated:!1,tokens:null,isLoading:!1,error:null}))}catch(c){t(f=>({...f,isAuthenticated:!1,tokens:null,isLoading:!1,error:c instanceof Error?c.message:"Logout error"}))}},[r]),p=_react.useCallback.call(void 0, async()=>{try{let c=await r.refreshTokens();if(c){let f=r.getTokenInfo();t(o=>({...o,tokens:f.crudifyTokens.accessToken?{accessToken:f.crudifyTokens.accessToken,refreshToken:f.crudifyTokens.refreshToken,expiresAt:f.crudifyTokens.expiresAt,refreshExpiresAt:f.crudifyTokens.refreshExpiresAt}:null,error:null}))}else t(f=>({...f,isAuthenticated:!1,tokens:null,error:"Token refresh failed"}));return c}catch(c){return t(f=>({...f,isAuthenticated:!1,tokens:null,error:c instanceof Error?c.message:"Token refresh failed"})),!1}},[r]),x=_react.useCallback.call(void 0, ()=>{t(c=>({...c,error:null}))},[]),y=_react.useCallback.call(void 0, ()=>r.getTokenInfo(),[r]);return _react.useEffect.call(void 0, ()=>{s()},[s]),{...e,login:l,logout:v,refreshTokens:p,clearError:x,getTokenInfo:y,isExpiringSoon:e.tokens?e.tokens.expiresAt-Date.now()<300*1e3:!1,expiresIn:e.tokens?Math.max(0,e.tokens.expiresAt-Date.now()):0,refreshExpiresIn:e.tokens?Math.max(0,e.tokens.refreshExpiresAt-Date.now()):0}}var _material = require('@mui/material');var _uuid = require('uuid');var _dompurify = require('dompurify'); var _dompurify2 = _interopRequireDefault(_dompurify);var _jsxruntime = require('react/jsx-runtime');var W=_react.createContext.call(void 0, null),ue=n=>_dompurify2.default.sanitize(n,{ALLOWED_TAGS:["b","i","em","strong","br","span"],ALLOWED_ATTR:["class"],FORBID_TAGS:["script","iframe","object","embed"],FORBID_ATTR:["onload","onerror","onclick","onmouseover","onfocus","onblur"],WHOLE_DOCUMENT:!1,RETURN_DOM:!1,RETURN_DOM_FRAGMENT:!1,RETURN_TRUSTED_TYPE:!1}),B= exports.d =({children:n,maxNotifications:e=5,defaultAutoHideDuration:t=6e3,position:r={vertical:"top",horizontal:"right"},enabled:s=!1,allowHtml:l=!1})=>{let[v,p]=_react.useState.call(void 0, []),x=_react.useCallback.call(void 0, (o,a="info",d)=>{if(!s)return"";if(!o||typeof o!="string")return console.warn("\u26A0\uFE0F GlobalNotificationProvider: Invalid message provided"),"";o.length>1e3&&(console.warn("\u26A0\uFE0F GlobalNotificationProvider: Message too long, truncating"),o=o.substring(0,1e3)+"...");let k=_uuid.v4.call(void 0, ),b={id:k,message:o,severity:a,autoHideDuration:_nullishCoalesce(_optionalChain([d, 'optionalAccess', _65 => _65.autoHideDuration]), () => (t)),persistent:_nullishCoalesce(_optionalChain([d, 'optionalAccess', _66 => _66.persistent]), () => (!1)),allowHtml:_nullishCoalesce(_optionalChain([d, 'optionalAccess', _67 => _67.allowHtml]), () => (l))};return p(T=>[...T.length>=e?T.slice(-(e-1)):T,b]),k},[e,t,s,l]),y=_react.useCallback.call(void 0, o=>{p(a=>a.filter(d=>d.id!==o))},[]),c=_react.useCallback.call(void 0, ()=>{p([])},[]),f={showNotification:x,hideNotification:y,clearAllNotifications:c};return _jsxruntime.jsxs.call(void 0, W.Provider,{value:f,children:[n,s&&_jsxruntime.jsx.call(void 0, _material.Portal,{children:_jsxruntime.jsx.call(void 0, _material.Box,{sx:{position:"fixed",zIndex:9999,[r.vertical]:(r.vertical==="top",24),[r.horizontal]:r.horizontal==="right"||r.horizontal==="left"?24:"50%",...r.horizontal==="center"&&{transform:"translateX(-50%)"},display:"flex",flexDirection:r.vertical==="top"?"column":"column-reverse",gap:1,maxWidth:"400px",width:"auto"},children:v.map(o=>_jsxruntime.jsx.call(void 0, fe,{notification:o,onClose:()=>y(o.id)},o.id))})})]})},fe=({notification:n,onClose:e})=>{let[t,r]=_react.useState.call(void 0, !0),s=_react.useCallback.call(void 0, (l,v)=>{v!=="clickaway"&&(r(!1),setTimeout(e,300))},[e]);return _react.useEffect.call(void 0, ()=>{if(!n.persistent&&n.autoHideDuration){let l=setTimeout(()=>{s()},n.autoHideDuration);return()=>clearTimeout(l)}},[n.autoHideDuration,n.persistent,s]),_jsxruntime.jsx.call(void 0, _material.Snackbar,{open:t,onClose:s,sx:{position:"relative","& .MuiSnackbarContent-root":{minWidth:"auto"}},TransitionProps:{enter:!0,exit:!0},children:_jsxruntime.jsx.call(void 0, _material.Alert,{variant:"filled",severity:n.severity,onClose:s,sx:{width:"100%",minWidth:"280px",maxWidth:"400px",wordBreak:"break-word"},children:n.allowHtml?_jsxruntime.jsx.call(void 0, "span",{dangerouslySetInnerHTML:{__html:ue(n.message)}}):_jsxruntime.jsx.call(void 0, "span",{children:n.message})})})},J= exports.e =()=>{let n=_react.useContext.call(void 0, W);if(!n)throw new Error("useGlobalNotification debe ser usado dentro de un GlobalNotificationProvider");return n};var X=_react.createContext.call(void 0, void 0);function ye({children:n,options:e={},config:t,showNotifications:r=!1,notificationOptions:s={}}){let l;try{let{showNotification:o}=J();l=o}catch (e5){}let v=_react2.default.useMemo(()=>({...e,showNotification:l,onSessionExpired:()=>{_optionalChain([e, 'access', _68 => _68.onSessionExpired, 'optionalCall', _69 => _69()])}}),[e,l]),p=V(v),x=_react.useMemo.call(void 0, ()=>{let o,a,d,k,b,T="unknown";if(_optionalChain([t, 'optionalAccess', _70 => _70.publicApiKey])&&(o=t.publicApiKey,T="props"),_optionalChain([t, 'optionalAccess', _71 => _71.env])&&(a=t.env),_optionalChain([t, 'optionalAccess', _72 => _72.appName])&&(d=t.appName),_optionalChain([t, 'optionalAccess', _73 => _73.loginActions])&&(k=t.loginActions),_optionalChain([t, 'optionalAccess', _74 => _74.logo])&&(b=t.logo),!o){let R=_chunk6EBMA4HZjs.a.call(void 0, "publicApiKey"),S=_chunk6EBMA4HZjs.a.call(void 0, "environment"),I=_chunk6EBMA4HZjs.a.call(void 0, "appName"),A=_chunk6EBMA4HZjs.a.call(void 0, "loginActions"),u=_chunk6EBMA4HZjs.a.call(void 0, "logo");R&&(o=R,T="cookies"),S&&["dev","stg","prod"].includes(S)&&(a=S),I&&(d=decodeURIComponent(I)),A&&(k=decodeURIComponent(A).split(",").map(C=>C.trim()).filter(Boolean)),u&&(b=decodeURIComponent(u))}return{publicApiKey:o,env:a,appName:d,loginActions:k,logo:b}},[t]),y=_react.useMemo.call(void 0, ()=>{if(!_optionalChain([p, 'access', _75 => _75.tokens, 'optionalAccess', _76 => _76.accessToken])||!p.isAuthenticated)return null;try{let o=_chunk6EBMA4HZjs.f.call(void 0, p.tokens.accessToken);if(o&&o.sub&&o.email&&o.subscriber){let a={_id:o.sub,email:o.email,subscriberKey:o.subscriber};return Object.keys(o).forEach(d=>{["sub","email","subscriber"].includes(d)||(a[d]=o[d])}),a}}catch(o){console.error("Error decoding JWT token for sessionData:",o)}return null},[_optionalChain([p, 'access', _77 => _77.tokens, 'optionalAccess', _78 => _78.accessToken]),p.isAuthenticated]),c={...p,sessionData:y,config:x},f={enabled:r,maxNotifications:s.maxNotifications||5,defaultAutoHideDuration:s.defaultAutoHideDuration||6e3,position:s.position||{vertical:"top",horizontal:"right"}};return _jsxruntime.jsx.call(void 0, X.Provider,{value:c,children:n})}function Be(n){let e={enabled:n.showNotifications,maxNotifications:_optionalChain([n, 'access', _79 => _79.notificationOptions, 'optionalAccess', _80 => _80.maxNotifications])||5,defaultAutoHideDuration:_optionalChain([n, 'access', _81 => _81.notificationOptions, 'optionalAccess', _82 => _82.defaultAutoHideDuration])||6e3,position:_optionalChain([n, 'access', _83 => _83.notificationOptions, 'optionalAccess', _84 => _84.position])||{vertical:"top",horizontal:"right"},allowHtml:_optionalChain([n, 'access', _85 => _85.notificationOptions, 'optionalAccess', _86 => _86.allowHtml])||!1};return _jsxruntime.jsx.call(void 0, B,{...e,children:_jsxruntime.jsx.call(void 0, ye,{...n})})}function $(){let n=_react.useContext.call(void 0, X);if(n===void 0)throw new Error("useSessionContext must be used within a SessionProvider");return n}function Je({children:n,fallback:e=_jsxruntime.jsx.call(void 0, "div",{children:"Please log in to access this content"}),redirectTo:t}){let{isAuthenticated:r,isLoading:s,isInitialized:l}=$();return!l||s?_jsxruntime.jsx.call(void 0, "div",{children:"Loading..."}):r?_jsxruntime.jsx.call(void 0, _jsxruntime.Fragment,{children:n}):t?(t(),null):_jsxruntime.jsx.call(void 0, _jsxruntime.Fragment,{children:e})}function Ze(){let n=$();return n.isInitialized?_jsxruntime.jsxs.call(void 0, "div",{style:{padding:"10px",margin:"10px",border:"1px solid #ccc",borderRadius:"4px",fontSize:"12px",fontFamily:"monospace"},children:[_jsxruntime.jsx.call(void 0, "h4",{children:"Session Debug Info"}),_jsxruntime.jsxs.call(void 0, "div",{children:[_jsxruntime.jsx.call(void 0, "strong",{children:"Authenticated:"})," ",n.isAuthenticated?"Yes":"No"]}),_jsxruntime.jsxs.call(void 0, "div",{children:[_jsxruntime.jsx.call(void 0, "strong",{children:"Loading:"})," ",n.isLoading?"Yes":"No"]}),_jsxruntime.jsxs.call(void 0, "div",{children:[_jsxruntime.jsx.call(void 0, "strong",{children:"Error:"})," ",n.error||"None"]}),n.tokens&&_jsxruntime.jsxs.call(void 0, _jsxruntime.Fragment,{children:[_jsxruntime.jsxs.call(void 0, "div",{children:[_jsxruntime.jsx.call(void 0, "strong",{children:"Access Token:"})," ",n.tokens.accessToken.substring(0,20),"..."]}),_jsxruntime.jsxs.call(void 0, "div",{children:[_jsxruntime.jsx.call(void 0, "strong",{children:"Refresh Token:"})," ",n.tokens.refreshToken.substring(0,20),"..."]}),_jsxruntime.jsxs.call(void 0, "div",{children:[_jsxruntime.jsx.call(void 0, "strong",{children:"Access Expires In:"})," ",Math.round(n.expiresIn/1e3/60)," minutes"]}),_jsxruntime.jsxs.call(void 0, "div",{children:[_jsxruntime.jsx.call(void 0, "strong",{children:"Refresh Expires In:"})," ",Math.round(n.refreshExpiresIn/1e3/60/60)," hours"]}),_jsxruntime.jsxs.call(void 0, "div",{children:[_jsxruntime.jsx.call(void 0, "strong",{children:"Expiring Soon:"})," ",n.isExpiringSoon?"Yes":"No"]})]})]}):_jsxruntime.jsx.call(void 0, "div",{children:"Session not initialized"})}var et=(n={})=>{let{autoFetch:e=!0,retryOnError:t=!1,maxRetries:r=3}=n,[s,l]=_react.useState.call(void 0, null),[v,p]=_react.useState.call(void 0, !1),[x,y]=_react.useState.call(void 0, null),[c,f]=_react.useState.call(void 0, {}),o=_react.useRef.call(void 0, null),a=_react.useRef.call(void 0, !0),d=_react.useRef.call(void 0, 0),k=_react.useRef.call(void 0, 0),b=_react.useCallback.call(void 0, ()=>{l(null),y(null),p(!1),f({})},[]),T=_react.useCallback.call(void 0, async()=>{let R=_chunk6EBMA4HZjs.g.call(void 0, );if(!R){a.current&&(y("No user email available"),p(!1));return}o.current&&o.current.abort();let S=new AbortController;o.current=S;let I=++d.current;try{a.current&&(p(!0),y(null));let A=await _crudifybrowser2.default.readItems("users",{filter:{email:R},pagination:{limit:1}});if(I===d.current&&a.current&&!S.signal.aborted)if(A.success&&A.data&&A.data.length>0){let u=A.data[0];l(u);let z={fullProfile:u,totalFields:Object.keys(u).length,displayData:{id:u.id,email:u.email,username:u.username,firstName:u.firstName,lastName:u.lastName,fullName:u.fullName||`${u.firstName||""} ${u.lastName||""}`.trim(),role:u.role,permissions:u.permissions||[],isActive:u.isActive,lastLogin:u.lastLogin,createdAt:u.createdAt,updatedAt:u.updatedAt,...Object.keys(u).filter(C=>!["id","email","username","firstName","lastName","fullName","role","permissions","isActive","lastLogin","createdAt","updatedAt"].includes(C)).reduce((C,F)=>({...C,[F]:u[F]}),{})}};f(z),y(null),k.current=0}else y("User profile not found"),l(null),f({})}catch(A){if(I===d.current&&a.current){let u=A;if(u.name==="AbortError")return;t&&k.current<r&&(_optionalChain([u, 'access', _87 => _87.message, 'optionalAccess', _88 => _88.includes, 'call', _89 => _89("Network Error")])||_optionalChain([u, 'access', _90 => _90.message, 'optionalAccess', _91 => _91.includes, 'call', _92 => _92("Failed to fetch")]))?(k.current++,setTimeout(()=>{a.current&&T()},1e3*k.current)):(y("Failed to load user profile"),l(null),f({}))}}finally{I===d.current&&a.current&&p(!1),o.current===S&&(o.current=null)}},[t,r]);return _react.useEffect.call(void 0, ()=>{e&&T()},[e,T]),_react.useEffect.call(void 0, ()=>(a.current=!0,()=>{a.current=!1,o.current&&(o.current.abort(),o.current=null)}),[]),{userProfile:s,loading:v,error:x,extendedData:c,refreshProfile:T,clearProfile:b}};exports.a = g; exports.b = L; exports.c = V; exports.d = B; exports.e = J; exports.f = Be; exports.g = $; exports.h = Je; exports.i = Ze; exports.j = et;
@@ -1 +0,0 @@
1
- import{a as w,b as M,f as G,g as Y}from"./chunk-YS3C7YG5.mjs";import P from"crypto-js";var i=class i{static setStorageType(e){i.storageType=e}static generateEncryptionKey(){let e=[navigator.userAgent,navigator.language,navigator.platform,screen.width,screen.height,Date.now().toString(),Math.random().toString(36)].join("|");return P.SHA256(e).toString()}static getEncryptionKey(){if(i.encryptionKey)return i.encryptionKey;let e=window.localStorage;if(!e)return i.encryptionKey=i.generateEncryptionKey(),i.encryptionKey;try{let t=e.getItem(i.ENCRYPTION_KEY_STORAGE);return(!t||t.length<32)&&(t=i.generateEncryptionKey(),e.setItem(i.ENCRYPTION_KEY_STORAGE,t)),i.encryptionKey=t,t}catch{return console.warn("Crudify: Cannot persist encryption key, using temporary key"),i.encryptionKey=i.generateEncryptionKey(),i.encryptionKey}}static isStorageAvailable(e){try{let t=window[e],r="__storage_test__";return t.setItem(r,"test"),t.removeItem(r),!0}catch{return!1}}static getStorage(){return i.storageType==="none"?null:i.isStorageAvailable(i.storageType)?window[i.storageType]:(console.warn(`Crudify: ${i.storageType} not available, tokens won't persist`),null)}static encrypt(e){try{let t=i.getEncryptionKey();return P.AES.encrypt(e,t).toString()}catch(t){return console.error("Crudify: Encryption failed",t),e}}static decrypt(e){try{let t=i.getEncryptionKey();return P.AES.decrypt(e,t).toString(P.enc.Utf8)||e}catch(t){return console.error("Crudify: Decryption failed",t),e}}static saveTokens(e){let t=i.getStorage();if(t)try{let r={accessToken:e.accessToken,refreshToken:e.refreshToken,expiresAt:e.expiresAt,refreshExpiresAt:e.refreshExpiresAt,savedAt:Date.now()},s=i.encrypt(JSON.stringify(r));t.setItem(i.TOKEN_KEY,s),console.debug("Crudify: Tokens saved successfully")}catch(r){console.error("Crudify: Failed to save tokens",r)}}static getTokens(){let e=i.getStorage();if(!e)return null;try{let t=e.getItem(i.TOKEN_KEY);if(!t)return null;let r=i.decrypt(t),s=JSON.parse(r);return!s.accessToken||!s.refreshToken||!s.expiresAt||!s.refreshExpiresAt?(console.warn("Crudify: Incomplete token data found, clearing storage"),i.clearTokens(),null):Date.now()>=s.refreshExpiresAt?(console.info("Crudify: Refresh token expired, clearing storage"),i.clearTokens(),null):{accessToken:s.accessToken,refreshToken:s.refreshToken,expiresAt:s.expiresAt,refreshExpiresAt:s.refreshExpiresAt}}catch(t){return console.error("Crudify: Failed to retrieve tokens",t),i.clearTokens(),null}}static clearTokens(){let e=i.getStorage();if(e)try{e.removeItem(i.TOKEN_KEY),console.debug("Crudify: Tokens cleared from storage")}catch(t){console.error("Crudify: Failed to clear tokens",t)}}static rotateEncryptionKey(){try{i.clearTokens(),i.encryptionKey=null;let e=window.localStorage;e&&e.removeItem(i.ENCRYPTION_KEY_STORAGE),console.info("Crudify: Encryption key rotated successfully")}catch(e){console.error("Crudify: Failed to rotate encryption key",e)}}static hasValidTokens(){return i.getTokens()!==null}static getExpirationInfo(){let e=i.getTokens();if(!e)return null;let t=Date.now();return{accessExpired:t>=e.expiresAt,refreshExpired:t>=e.refreshExpiresAt,accessExpiresIn:Math.max(0,e.expiresAt-t),refreshExpiresIn:Math.max(0,e.refreshExpiresAt-t)}}static updateAccessToken(e,t){let r=i.getTokens();if(!r){console.warn("Crudify: Cannot update access token, no existing tokens found");return}i.saveTokens({...r,accessToken:e,expiresAt:t})}};i.TOKEN_KEY="crudify_tokens",i.ENCRYPTION_KEY_STORAGE="crudify_enc_key",i.encryptionKey=null,i.storageType="localStorage";var g=i;import m from"@nocios/crudify-browser";var L=class n{constructor(){this.config={};this.initialized=!1}static getInstance(){return n.instance||(n.instance=new n),n.instance}async initialize(e={}){if(this.initialized){console.warn("SessionManager: Already initialized");return}this.config={storageType:"localStorage",autoRestore:!0,enableLogging:!1,...e},g.setStorageType(this.config.storageType||"localStorage"),this.config.enableLogging,this.config.autoRestore&&await this.restoreSession(),this.initialized=!0,this.log("SessionManager initialized successfully")}async login(e,t){try{this.log("Attempting login...");let r=await m.login(e,t);if(!r.success)return this.log("Login failed:",r.errors),{success:!1,error:this.formatError(r.errors),rawResponse:r};let s={accessToken:r.data.token,refreshToken:r.data.refreshToken,expiresAt:r.data.expiresAt,refreshExpiresAt:r.data.refreshExpiresAt};return g.saveTokens(s),this.log("Login successful, tokens saved"),this.config.onLoginSuccess?.(s),{success:!0,tokens:s,data:r.data}}catch(r){return this.log("Login error:",r),{success:!1,error:r instanceof Error?r.message:"Unknown error"}}}async logout(){try{this.log("Logging out..."),await m.logout(),g.clearTokens(),this.log("Logout successful"),this.config.onLogout?.()}catch(e){this.log("Logout error:",e),g.clearTokens()}}async restoreSession(){try{this.log("Attempting to restore session...");let e=g.getTokens();if(!e)return this.log("No valid tokens found in storage"),!1;if(Date.now()>=e.refreshExpiresAt)return this.log("Refresh token expired, clearing storage"),g.clearTokens(),!1;if(m.setTokens({accessToken:e.accessToken,refreshToken:e.refreshToken,expiresAt:e.expiresAt,refreshExpiresAt:e.refreshExpiresAt}),m.getTokenData().isValid===!1){if(this.log("Restored access token is invalid or expired"),Date.now()<e.refreshExpiresAt&&(this.log("Access token expired but refresh is valid, attempting refresh..."),await this.refreshTokens())){this.log("Session restored successfully via token refresh");let s=g.getTokens();return s&&this.config.onSessionRestored?.(s),!0}return g.clearTokens(),await m.logout(),!1}return this.log("Session restored successfully"),this.config.onSessionRestored?.(e),!0}catch(e){return this.log("Session restore error:",e),g.clearTokens(),await m.logout(),!1}}isAuthenticated(){return m.isLogin()||g.hasValidTokens()}getTokenInfo(){let e=m.getTokenData(),t=g.getExpirationInfo();return{isLoggedIn:this.isAuthenticated(),crudifyTokens:e,storageInfo:t,hasValidTokens:g.hasValidTokens()}}async refreshTokens(){try{this.log("Manually refreshing tokens...");let e=await m.refreshAccessToken();if(!e.success)return this.log("Token refresh failed:",e.errors),g.clearTokens(),this.config.showNotification?.(this.getSessionExpiredMessage(),"warning"),this.config.onSessionExpired?.(),!1;let t={accessToken:e.data.token,refreshToken:e.data.refreshToken,expiresAt:e.data.expiresAt,refreshExpiresAt:e.data.refreshExpiresAt};return g.saveTokens(t),this.log("Tokens refreshed and saved successfully"),!0}catch(e){return this.log("Token refresh error:",e),g.clearTokens(),this.config.showNotification?.(this.getSessionExpiredMessage(),"warning"),this.config.onSessionExpired?.(),!1}}setupResponseInterceptor(){m.setResponseInterceptor(async e=>{let t=this.detectAuthorizationError(e);if(t.isAuthError){if(console.warn("\u{1F6A8} SessionManager - Authorization error detected:",{errorType:t.errorType,errorDetails:t.errorDetails,fullResponse:e}),t.isRefreshTokenInvalid||t.isTokenRefreshFailed)return this.log("Refresh token invalid or refresh already failed, clearing session"),g.clearTokens(),this.config.showNotification?.(this.getSessionExpiredMessage(),"warning"),this.config.onSessionExpired?.(),e;g.hasValidTokens()&&!t.isIrrecoverable?(this.log("Auth error detected, attempting token refresh..."),await this.refreshTokens()||(this.log("Token refresh failed, triggering session expired"),this.config.onSessionExpired?.())):(this.log("Auth error with no valid tokens or irrecoverable error, triggering session expired"),g.clearTokens(),this.config.showNotification?.(this.getSessionExpiredMessage(),"warning"),this.config.onSessionExpired?.())}return e}),this.log("Response interceptor configured")}detectAuthorizationError(e){let t={isAuthError:!1,isRefreshTokenInvalid:!1,isTokenRefreshFailed:!1,isIrrecoverable:!1,errorType:"",errorDetails:null};if(e.errors){if(Array.isArray(e.errors))e.errors.some(s=>s.errorType==="Unauthorized"||s.message?.includes("Unauthorized")||s.message?.includes("Not Authorized")||s.message?.includes("Token")||s.extensions?.code==="UNAUTHENTICATED"||s.message?.includes("NOT_AUTHORIZED"))&&(t.isAuthError=!0,t.errorType="GraphQL Array Format",t.errorDetails=e.errors);else if(typeof e.errors=="object"){let r=Object.values(e.errors).flat();r.some(l=>typeof l=="string"&&(l.includes("NOT_AUTHORIZED")||l.includes("TOKEN_REFRESH_FAILED")||l.includes("PLEASE_LOGIN")||l.includes("Unauthorized")||l.includes("UNAUTHENTICATED")||l.includes("Token")))&&(t.isAuthError=!0,t.errorType="GraphQL Object Format",t.errorDetails=e.errors,t.isTokenRefreshFailed=r.some(l=>typeof l=="string"&&l.includes("TOKEN_REFRESH_FAILED")))}}if(!t.isAuthError&&e.data?.response?.status==="UNAUTHORIZED"&&(t.isAuthError=!0,t.errorType="Status UNAUTHORIZED",t.errorDetails=e.data.response,t.isIrrecoverable=!0),!t.isAuthError&&e.data?.response?.data)try{let r=JSON.parse(e.data.response.data);(r.error==="REFRESH_TOKEN_INVALID"||r.error==="TOKEN_EXPIRED")&&(t.isAuthError=!0,t.errorType="Parsed Data Format",t.errorDetails=r,t.isRefreshTokenInvalid=!0,t.isIrrecoverable=!0)}catch{}if(!t.isAuthError&&e.errorCode){let r=e.errorCode;(r==="UNAUTHORIZED"||r==="UNAUTHENTICATED"||r==="TOKEN_EXPIRED")&&(t.isAuthError=!0,t.errorType="Error Code Format",t.errorDetails={errorCode:r})}return t}clearSession(){g.clearTokens(),m.logout(),this.log("Session cleared completely")}getSessionExpiredMessage(){return this.config.translateFn?M("SESSION_EXPIRED",{translateFn:this.config.translateFn,enableDebug:this.config.enableLogging}):"Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente."}log(e,...t){this.config.enableLogging&&console.log(`[SessionManager] ${e}`,...t)}formatError(e){return e?typeof e=="string"?e:typeof e=="object"?Object.values(e).flat().join(", "):"Authentication failed":"Unknown error"}};import{useState as _,useEffect as ee,useCallback as D}from"react";function V(n={}){let[e,t]=_({isAuthenticated:!1,isLoading:!0,isInitialized:!1,tokens:null,error:null}),r=L.getInstance(),s=D(async()=>{try{t(a=>({...a,isLoading:!0,error:null}));let c={autoRestore:n.autoRestore??!0,enableLogging:n.enableLogging??!1,showNotification:n.showNotification,translateFn:n.translateFn,onSessionExpired:()=>{t(a=>({...a,isAuthenticated:!1,tokens:null,error:"Session expired"})),n.onSessionExpired?.()},onSessionRestored:a=>{t(d=>({...d,isAuthenticated:!0,tokens:a,error:null})),n.onSessionRestored?.(a)},onLoginSuccess:a=>{t(d=>({...d,isAuthenticated:!0,tokens:a,error:null}))},onLogout:()=>{t(a=>({...a,isAuthenticated:!1,tokens:null,error:null}))}};await r.initialize(c),r.setupResponseInterceptor();let f=r.isAuthenticated(),o=r.getTokenInfo();t(a=>({...a,isAuthenticated:f,isInitialized:!0,isLoading:!1,tokens:o.crudifyTokens.accessToken?{accessToken:o.crudifyTokens.accessToken,refreshToken:o.crudifyTokens.refreshToken,expiresAt:o.crudifyTokens.expiresAt,refreshExpiresAt:o.crudifyTokens.refreshExpiresAt}:null}))}catch(c){let f=c instanceof Error?c.message:"Initialization failed";t(o=>({...o,isLoading:!1,isInitialized:!0,error:f}))}},[n.autoRestore,n.enableLogging,n.onSessionExpired,n.onSessionRestored]),l=D(async(c,f)=>{t(o=>({...o,isLoading:!0,error:null}));try{let o=await r.login(c,f);return o.success&&o.tokens?t(a=>({...a,isAuthenticated:!0,tokens:o.tokens,isLoading:!1,error:null})):t(a=>({...a,isAuthenticated:!1,tokens:null,isLoading:!1,error:null})),o}catch(o){let a=o instanceof Error?o.message:"Login failed",d=a.includes("INVALID_CREDENTIALS")||a.includes("Invalid email")||a.includes("Invalid password")||a.includes("credentials");return t(k=>({...k,isAuthenticated:!1,tokens:null,isLoading:!1,error:d?null:a})),{success:!1,error:a}}},[r]),v=D(async()=>{t(c=>({...c,isLoading:!0}));try{await r.logout(),t(c=>({...c,isAuthenticated:!1,tokens:null,isLoading:!1,error:null}))}catch(c){t(f=>({...f,isAuthenticated:!1,tokens:null,isLoading:!1,error:c instanceof Error?c.message:"Logout error"}))}},[r]),p=D(async()=>{try{let c=await r.refreshTokens();if(c){let f=r.getTokenInfo();t(o=>({...o,tokens:f.crudifyTokens.accessToken?{accessToken:f.crudifyTokens.accessToken,refreshToken:f.crudifyTokens.refreshToken,expiresAt:f.crudifyTokens.expiresAt,refreshExpiresAt:f.crudifyTokens.refreshExpiresAt}:null,error:null}))}else t(f=>({...f,isAuthenticated:!1,tokens:null,error:"Token refresh failed"}));return c}catch(c){return t(f=>({...f,isAuthenticated:!1,tokens:null,error:c instanceof Error?c.message:"Token refresh failed"})),!1}},[r]),x=D(()=>{t(c=>({...c,error:null}))},[]),y=D(()=>r.getTokenInfo(),[r]);return ee(()=>{s()},[s]),{...e,login:l,logout:v,refreshTokens:p,clearError:x,getTokenInfo:y,isExpiringSoon:e.tokens?e.tokens.expiresAt-Date.now()<300*1e3:!1,expiresIn:e.tokens?Math.max(0,e.tokens.expiresAt-Date.now()):0,refreshExpiresIn:e.tokens?Math.max(0,e.tokens.refreshExpiresAt-Date.now()):0}}import{useState as j,createContext as te,useContext as re,useCallback as O,useEffect as oe}from"react";import{Snackbar as ne,Alert as se,Box as ie,Portal as ae}from"@mui/material";import{v4 as le}from"uuid";import ce from"dompurify";import{jsx as N,jsxs as de}from"react/jsx-runtime";var W=te(null),ue=n=>ce.sanitize(n,{ALLOWED_TAGS:["b","i","em","strong","br","span"],ALLOWED_ATTR:["class"],FORBID_TAGS:["script","iframe","object","embed"],FORBID_ATTR:["onload","onerror","onclick","onmouseover","onfocus","onblur"],WHOLE_DOCUMENT:!1,RETURN_DOM:!1,RETURN_DOM_FRAGMENT:!1,RETURN_TRUSTED_TYPE:!1}),B=({children:n,maxNotifications:e=5,defaultAutoHideDuration:t=6e3,position:r={vertical:"top",horizontal:"right"},enabled:s=!1,allowHtml:l=!1})=>{let[v,p]=j([]),x=O((o,a="info",d)=>{if(!s)return"";if(!o||typeof o!="string")return console.warn("\u26A0\uFE0F GlobalNotificationProvider: Invalid message provided"),"";o.length>1e3&&(console.warn("\u26A0\uFE0F GlobalNotificationProvider: Message too long, truncating"),o=o.substring(0,1e3)+"...");let k=le(),b={id:k,message:o,severity:a,autoHideDuration:d?.autoHideDuration??t,persistent:d?.persistent??!1,allowHtml:d?.allowHtml??l};return p(T=>[...T.length>=e?T.slice(-(e-1)):T,b]),k},[e,t,s,l]),y=O(o=>{p(a=>a.filter(d=>d.id!==o))},[]),c=O(()=>{p([])},[]),f={showNotification:x,hideNotification:y,clearAllNotifications:c};return de(W.Provider,{value:f,children:[n,s&&N(ae,{children:N(ie,{sx:{position:"fixed",zIndex:9999,[r.vertical]:(r.vertical==="top",24),[r.horizontal]:r.horizontal==="right"||r.horizontal==="left"?24:"50%",...r.horizontal==="center"&&{transform:"translateX(-50%)"},display:"flex",flexDirection:r.vertical==="top"?"column":"column-reverse",gap:1,maxWidth:"400px",width:"auto"},children:v.map(o=>N(fe,{notification:o,onClose:()=>y(o.id)},o.id))})})]})},fe=({notification:n,onClose:e})=>{let[t,r]=j(!0),s=O((l,v)=>{v!=="clickaway"&&(r(!1),setTimeout(e,300))},[e]);return oe(()=>{if(!n.persistent&&n.autoHideDuration){let l=setTimeout(()=>{s()},n.autoHideDuration);return()=>clearTimeout(l)}},[n.autoHideDuration,n.persistent,s]),N(ne,{open:t,onClose:s,sx:{position:"relative","& .MuiSnackbarContent-root":{minWidth:"auto"}},TransitionProps:{enter:!0,exit:!0},children:N(se,{variant:"filled",severity:n.severity,onClose:s,sx:{width:"100%",minWidth:"280px",maxWidth:"400px",wordBreak:"break-word"},children:n.allowHtml?N("span",{dangerouslySetInnerHTML:{__html:ue(n.message)}}):N("span",{children:n.message})})})},J=()=>{let n=re(W);if(!n)throw new Error("useGlobalNotification debe ser usado dentro de un GlobalNotificationProvider");return n};import ge,{createContext as pe,useContext as he,useMemo as Z}from"react";import{Fragment as H,jsx as h,jsxs as E}from"react/jsx-runtime";var X=pe(void 0);function ye({children:n,options:e={},config:t,showNotifications:r=!1,notificationOptions:s={}}){let l;try{let{showNotification:o}=J();l=o}catch{}let v=ge.useMemo(()=>({...e,showNotification:l,onSessionExpired:()=>{e.onSessionExpired?.()}}),[e,l]),p=V(v),x=Z(()=>{let o,a,d,k,b,T="unknown";if(t?.publicApiKey&&(o=t.publicApiKey,T="props"),t?.env&&(a=t.env),t?.appName&&(d=t.appName),t?.loginActions&&(k=t.loginActions),t?.logo&&(b=t.logo),!o){let R=w("publicApiKey"),S=w("environment"),I=w("appName"),A=w("loginActions"),u=w("logo");R&&(o=R,T="cookies"),S&&["dev","stg","prod"].includes(S)&&(a=S),I&&(d=decodeURIComponent(I)),A&&(k=decodeURIComponent(A).split(",").map(C=>C.trim()).filter(Boolean)),u&&(b=decodeURIComponent(u))}return{publicApiKey:o,env:a,appName:d,loginActions:k,logo:b}},[t]),y=Z(()=>{if(!p.tokens?.accessToken||!p.isAuthenticated)return null;try{let o=G(p.tokens.accessToken);if(o&&o.sub&&o.email&&o.subscriber){let a={_id:o.sub,email:o.email,subscriberKey:o.subscriber};return Object.keys(o).forEach(d=>{["sub","email","subscriber"].includes(d)||(a[d]=o[d])}),a}}catch(o){console.error("Error decoding JWT token for sessionData:",o)}return null},[p.tokens?.accessToken,p.isAuthenticated]),c={...p,sessionData:y,config:x},f={enabled:r,maxNotifications:s.maxNotifications||5,defaultAutoHideDuration:s.defaultAutoHideDuration||6e3,position:s.position||{vertical:"top",horizontal:"right"}};return h(X.Provider,{value:c,children:n})}function Be(n){let e={enabled:n.showNotifications,maxNotifications:n.notificationOptions?.maxNotifications||5,defaultAutoHideDuration:n.notificationOptions?.defaultAutoHideDuration||6e3,position:n.notificationOptions?.position||{vertical:"top",horizontal:"right"},allowHtml:n.notificationOptions?.allowHtml||!1};return h(B,{...e,children:h(ye,{...n})})}function $(){let n=he(X);if(n===void 0)throw new Error("useSessionContext must be used within a SessionProvider");return n}function Je({children:n,fallback:e=h("div",{children:"Please log in to access this content"}),redirectTo:t}){let{isAuthenticated:r,isLoading:s,isInitialized:l}=$();return!l||s?h("div",{children:"Loading..."}):r?h(H,{children:n}):t?(t(),null):h(H,{children:e})}function Ze(){let n=$();return n.isInitialized?E("div",{style:{padding:"10px",margin:"10px",border:"1px solid #ccc",borderRadius:"4px",fontSize:"12px",fontFamily:"monospace"},children:[h("h4",{children:"Session Debug Info"}),E("div",{children:[h("strong",{children:"Authenticated:"})," ",n.isAuthenticated?"Yes":"No"]}),E("div",{children:[h("strong",{children:"Loading:"})," ",n.isLoading?"Yes":"No"]}),E("div",{children:[h("strong",{children:"Error:"})," ",n.error||"None"]}),n.tokens&&E(H,{children:[E("div",{children:[h("strong",{children:"Access Token:"})," ",n.tokens.accessToken.substring(0,20),"..."]}),E("div",{children:[h("strong",{children:"Refresh Token:"})," ",n.tokens.refreshToken.substring(0,20),"..."]}),E("div",{children:[h("strong",{children:"Access Expires In:"})," ",Math.round(n.expiresIn/1e3/60)," minutes"]}),E("div",{children:[h("strong",{children:"Refresh Expires In:"})," ",Math.round(n.refreshExpiresIn/1e3/60/60)," hours"]}),E("div",{children:[h("strong",{children:"Expiring Soon:"})," ",n.isExpiringSoon?"Yes":"No"]})]})]}):h("div",{children:"Session not initialized"})}import{useState as U,useEffect as q,useCallback as Q,useRef as K}from"react";import ke from"@nocios/crudify-browser";var et=(n={})=>{let{autoFetch:e=!0,retryOnError:t=!1,maxRetries:r=3}=n,[s,l]=U(null),[v,p]=U(!1),[x,y]=U(null),[c,f]=U({}),o=K(null),a=K(!0),d=K(0),k=K(0),b=Q(()=>{l(null),y(null),p(!1),f({})},[]),T=Q(async()=>{let R=Y();if(!R){a.current&&(y("No user email available"),p(!1));return}o.current&&o.current.abort();let S=new AbortController;o.current=S;let I=++d.current;try{a.current&&(p(!0),y(null));let A=await ke.readItems("users",{filter:{email:R},pagination:{limit:1}});if(I===d.current&&a.current&&!S.signal.aborted)if(A.success&&A.data&&A.data.length>0){let u=A.data[0];l(u);let z={fullProfile:u,totalFields:Object.keys(u).length,displayData:{id:u.id,email:u.email,username:u.username,firstName:u.firstName,lastName:u.lastName,fullName:u.fullName||`${u.firstName||""} ${u.lastName||""}`.trim(),role:u.role,permissions:u.permissions||[],isActive:u.isActive,lastLogin:u.lastLogin,createdAt:u.createdAt,updatedAt:u.updatedAt,...Object.keys(u).filter(C=>!["id","email","username","firstName","lastName","fullName","role","permissions","isActive","lastLogin","createdAt","updatedAt"].includes(C)).reduce((C,F)=>({...C,[F]:u[F]}),{})}};f(z),y(null),k.current=0}else y("User profile not found"),l(null),f({})}catch(A){if(I===d.current&&a.current){let u=A;if(u.name==="AbortError")return;t&&k.current<r&&(u.message?.includes("Network Error")||u.message?.includes("Failed to fetch"))?(k.current++,setTimeout(()=>{a.current&&T()},1e3*k.current)):(y("Failed to load user profile"),l(null),f({}))}}finally{I===d.current&&a.current&&p(!1),o.current===S&&(o.current=null)}},[t,r]);return q(()=>{e&&T()},[e,T]),q(()=>(a.current=!0,()=>{a.current=!1,o.current&&(o.current.abort(),o.current=null)}),[]),{userProfile:s,loading:v,error:x,extendedData:c,refreshProfile:T,clearProfile:b}};export{g as a,L as b,V as c,B as d,J as e,Be as f,$ as g,Je as h,Ze as i,et as j};
@@ -1 +0,0 @@
1
- var m=e=>{let n=document.cookie.match(new RegExp("(^|;)\\s*"+e+"=([^;]+)"));return n?n[2]:null};var R=["errors.{category}.{code}","errors.{code}","login.{code}","error.{code}","messages.{code}","{code}"],T={INVALID_CREDENTIALS:"auth",UNAUTHORIZED:"auth",INVALID_API_KEY:"auth",USER_NOT_FOUND:"auth",USER_NOT_ACTIVE:"auth",NO_PERMISSION:"auth",SESSION_EXPIRED:"auth",ITEM_NOT_FOUND:"data",NOT_FOUND:"data",IN_USE:"data",DUPLICATE_ENTRY:"data",FIELD_ERROR:"validation",BAD_REQUEST:"validation",INVALID_EMAIL:"validation",INVALID_CODE:"validation",REQUIRED_FIELD:"validation",INTERNAL_SERVER_ERROR:"system",DATABASE_CONNECTION_ERROR:"system",INVALID_CONFIGURATION:"system",UNKNOWN_OPERATION:"system",TIMEOUT_ERROR:"system",NETWORK_ERROR:"system",TOO_MANY_REQUESTS:"rate_limit"},f={INVALID_CREDENTIALS:"Invalid username or password",UNAUTHORIZED:"You are not authorized to perform this action",SESSION_EXPIRED:"Your session has expired. Please log in again.",USER_NOT_FOUND:"User not found",ITEM_NOT_FOUND:"Item not found",FIELD_ERROR:"Invalid field value",INTERNAL_SERVER_ERROR:"An internal error occurred",NETWORK_ERROR:"Network connection error",TIMEOUT_ERROR:"Request timeout",UNKNOWN_OPERATION:"Unknown operation",INVALID_EMAIL:"Invalid email format",INVALID_CODE:"Invalid code",TOO_MANY_REQUESTS:"Too many requests, please try again later"};function l(e,n){let{translateFn:r,currentLanguage:t,enableDebug:a}=n;a&&console.log(`\u{1F50D} [ErrorTranslation] Translating error code: ${e} (lang: ${t||"unknown"})`);let i=e.toUpperCase(),d=T[i],c=R.map(o=>o.replace("{category}",d||"general").replace("{code}",i));a&&console.log("\u{1F511} [ErrorTranslation] Searching keys:",c);for(let o of c){let s=r(o);if(a&&console.log(`\u{1F50D} [ErrorTranslation] Checking key: "${o}" -> result: "${s}" (same as key: ${s===o})`),s&&s!==o)return a&&console.log(`\u2705 [ErrorTranslation] Found translation at key: ${o} = "${s}"`),s}let g=f[i];if(g)return a&&console.log(`\u{1F504} [ErrorTranslation] Using default message: "${g}"`),g;let u=i.replace(/_/g," ").toLowerCase().replace(/\b\w/g,o=>o.toUpperCase());return a&&console.log(`\u26A0\uFE0F [ErrorTranslation] No translation found, using friendly code: "${u}"`),u}function I(e,n){return e.map(r=>l(r,n))}function N(e,n){let{enableDebug:r}=n;r&&console.log("\u{1F50D} [ErrorTranslation] Translating error:",e);let t=l(e.code,n);return t!==e.code.toUpperCase()&&t!==e.code?(r&&console.log(`\u2705 [ErrorTranslation] Using hierarchical translation: "${t}"`),e.field?`${e.field}: ${t}`:t):e.message&&!e.message.includes("Error:")&&e.message.length>0&&e.message!==e.code?(r&&console.log(`\u{1F504} [ErrorTranslation] No hierarchical translation found, using API message: "${e.message}"`),e.message):(r&&console.log(`\u26A0\uFE0F [ErrorTranslation] Using final fallback: "${t}"`),e.field?`${e.field}: ${t}`:t)}function O(e,n={}){let r={translateFn:e,currentLanguage:n.currentLanguage,enableDebug:n.enableDebug||!1};return{translateErrorCode:t=>l(t,r),translateErrorCodes:t=>I(t,r),translateError:t=>N(t,r),translateApiError:t=>t?.data?.response?.status?l(t.data.response.status,r):t?.status?l(t.status,r):t?.code?l(t.code,r):"Unknown error"}}var E=e=>{try{let n=e.split(".");if(n.length!==3)return console.warn("Invalid JWT format: token must have 3 parts"),null;let r=n[1],t=r+"=".repeat((4-r.length%4)%4);return JSON.parse(atob(t))}catch(n){return console.warn("Failed to decode JWT token:",n),null}},y=()=>{try{let e=null;if(e=sessionStorage.getItem("authToken"),console.log("\u{1F50D} getCurrentUserEmail - authToken:",e?`${e.substring(0,20)}...`:null),e||(e=sessionStorage.getItem("token"),console.log("\u{1F50D} getCurrentUserEmail - token:",e?`${e.substring(0,20)}...`:null)),e||(e=localStorage.getItem("authToken")||localStorage.getItem("token"),console.log("\u{1F50D} getCurrentUserEmail - localStorage:",e?`${e.substring(0,20)}...`:null)),!e)return console.warn("\u{1F50D} getCurrentUserEmail - No token found in any storage"),null;let n=E(e);if(!n)return console.warn("\u{1F50D} getCurrentUserEmail - Failed to decode token"),null;let r=n.email||n["cognito:username"]||null;return console.log("\u{1F50D} getCurrentUserEmail - Extracted email:",r),r}catch(e){return console.warn("Failed to get current user email:",e),null}},A=e=>{try{let n=E(e);if(!n||!n.exp)return!0;let r=Math.floor(Date.now()/1e3);return n.exp<r}catch{return!0}};export{m as a,l as b,I as c,N as d,O as e,E as f,y as g,A as h};