@nocios/crudify-ui 4.1.44 → 4.1.48

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.
@@ -1 +0,0 @@
1
- import{a as P,b as V,f as v,g as X,h as Y,i as $}from"./chunk-5JKS55SE.mjs";import z from"crypto-js";var l=class l{static setStorageType(i){l.storageType=i}static generateEncryptionKey(){let i=[navigator.userAgent,navigator.language,navigator.platform,screen.width,screen.height,Date.now().toString(),Math.random().toString(36)].join("|");return z.SHA256(i).toString()}static getEncryptionKey(){if(l.encryptionKey)return l.encryptionKey;let i=window.localStorage;if(!i)return l.encryptionKey=l.generateEncryptionKey(),l.encryptionKey;try{let e=i.getItem(l.ENCRYPTION_KEY_STORAGE);return(!e||e.length<32)&&(e=l.generateEncryptionKey(),i.setItem(l.ENCRYPTION_KEY_STORAGE,e)),l.encryptionKey=e,e}catch{return console.warn("Crudify: Cannot persist encryption key, using temporary key"),l.encryptionKey=l.generateEncryptionKey(),l.encryptionKey}}static isStorageAvailable(i){try{let e=window[i],n="__storage_test__";return e.setItem(n,"test"),e.removeItem(n),!0}catch{return!1}}static getStorage(){return l.storageType==="none"?null:l.isStorageAvailable(l.storageType)?window[l.storageType]:(console.warn(`Crudify: ${l.storageType} not available, tokens won't persist`),null)}static encrypt(i){try{let e=l.getEncryptionKey();return z.AES.encrypt(i,e).toString()}catch(e){return console.error("Crudify: Encryption failed",e),i}}static decrypt(i){try{let e=l.getEncryptionKey();return z.AES.decrypt(i,e).toString(z.enc.Utf8)||i}catch(e){return console.error("Crudify: Decryption failed",e),i}}static saveTokens(i){let e=l.getStorage();if(e)try{let n={accessToken:i.accessToken,refreshToken:i.refreshToken,expiresAt:i.expiresAt,refreshExpiresAt:i.refreshExpiresAt,savedAt:Date.now()},r=l.encrypt(JSON.stringify(n));e.setItem(l.TOKEN_KEY,r),console.debug("Crudify: Tokens saved successfully")}catch(n){console.error("Crudify: Failed to save tokens",n)}}static getTokens(){let i=l.getStorage();if(!i)return null;try{let e=i.getItem(l.TOKEN_KEY);if(!e)return null;let n=l.decrypt(e),r=JSON.parse(n);return!r.accessToken||!r.refreshToken||!r.expiresAt||!r.refreshExpiresAt?(console.warn("Crudify: Incomplete token data found, clearing storage"),l.clearTokens(),null):Date.now()>=r.refreshExpiresAt?(console.info("Crudify: Refresh token expired, clearing storage"),l.clearTokens(),null):{accessToken:r.accessToken,refreshToken:r.refreshToken,expiresAt:r.expiresAt,refreshExpiresAt:r.refreshExpiresAt}}catch(e){return console.error("Crudify: Failed to retrieve tokens",e),l.clearTokens(),null}}static clearTokens(){let i=l.getStorage();if(i)try{i.removeItem(l.TOKEN_KEY),console.debug("Crudify: Tokens cleared from storage")}catch(e){console.error("Crudify: Failed to clear tokens",e)}}static rotateEncryptionKey(){try{l.clearTokens(),l.encryptionKey=null;let i=window.localStorage;i&&i.removeItem(l.ENCRYPTION_KEY_STORAGE),console.info("Crudify: Encryption key rotated successfully")}catch(i){console.error("Crudify: Failed to rotate encryption key",i)}}static hasValidTokens(){return l.getTokens()!==null}static getExpirationInfo(){let i=l.getTokens();if(!i)return null;let e=Date.now();return{accessExpired:e>=i.expiresAt,refreshExpired:e>=i.refreshExpiresAt,accessExpiresIn:Math.max(0,i.expiresAt-e),refreshExpiresIn:Math.max(0,i.refreshExpiresAt-e)}}static updateAccessToken(i,e){let n=l.getTokens();if(!n){console.warn("Crudify: Cannot update access token, no existing tokens found");return}l.saveTokens({...n,accessToken:i,expiresAt:e})}static subscribeToChanges(i){let e=n=>{if(n.key===l.TOKEN_KEY){if(n.newValue===null){console.debug("Crudify: Tokens removed in another tab"),i(null);return}if(n.newValue){console.debug("Crudify: Tokens updated in another tab");let r=l.getTokens();i(r)}}};return window.addEventListener("storage",e),()=>{window.removeEventListener("storage",e)}}};l.TOKEN_KEY="crudify_tokens",l.ENCRYPTION_KEY_STORAGE="crudify_enc_key",l.encryptionKey=null,l.storageType="localStorage";var f=l;import T from"@nocios/crudify-browser";var U=class o{constructor(){this.config={};this.initialized=!1;this.lastActivityTime=0;this.isRefreshingLocally=!1;this.refreshPromise=null}static getInstance(){return o.instance||(o.instance=new o),o.instance}async initialize(i={}){if(console.log("\u{1F535} [SessionManager] initialize() CALLED"),console.log("\u{1F50D} [SessionManager] Received config:",i),this.initialized){console.warn("SessionManager: Already initialized");return}if(this.config={storageType:"localStorage",autoRestore:!0,enableLogging:!1,...i},f.setStorageType(this.config.storageType||"localStorage"),this.config.enableLogging,T.setTokenInvalidationCallback(()=>{this.log("\u{1F514} Tokens invalidated by crudify-core"),v.emit("SESSION_EXPIRED",{message:"Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente.",source:"crudify-core.clearTokensAndRefreshState"})}),console.log("\u{1F50D} [SessionManager] config.apiEndpointAdmin:",this.config.apiEndpointAdmin),console.log("\u{1F50D} [SessionManager] config.apiKeyEndpointAdmin:",this.config.apiKeyEndpointAdmin),this.config.apiEndpointAdmin&&this.config.apiKeyEndpointAdmin){console.log("\u2705 [SessionManager] Admin credentials provided, storing...");let e=f.getTokens();e?(f.saveTokens({...e,apiEndpointAdmin:this.config.apiEndpointAdmin,apiKeyEndpointAdmin:this.config.apiKeyEndpointAdmin}),console.log("\u2705 [SessionManager] Admin API credentials stored from init (with existing tokens)")):(f.saveTokens({accessToken:"",refreshToken:"",expiresAt:0,refreshExpiresAt:0,apiEndpointAdmin:this.config.apiEndpointAdmin,apiKeyEndpointAdmin:this.config.apiKeyEndpointAdmin}),console.log("\u2705 [SessionManager] Admin API credentials stored (no tokens yet)"));let n=f.getTokens();console.log("\u{1F50D} [SessionManager] After saving, TokenStorage has:",{apiEndpointAdmin:n?.apiEndpointAdmin,apiKeyEndpointAdmin:n?.apiKeyEndpointAdmin})}else console.warn("\u26A0\uFE0F [SessionManager] Admin API credentials NOT provided to SessionManager.initialize()");this.config.autoRestore&&await this.restoreSession(),this.initialized=!0,console.log("\u2705 [SessionManager] Initialized successfully")}async login(i,e){try{console.log("\u{1F535} [SessionManager] login() CALLED");let n=await T.login(i,e);if(!n.success)return console.log("\u274C [SessionManager] Login failed:",n.errors),{success:!1,error:this.formatError(n.errors),rawResponse:n};let r=f.getTokens();console.log("\u{1F50D} [SessionManager] Login - existingTokens:",r),console.log("\u{1F50D} [SessionManager] Login - this.config.apiEndpointAdmin:",this.config.apiEndpointAdmin),console.log("\u{1F50D} [SessionManager] Login - this.config.apiKeyEndpointAdmin:",this.config.apiKeyEndpointAdmin);let d={accessToken:n.data.token,refreshToken:n.data.refreshToken,expiresAt:n.data.expiresAt,refreshExpiresAt:n.data.refreshExpiresAt,apiEndpointAdmin:r?.apiEndpointAdmin||this.config.apiEndpointAdmin,apiKeyEndpointAdmin:r?.apiKeyEndpointAdmin||this.config.apiKeyEndpointAdmin};console.log("\u{1F50D} [SessionManager] Login - tokens to save:",d),f.saveTokens(d);let p=f.getTokens();return console.log("\u{1F50D} [SessionManager] After login save, TokenStorage has:",{apiEndpointAdmin:p?.apiEndpointAdmin,apiKeyEndpointAdmin:p?.apiKeyEndpointAdmin}),this.lastActivityTime=Date.now(),console.log("\u2705 [SessionManager] Login successful, tokens saved"),this.config.onLoginSuccess?.(d),{success:!0,tokens:d,data:n.data}}catch(n){return console.error("\u274C [SessionManager] Login error:",n),{success:!1,error:n instanceof Error?n.message:"Unknown error"}}}async logout(){try{this.log("Logging out..."),await T.logout(),f.clearTokens(),this.log("Logout successful"),this.config.onLogout?.()}catch(i){this.log("Logout error:",i),f.clearTokens()}}async restoreSession(){try{this.log("Attempting to restore session...");let i=f.getTokens();if(!i)return this.log("No valid tokens found in storage"),!1;if(Date.now()>=i.refreshExpiresAt)return this.log("Refresh token expired, clearing storage"),f.clearTokens(),!1;if(T.setTokens({accessToken:i.accessToken,refreshToken:i.refreshToken,expiresAt:i.expiresAt,refreshExpiresAt:i.refreshExpiresAt}),T.getTokenData().isValid===!1){if(this.log("Restored access token is invalid or expired"),Date.now()<i.refreshExpiresAt&&(this.log("Access token expired but refresh is valid, attempting refresh..."),await this.refreshTokens())){this.log("Session restored successfully via token refresh");let r=f.getTokens();return r&&this.config.onSessionRestored?.(r),!0}return f.clearTokens(),await T.logout(),!1}return this.log("Session restored successfully"),this.lastActivityTime=Date.now(),this.config.onSessionRestored?.(i),!0}catch(i){return this.log("Session restore error:",i),f.clearTokens(),await T.logout(),!1}}isAuthenticated(){return T.isLogin()||f.hasValidTokens()}getTokenInfo(){let i=T.getTokenData(),e=f.getExpirationInfo(),n=f.getTokens();return{isLoggedIn:this.isAuthenticated(),crudifyTokens:i,storageInfo:e,hasValidTokens:f.hasValidTokens(),apiEndpointAdmin:n?.apiEndpointAdmin,apiKeyEndpointAdmin:n?.apiKeyEndpointAdmin}}async refreshTokens(){if(this.isRefreshingLocally&&this.refreshPromise)return this.log("Refresh already in progress, waiting for existing promise..."),this.refreshPromise;this.isRefreshingLocally=!0,this.refreshPromise=this._performRefresh();try{return await this.refreshPromise}finally{this.isRefreshingLocally=!1,this.refreshPromise=null}}async _performRefresh(){try{this.log("Starting token refresh...");let i=await T.refreshAccessToken();if(!i.success)return this.log("Token refresh failed:",i.errors),f.clearTokens(),this.config.showNotification?.(this.getSessionExpiredMessage(),"warning"),this.config.onSessionExpired?.(),!1;let e={accessToken:i.data.token,refreshToken:i.data.refreshToken,expiresAt:i.data.expiresAt,refreshExpiresAt:i.data.refreshExpiresAt};return f.saveTokens(e),this.log("Tokens refreshed and saved successfully"),this.lastActivityTime=Date.now(),!0}catch(i){return this.log("Token refresh error:",i),f.clearTokens(),this.config.showNotification?.(this.getSessionExpiredMessage(),"warning"),this.config.onSessionExpired?.(),!1}}isRefreshing(){return this.isRefreshingLocally}setupResponseInterceptor(){T.setResponseInterceptor(async i=>{this.updateLastActivity();let e=this.detectAuthorizationError(i);if(e.isAuthError){if(this.log("\u{1F6A8} Authorization error detected:",{errorType:e.errorType,shouldLogout:e.shouldTriggerLogout}),e.isRefreshTokenInvalid||e.isTokenRefreshFailed)return this.log("Refresh token invalid, emitting TOKEN_REFRESH_FAILED event"),v.emit("TOKEN_REFRESH_FAILED",{message:e.userFriendlyMessage,error:e.errorDetails,source:"SessionManager.setupResponseInterceptor"}),i;e.shouldTriggerLogout&&(f.hasValidTokens()&&!e.isIrrecoverable?(this.log("Access token expired, emitting TOKEN_EXPIRED event"),v.emit("TOKEN_EXPIRED",{message:"Access token expired, refresh needed",error:e.errorDetails,source:"SessionManager.setupResponseInterceptor"})):(this.log("No valid tokens or irrecoverable error, emitting SESSION_EXPIRED event"),v.emit("SESSION_EXPIRED",{message:e.userFriendlyMessage,error:e.errorDetails,source:"SessionManager.setupResponseInterceptor"})))}return i}),this.log("Response interceptor configured (non-blocking mode)")}detectAuthorizationError(i){let e={isAuthError:!1,isRefreshTokenInvalid:!1,isTokenRefreshFailed:!1,isTokenExpired:!1,isUnauthorized:!1,isIrrecoverable:!1,shouldTriggerLogout:!1,errorType:"",errorDetails:null,userFriendlyMessage:""};if(i.errors&&Array.isArray(i.errors)){let n=i.errors.find(r=>r.errorType==="Unauthorized"||r.message?.includes("Unauthorized")||r.message?.includes("Not Authorized")||r.message?.includes("NOT_AUTHORIZED")||r.message?.includes("Token")||r.message?.includes("TOKEN")||r.message?.includes("Authentication")||r.message?.includes("UNAUTHENTICATED")||r.extensions?.code==="UNAUTHENTICATED"||r.extensions?.code==="FORBIDDEN");n&&(e.isAuthError=!0,e.errorType="GraphQL Array",e.errorDetails=n,e.shouldTriggerLogout=!0,e.userFriendlyMessage="Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente.",(n.message?.includes("TOKEN")||n.message?.includes("Token"))&&(e.isTokenExpired=!0),n.extensions?.code==="UNAUTHENTICATED"&&(e.isUnauthorized=!0))}if(!e.isAuthError&&i.errors&&typeof i.errors=="object"&&!Array.isArray(i.errors)){let r=Object.values(i.errors).flat().find(d=>typeof d=="string"&&(d.includes("NOT_AUTHORIZED")||d.includes("TOKEN_REFRESH_FAILED")||d.includes("TOKEN_HAS_EXPIRED")||d.includes("PLEASE_LOGIN")||d.includes("Unauthorized")||d.includes("UNAUTHENTICATED")||d.includes("SESSION_EXPIRED")||d.includes("INVALID_TOKEN")));r&&typeof r=="string"&&(e.isAuthError=!0,e.errorType="GraphQL Object",e.errorDetails=i.errors,e.shouldTriggerLogout=!0,r.includes("TOKEN_REFRESH_FAILED")?(e.isTokenRefreshFailed=!0,e.isRefreshTokenInvalid=!0,e.isIrrecoverable=!0,e.userFriendlyMessage="Tu sesi\xF3n ha caducado. Por favor, inicia sesi\xF3n nuevamente."):r.includes("TOKEN_HAS_EXPIRED")||r.includes("SESSION_EXPIRED")?(e.isTokenExpired=!0,e.userFriendlyMessage="Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente."):r.includes("INVALID_TOKEN")?(e.isTokenExpired=!0,e.isIrrecoverable=!0,e.userFriendlyMessage="Token inv\xE1lido. Por favor, inicia sesi\xF3n nuevamente."):e.userFriendlyMessage="Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente.")}if(!e.isAuthError&&i.data?.response?.status){let n=i.data.response.status.toUpperCase();(n==="UNAUTHORIZED"||n==="UNAUTHENTICATED")&&(e.isAuthError=!0,e.errorType="Status",e.errorDetails=i.data.response,e.isUnauthorized=!0,e.shouldTriggerLogout=!0,e.isIrrecoverable=!0,e.userFriendlyMessage="Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente.")}if(!e.isAuthError&&i.data?.response?.data)try{let n=typeof i.data.response.data=="string"?JSON.parse(i.data.response.data):i.data.response.data;(n.error==="REFRESH_TOKEN_INVALID"||n.error==="TOKEN_EXPIRED"||n.error==="INVALID_TOKEN")&&(e.isAuthError=!0,e.errorType="Parsed Data",e.errorDetails=n,e.shouldTriggerLogout=!0,e.isIrrecoverable=!0,n.error==="REFRESH_TOKEN_INVALID"?(e.isRefreshTokenInvalid=!0,e.isTokenRefreshFailed=!0,e.userFriendlyMessage="Tu sesi\xF3n ha caducado. Por favor, inicia sesi\xF3n nuevamente."):(e.isTokenExpired=!0,e.userFriendlyMessage="Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente."))}catch{}if(!e.isAuthError&&i.errorCode){let n=i.errorCode.toUpperCase();(n==="UNAUTHORIZED"||n==="UNAUTHENTICATED"||n==="TOKEN_EXPIRED"||n==="INVALID_TOKEN")&&(e.isAuthError=!0,e.errorType="Error Code",e.errorDetails={errorCode:n},e.shouldTriggerLogout=!0,n==="TOKEN_EXPIRED"?e.isTokenExpired=!0:e.isUnauthorized=!0,e.userFriendlyMessage="Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente.")}return e}updateLastActivity(){this.lastActivityTime=Date.now(),this.log("Last activity updated")}getTimeSinceLastActivity(){return this.lastActivityTime===0?0:Date.now()-this.lastActivityTime}checkInactivity(){let i=this.getTimeSinceLastActivity(),e=T.getTokenData();if(this.lastActivityTime===0)return"none";let n=900*1e3,r=300*1e3,d=300*1e3;return i>n?(this.log(`Inactivity timeout: ${Math.floor(i/6e4)} minutes since last activity`),"logout"):i<r&&e.expiresIn<d&&e.expiresIn>0?(this.log(`User active recently (${Math.floor(i/6e4)}min ago) and token expiring soon, should refresh`),"refresh"):"none"}clearSession(){f.clearTokens(),T.logout(),this.lastActivityTime=0,this.log("Session cleared completely")}getSessionExpiredMessage(){return this.config.translateFn?V("SESSION_EXPIRED",{translateFn:this.config.translateFn,enableDebug:this.config.enableLogging}):"Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente."}log(i,...e){this.config.enableLogging&&console.log(`[SessionManager] ${i}`,...e)}formatError(i){return i?typeof i=="string"?i:typeof i=="object"?Object.values(i).flat().join(", "):"Authentication failed":"Unknown error"}};import{useState as te,useEffect as F,useCallback as R}from"react";function B(o={}){let[i,e]=te({isAuthenticated:!1,isLoading:!0,isInitialized:!1,tokens:null,error:null}),n=U.getInstance(),r=R(async()=>{console.log("\u{1F535} [useSession] initialize() CALLED"),console.log("\u{1F50D} [useSession] options received:",{autoRestore:o.autoRestore,enableLogging:o.enableLogging,apiEndpointAdmin:o.apiEndpointAdmin,apiKeyEndpointAdmin:o.apiKeyEndpointAdmin});try{e(a=>({...a,isLoading:!0,error:null}));let c={autoRestore:o.autoRestore??!0,enableLogging:o.enableLogging??!1,showNotification:o.showNotification,translateFn:o.translateFn,apiEndpointAdmin:o.apiEndpointAdmin,apiKeyEndpointAdmin:o.apiKeyEndpointAdmin,onSessionExpired:()=>{e(a=>({...a,isAuthenticated:!1,tokens:null,error:"Session expired"})),o.onSessionExpired?.()},onSessionRestored:a=>{e(u=>({...u,isAuthenticated:!0,tokens:a,error:null})),o.onSessionRestored?.(a)},onLoginSuccess:a=>{e(u=>({...u,isAuthenticated:!0,tokens:a,error:null}))},onLogout:()=>{e(a=>({...a,isAuthenticated:!1,tokens:null,error:null}))}};console.log("\u{1F50D} [useSession] Calling sessionManager.initialize() with config:",c),await n.initialize(c),console.log("\u2705 [useSession] sessionManager.initialize() completed"),n.setupResponseInterceptor();let s=n.isAuthenticated(),t=n.getTokenInfo();console.log("\u{1F50D} [useSession] After initialize, isAuth:",s),console.log("\u{1F50D} [useSession] After initialize, tokenInfo:",t),e(a=>({...a,isAuthenticated:s,isInitialized:!0,isLoading:!1,tokens:t.crudifyTokens.accessToken?{accessToken:t.crudifyTokens.accessToken,refreshToken:t.crudifyTokens.refreshToken,expiresAt:t.crudifyTokens.expiresAt,refreshExpiresAt:t.crudifyTokens.refreshExpiresAt}:null}))}catch(c){let s=c instanceof Error?c.message:"Initialization failed";e(t=>({...t,isLoading:!1,isInitialized:!0,error:s}))}},[o.autoRestore,o.enableLogging,o.onSessionExpired,o.onSessionRestored]),d=R(async(c,s)=>{e(t=>({...t,isLoading:!0,error:null}));try{let t=await n.login(c,s);return t.success&&t.tokens?e(a=>({...a,isAuthenticated:!0,tokens:t.tokens,isLoading:!1,error:null})):e(a=>({...a,isAuthenticated:!1,tokens:null,isLoading:!1,error:null})),t}catch(t){let a=t instanceof Error?t.message:"Login failed",u=a.includes("INVALID_CREDENTIALS")||a.includes("Invalid email")||a.includes("Invalid password")||a.includes("credentials");return e(k=>({...k,isAuthenticated:!1,tokens:null,isLoading:!1,error:u?null:a})),{success:!1,error:a}}},[n]),p=R(async()=>{e(c=>({...c,isLoading:!0}));try{await n.logout(),e(c=>({...c,isAuthenticated:!1,tokens:null,isLoading:!1,error:null}))}catch(c){e(s=>({...s,isAuthenticated:!1,tokens:null,isLoading:!1,error:c instanceof Error?c.message:"Logout error"}))}},[n]),h=R(async()=>{try{let c=await n.refreshTokens();if(c){let s=n.getTokenInfo();e(t=>({...t,tokens:s.crudifyTokens.accessToken?{accessToken:s.crudifyTokens.accessToken,refreshToken:s.crudifyTokens.refreshToken,expiresAt:s.crudifyTokens.expiresAt,refreshExpiresAt:s.crudifyTokens.refreshExpiresAt}:null,error:null}))}else e(s=>({...s,isAuthenticated:!1,tokens:null,error:"Token refresh failed"}));return c}catch(c){return e(s=>({...s,isAuthenticated:!1,tokens:null,error:c instanceof Error?c.message:"Token refresh failed"})),!1}},[n]),m=R(()=>{e(c=>({...c,error:null}))},[]),E=R(()=>n.getTokenInfo(),[n]);F(()=>{r()},[r]),F(()=>{if(!i.isAuthenticated||!i.tokens)return;let c=X.getInstance(),s=()=>{n.updateLastActivity(),o.enableLogging&&console.log("\u{1F4CD} User navigating - activity updated")},t=c.subscribe(s);window.addEventListener("popstate",s);let a=setInterval(async()=>{if(n.isRefreshing()){o.enableLogging&&console.log("\u23F8\uFE0F Refresh already in progress, skipping inactivity check");return}let u=n.checkInactivity();if(u==="logout")o.enableLogging&&console.log("\u23F1\uFE0F Inactivity timeout - logging out user"),await p();else if(u==="refresh")if(o.enableLogging&&console.log("\u{1F504} User active, token expiring soon - refreshing..."),e(y=>({...y,isLoading:!0})),await n.refreshTokens()){let y=n.getTokenInfo();e(I=>({...I,isLoading:!1,tokens:y.crudifyTokens.accessToken?{accessToken:y.crudifyTokens.accessToken,refreshToken:y.crudifyTokens.refreshToken,expiresAt:y.crudifyTokens.expiresAt,refreshExpiresAt:y.crudifyTokens.refreshExpiresAt}:null}))}else e(y=>({...y,isLoading:!1,isAuthenticated:!1,tokens:null}))},120*1e3);return()=>{clearInterval(a),window.removeEventListener("popstate",s),t()}},[i.isAuthenticated,i.tokens,n,o.enableLogging,p]),F(()=>{let c=v.subscribe(async s=>{if(o.enableLogging&&console.log(`\u{1F4E2} useSession: Received auth event: ${s.type}`),s.type==="TOKEN_EXPIRED"){if(n.isRefreshing()){o.enableLogging&&console.log("\u23F8\uFE0F Refresh already in progress, skipping TOKEN_EXPIRED handler");return}o.enableLogging&&console.log("\u{1F504} Token expired, attempting refresh..."),e(t=>({...t,isLoading:!0}));try{if(await n.refreshTokens()){o.enableLogging&&console.log("\u2705 Token refreshed successfully");let a=n.getTokenInfo();e(u=>({...u,isLoading:!1,tokens:a.crudifyTokens.accessToken?{accessToken:a.crudifyTokens.accessToken,refreshToken:a.crudifyTokens.refreshToken,expiresAt:a.crudifyTokens.expiresAt,refreshExpiresAt:a.crudifyTokens.refreshExpiresAt}:null}))}else o.enableLogging&&console.log("\u274C Token refresh failed, session expired"),v.emit("SESSION_EXPIRED",{message:"Failed to refresh token after detecting expiration",source:"useSession.TOKEN_EXPIRED handler"})}catch(t){o.enableLogging&&console.error("\u274C Error during token refresh:",t),v.emit("SESSION_EXPIRED",{message:t instanceof Error?t.message:"Unknown error during refresh",source:"useSession.TOKEN_EXPIRED handler (error)"})}}(s.type==="SESSION_EXPIRED"||s.type==="TOKEN_REFRESH_FAILED")&&(o.enableLogging&&console.log(`\u{1F534} Session expired (${s.type}), logging out...`),e(t=>({...t,isAuthenticated:!1,tokens:null,isLoading:!1,error:s.details?.message||"Session expired"})),o.onSessionExpired?.())});return()=>c()},[o.enableLogging,o.onSessionExpired,n]),F(()=>{let c=f.subscribeToChanges(s=>{s?(o.enableLogging&&console.log("\u{1F504} Tokens updated in another tab"),e(t=>({...t,tokens:s,isAuthenticated:!0}))):(o.enableLogging&&console.log("\u{1F504} Logout detected in another tab"),e(t=>({...t,isAuthenticated:!1,tokens:null})),v.emit("SESSION_EXPIRED",{message:"Sesi\xF3n cerrada en otra pesta\xF1a",source:"CrossTabSync"}))});return()=>c()},[o.enableLogging]);let S=R(()=>{n.updateLastActivity()},[n]);return{...i,login:d,logout:p,refreshTokens:h,clearError:m,getTokenInfo:E,updateActivity:S,isExpiringSoon:i.tokens?i.tokens.expiresAt-Date.now()<300*1e3:!1,expiresIn:i.tokens?Math.max(0,i.tokens.expiresAt-Date.now()):0,refreshExpiresIn:i.tokens?Math.max(0,i.tokens.refreshExpiresAt-Date.now()):0}}import{useState as j,createContext as re,useContext as se,useCallback as H,useEffect as ae}from"react";import{Snackbar as le,Alert as ce,Box as de,Portal as ue}from"@mui/material";import{v4 as fe}from"uuid";import ge from"dompurify";import{jsx as C,jsxs as he}from"react/jsx-runtime";var W=re(null),pe=o=>ge.sanitize(o,{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}),J=({children:o,maxNotifications:i=5,defaultAutoHideDuration:e=6e3,position:n={vertical:"top",horizontal:"right"},enabled:r=!1,allowHtml:d=!1})=>{let[p,h]=j([]),m=H((s,t="info",a)=>{if(!r)return"";if(!s||typeof s!="string")return console.warn("\u26A0\uFE0F GlobalNotificationProvider: Invalid message provided"),"";s.length>1e3&&(console.warn("\u26A0\uFE0F GlobalNotificationProvider: Message too long, truncating"),s=s.substring(0,1e3)+"...");let u=fe(),k={id:u,message:s,severity:t,autoHideDuration:a?.autoHideDuration??e,persistent:a?.persistent??!1,allowHtml:a?.allowHtml??d};return h(y=>[...y.length>=i?y.slice(-(i-1)):y,k]),u},[i,e,r,d]),E=H(s=>{h(t=>t.filter(a=>a.id!==s))},[]),S=H(()=>{h([])},[]),c={showNotification:m,hideNotification:E,clearAllNotifications:S};return he(W.Provider,{value:c,children:[o,r&&C(ue,{children:C(de,{sx:{position:"fixed",zIndex:9999,[n.vertical]:(n.vertical==="top",24),[n.horizontal]:n.horizontal==="right"||n.horizontal==="left"?24:"50%",...n.horizontal==="center"&&{transform:"translateX(-50%)"},display:"flex",flexDirection:n.vertical==="top"?"column":"column-reverse",gap:1,maxWidth:"400px",width:"auto"},children:p.map(s=>C(ye,{notification:s,onClose:()=>E(s.id)},s.id))})})]})},ye=({notification:o,onClose:i})=>{let[e,n]=j(!0),r=H((d,p)=>{p!=="clickaway"&&(n(!1),setTimeout(i,300))},[i]);return ae(()=>{if(!o.persistent&&o.autoHideDuration){let d=setTimeout(()=>{r()},o.autoHideDuration);return()=>clearTimeout(d)}},[o.autoHideDuration,o.persistent,r]),C(le,{open:e,onClose:r,sx:{position:"relative","& .MuiSnackbarContent-root":{minWidth:"auto"}},TransitionProps:{enter:!0,exit:!0},children:C(ce,{variant:"filled",severity:o.severity,onClose:r,sx:{width:"100%",minWidth:"280px",maxWidth:"400px",wordBreak:"break-word"},children:o.allowHtml?C("span",{dangerouslySetInnerHTML:{__html:pe(o.message)}}):C("span",{children:o.message})})})},Z=()=>{let o=se(W);if(!o)throw new Error("useGlobalNotification debe ser usado dentro de un GlobalNotificationProvider");return o};import ke,{createContext as ve,useContext as be,useMemo as ee}from"react";import{createContext as me,useContext as Ee,useEffect as Te,useState as w}from"react";import K from"@nocios/crudify-browser";import{jsx as Ae}from"react/jsx-runtime";var q=me(void 0),ni=({config:o,children:i})=>{let[e,n]=w(!0),[r,d]=w(null),[p,h]=w(!1),[m,E]=w(""),[S,c]=w();console.log("\u{1F50D} CrudifyProvider - Received config:",o),Te(()=>{if(console.log("\u{1F50D} CrudifyProvider - useEffect - config.publicApiKey:",o.publicApiKey),console.log("\u{1F50D} CrudifyProvider - useEffect - full config:",o),!o.publicApiKey){console.log("\u274C CrudifyProvider - No publicApiKey provided, setting error"),d("No publicApiKey provided"),n(!1),h(!1);return}console.log("\u2705 CrudifyProvider - publicApiKey found, proceeding with initialization");let t=`${o.publicApiKey}-${o.env}`;if(t===m&&p){n(!1);return}(async()=>{console.log("\u{1F535} [CrudifyProvider] initializeCrudify() CALLED"),n(!0),d(null),h(!1);try{console.log("\u{1F50D} [CrudifyProvider] Calling crudify.config with env:",o.env||"prod"),K.config(o.env||"prod"),console.log("\u{1F50D} [CrudifyProvider] Calling crudify.init with publicApiKey:",o.publicApiKey);let u=await K.init(o.publicApiKey,"none");if(console.log("\u2705 [CrudifyProvider] crudify.init() completed, result:",u),c(u),console.log("\u2705 [CrudifyProvider] Admin credentials stored in state:",u),typeof K.transaction=="function"&&typeof K.login=="function")h(!0),E(t),console.log("\u2705 [CrudifyProvider] Crudify initialized successfully");else throw new Error("Crudify methods not properly initialized")}catch(u){let k=u instanceof Error?u.message:"Failed to initialize Crudify";console.error("\u274C [CrudifyProvider] Initialization error:",u),d(k),h(!1)}finally{n(!1)}})()},[o.publicApiKey,o.env,m,p]);let s={crudify:p?K:null,isLoading:e,error:r,isInitialized:p,adminCredentials:S};return Ae(q.Provider,{value:s,children:i})},Q=()=>{let o=Ee(q);if(o===void 0)throw new Error("useCrudify must be used within a CrudifyProvider");return o};import{Fragment as Ie,jsx as A,jsxs as b}from"react/jsx-runtime";var ie=ve(void 0);function Se({children:o,options:i={},config:e,showNotifications:n=!1,notificationOptions:r={}}){let d;try{let{showNotification:t}=Z();d=t}catch{}let p={};try{console.log("\u{1F535} [SessionProvider] Attempting to get Crudify context...");let t=Q();console.log("\u{1F50D} [SessionProvider] Crudify context obtained:",{isInitialized:t.isInitialized,isLoading:t.isLoading,hasAdminCredentials:!!t.adminCredentials,adminCredentials:t.adminCredentials}),t.adminCredentials?(p=t.adminCredentials,console.log("\u2705 [SessionProvider] Admin credentials obtained from Crudify context:",p)):console.warn("\u26A0\uFE0F [SessionProvider] Crudify context has no adminCredentials")}catch(t){console.warn("\u26A0\uFE0F [SessionProvider] Could not get Crudify context:",t)}let h=ke.useMemo(()=>{console.log("\u{1F50D} [SessionProvider] Creating enhancedOptions with adminCredentials:",p);let t={...i,showNotification:d,apiEndpointAdmin:p.apiEndpointAdmin,apiKeyEndpointAdmin:p.apiKeyEndpointAdmin,onSessionExpired:()=>{i.onSessionExpired?.()}};return console.log("\u2705 [SessionProvider] enhancedOptions created:",t),t},[i,d,p.apiEndpointAdmin,p.apiKeyEndpointAdmin]),m=B(h),E=ee(()=>{let t,a,u,k,y,I="unknown";if(e?.publicApiKey&&(t=e.publicApiKey,I="props"),e?.env&&(a=e.env),e?.appName&&(u=e.appName),e?.loginActions&&(k=e.loginActions),e?.logo&&(y=e.logo),!t){let L=P("publicApiKey"),N=P("environment"),x=P("appName"),g=P("loginActions"),D=P("logo");L&&(t=L,I="cookies"),N&&["dev","stg","prod"].includes(N)&&(a=N),x&&(u=decodeURIComponent(x)),g&&(k=decodeURIComponent(g).split(",").map(M=>M.trim()).filter(Boolean)),D&&(y=decodeURIComponent(D))}return{publicApiKey:t,env:a,appName:u,loginActions:k,logo:y}},[e]),S=ee(()=>{if(!m.tokens?.accessToken||!m.isAuthenticated)return null;try{let t=Y(m.tokens.accessToken);if(t&&t.sub&&t.email&&t.subscriber){let a={_id:t.sub,email:t.email,subscriberKey:t.subscriber};return Object.keys(t).forEach(u=>{["sub","email","subscriber"].includes(u)||(a[u]=t[u])}),a}}catch(t){console.error("Error decoding JWT token for sessionData:",t)}return null},[m.tokens?.accessToken,m.isAuthenticated]),c={...m,sessionData:S,config:E},s={enabled:n,maxNotifications:r.maxNotifications||5,defaultAutoHideDuration:r.defaultAutoHideDuration||6e3,position:r.position||{vertical:"top",horizontal:"right"}};return A(ie.Provider,{value:c,children:o})}function pi(o){let i={enabled:o.showNotifications,maxNotifications:o.notificationOptions?.maxNotifications||5,defaultAutoHideDuration:o.notificationOptions?.defaultAutoHideDuration||6e3,position:o.notificationOptions?.position||{vertical:"top",horizontal:"right"},allowHtml:o.notificationOptions?.allowHtml||!1};return A(J,{...i,children:A(Se,{...o})})}function xe(){let o=be(ie);if(o===void 0)throw new Error("useSessionContext must be used within a SessionProvider");return o}function yi(){let o=xe();return o.isInitialized?b("div",{style:{padding:"10px",margin:"10px",border:"1px solid #ccc",borderRadius:"4px",fontSize:"12px",fontFamily:"monospace"},children:[A("h4",{children:"Session Debug Info"}),b("div",{children:[A("strong",{children:"Authenticated:"})," ",o.isAuthenticated?"Yes":"No"]}),b("div",{children:[A("strong",{children:"Loading:"})," ",o.isLoading?"Yes":"No"]}),b("div",{children:[A("strong",{children:"Error:"})," ",o.error||"None"]}),o.tokens&&b(Ie,{children:[b("div",{children:[A("strong",{children:"Access Token:"})," ",o.tokens.accessToken.substring(0,20),"..."]}),b("div",{children:[A("strong",{children:"Refresh Token:"})," ",o.tokens.refreshToken.substring(0,20),"..."]}),b("div",{children:[A("strong",{children:"Access Expires In:"})," ",Math.round(o.expiresIn/1e3/60)," minutes"]}),b("div",{children:[A("strong",{children:"Refresh Expires In:"})," ",Math.round(o.refreshExpiresIn/1e3/60/60)," hours"]}),b("div",{children:[A("strong",{children:"Expiring Soon:"})," ",o.isExpiringSoon?"Yes":"No"]})]})]}):A("div",{children:"Session not initialized"})}import{useState as _,useEffect as ne,useCallback as oe,useRef as G}from"react";import Ne from"@nocios/crudify-browser";var ki=(o={})=>{let{autoFetch:i=!0,retryOnError:e=!1,maxRetries:n=3}=o,[r,d]=_(null),[p,h]=_(!1),[m,E]=_(null),[S,c]=_({}),s=G(null),t=G(!0),a=G(0),u=G(0),k=oe(()=>{d(null),E(null),h(!1),c({})},[]),y=oe(async()=>{let I=$();if(!I){t.current&&(E("No user email available"),h(!1));return}s.current&&s.current.abort();let L=new AbortController;s.current=L;let N=++a.current;try{t.current&&(h(!0),E(null));let x=await Ne.readItems("users",{filter:{email:I},pagination:{limit:1}});if(N===a.current&&t.current&&!L.signal.aborted)if(x.success&&x.data&&x.data.length>0){let g=x.data[0];d(g);let D={fullProfile:g,totalFields:Object.keys(g).length,displayData:{id:g.id,email:g.email,username:g.username,firstName:g.firstName,lastName:g.lastName,fullName:g.fullName||`${g.firstName||""} ${g.lastName||""}`.trim(),role:g.role,permissions:g.permissions||[],isActive:g.isActive,lastLogin:g.lastLogin,createdAt:g.createdAt,updatedAt:g.updatedAt,...Object.keys(g).filter(O=>!["id","email","username","firstName","lastName","fullName","role","permissions","isActive","lastLogin","createdAt","updatedAt"].includes(O)).reduce((O,M)=>({...O,[M]:g[M]}),{})}};c(D),E(null),u.current=0}else E("User profile not found"),d(null),c({})}catch(x){if(N===a.current&&t.current){let g=x;if(g.name==="AbortError")return;e&&u.current<n&&(g.message?.includes("Network Error")||g.message?.includes("Failed to fetch"))?(u.current++,setTimeout(()=>{t.current&&y()},1e3*u.current)):(E("Failed to load user profile"),d(null),c({}))}}finally{N===a.current&&t.current&&h(!1),s.current===L&&(s.current=null)}},[e,n]);return ne(()=>{i&&y()},[i,y]),ne(()=>(t.current=!0,()=>{t.current=!1,s.current&&(s.current.abort(),s.current=null)}),[]),{userProfile:r,loading:p,error:m,extendedData:S,refreshProfile:y,clearProfile:k}};export{ni as a,Q as b,f as c,U as d,B as e,J as f,Z as g,pi as h,xe as i,yi as j,ki as k};