@nocios/crudify-ui 4.0.98 → 4.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -74,4 +74,4 @@ declare function LoginComponent(): react_jsx_runtime.JSX.Element;
74
74
  */
75
75
  declare function SessionStatus(): react_jsx_runtime.JSX.Element;
76
76
 
77
- export { type BoxScreenType as B, CrudifyLogin as C, LoginComponent as L, Policies as P, SessionStatus as S, UserProfileDisplay as U, POLICY_ACTIONS as a, PREFERRED_POLICY_ORDER as b, type PolicyAction as c, type CrudifyLoginConfig as d, type CrudifyLoginProps as e, type CrudifyLoginTranslations as f, type UserLoginData as g };
77
+ export { type BoxScreenType as B, CrudifyLogin as C, LoginComponent as L, Policies as P, SessionStatus as S, UserProfileDisplay as U, type CrudifyLoginConfig as a, type CrudifyLoginProps as b, type CrudifyLoginTranslations as c, type UserLoginData as d, type PolicyAction as e, POLICY_ACTIONS as f, PREFERRED_POLICY_ORDER as g };
@@ -74,4 +74,4 @@ declare function LoginComponent(): react_jsx_runtime.JSX.Element;
74
74
  */
75
75
  declare function SessionStatus(): react_jsx_runtime.JSX.Element;
76
76
 
77
- export { type BoxScreenType as B, CrudifyLogin as C, LoginComponent as L, Policies as P, SessionStatus as S, UserProfileDisplay as U, POLICY_ACTIONS as a, PREFERRED_POLICY_ORDER as b, type PolicyAction as c, type CrudifyLoginConfig as d, type CrudifyLoginProps as e, type CrudifyLoginTranslations as f, type UserLoginData as g };
77
+ export { type BoxScreenType as B, CrudifyLogin as C, LoginComponent as L, Policies as P, SessionStatus as S, UserProfileDisplay as U, type CrudifyLoginConfig as a, type CrudifyLoginProps as b, type CrudifyLoginTranslations as c, type UserLoginData as d, type PolicyAction as e, POLICY_ACTIONS as f, PREFERRED_POLICY_ORDER as g };
@@ -1 +1 @@
1
- import{a as w,b as G,f as v,g as X,h as V,i as Y}from"./chunk-5JKS55SE.mjs";import O from"crypto-js";var l=class l{static setStorageType(r){l.storageType=r}static generateEncryptionKey(){let r=[navigator.userAgent,navigator.language,navigator.platform,screen.width,screen.height,Date.now().toString(),Math.random().toString(36)].join("|");return O.SHA256(r).toString()}static getEncryptionKey(){if(l.encryptionKey)return l.encryptionKey;let r=window.localStorage;if(!r)return l.encryptionKey=l.generateEncryptionKey(),l.encryptionKey;try{let e=r.getItem(l.ENCRYPTION_KEY_STORAGE);return(!e||e.length<32)&&(e=l.generateEncryptionKey(),r.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(r){try{let e=window[r],t="__storage_test__";return e.setItem(t,"test"),e.removeItem(t),!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(r){try{let e=l.getEncryptionKey();return O.AES.encrypt(r,e).toString()}catch(e){return console.error("Crudify: Encryption failed",e),r}}static decrypt(r){try{let e=l.getEncryptionKey();return O.AES.decrypt(r,e).toString(O.enc.Utf8)||r}catch(e){return console.error("Crudify: Decryption failed",e),r}}static saveTokens(r){let e=l.getStorage();if(e)try{let t={accessToken:r.accessToken,refreshToken:r.refreshToken,expiresAt:r.expiresAt,refreshExpiresAt:r.refreshExpiresAt,savedAt:Date.now()},i=l.encrypt(JSON.stringify(t));e.setItem(l.TOKEN_KEY,i),console.debug("Crudify: Tokens saved successfully")}catch(t){console.error("Crudify: Failed to save tokens",t)}}static getTokens(){let r=l.getStorage();if(!r)return null;try{let e=r.getItem(l.TOKEN_KEY);if(!e)return null;let t=l.decrypt(e),i=JSON.parse(t);return!i.accessToken||!i.refreshToken||!i.expiresAt||!i.refreshExpiresAt?(console.warn("Crudify: Incomplete token data found, clearing storage"),l.clearTokens(),null):Date.now()>=i.refreshExpiresAt?(console.info("Crudify: Refresh token expired, clearing storage"),l.clearTokens(),null):{accessToken:i.accessToken,refreshToken:i.refreshToken,expiresAt:i.expiresAt,refreshExpiresAt:i.refreshExpiresAt}}catch(e){return console.error("Crudify: Failed to retrieve tokens",e),l.clearTokens(),null}}static clearTokens(){let r=l.getStorage();if(r)try{r.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 r=window.localStorage;r&&r.removeItem(l.ENCRYPTION_KEY_STORAGE),console.info("Crudify: Encryption key rotated successfully")}catch(r){console.error("Crudify: Failed to rotate encryption key",r)}}static hasValidTokens(){return l.getTokens()!==null}static getExpirationInfo(){let r=l.getTokens();if(!r)return null;let e=Date.now();return{accessExpired:e>=r.expiresAt,refreshExpired:e>=r.refreshExpiresAt,accessExpiresIn:Math.max(0,r.expiresAt-e),refreshExpiresIn:Math.max(0,r.refreshExpiresAt-e)}}static updateAccessToken(r,e){let t=l.getTokens();if(!t){console.warn("Crudify: Cannot update access token, no existing tokens found");return}l.saveTokens({...t,accessToken:r,expiresAt:e})}static subscribeToChanges(r){let e=t=>{if(t.key===l.TOKEN_KEY){if(t.newValue===null){console.debug("Crudify: Tokens removed in another tab"),r(null);return}if(t.newValue){console.debug("Crudify: Tokens updated in another tab");let i=l.getTokens();r(i)}}};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 g=l;import k from"@nocios/crudify-browser";var C=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(r={}){if(this.initialized){console.warn("SessionManager: Already initialized");return}this.config={storageType:"localStorage",autoRestore:!0,enableLogging:!1,...r},g.setStorageType(this.config.storageType||"localStorage"),this.config.enableLogging,k.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"})}),this.config.autoRestore&&await this.restoreSession(),this.initialized=!0,this.log("SessionManager initialized successfully")}async login(r,e){try{this.log("Attempting login...");let t=await k.login(r,e);if(!t.success)return this.log("Login failed:",t.errors),{success:!1,error:this.formatError(t.errors),rawResponse:t};let i={accessToken:t.data.token,refreshToken:t.data.refreshToken,expiresAt:t.data.expiresAt,refreshExpiresAt:t.data.refreshExpiresAt};return g.saveTokens(i),this.lastActivityTime=Date.now(),this.log("Login successful, tokens saved"),this.config.onLoginSuccess?.(i),{success:!0,tokens:i,data:t.data}}catch(t){return this.log("Login error:",t),{success:!1,error:t instanceof Error?t.message:"Unknown error"}}}async logout(){try{this.log("Logging out..."),await k.logout(),g.clearTokens(),this.log("Logout successful"),this.config.onLogout?.()}catch(r){this.log("Logout error:",r),g.clearTokens()}}async restoreSession(){try{this.log("Attempting to restore session...");let r=g.getTokens();if(!r)return this.log("No valid tokens found in storage"),!1;if(Date.now()>=r.refreshExpiresAt)return this.log("Refresh token expired, clearing storage"),g.clearTokens(),!1;if(k.setTokens({accessToken:r.accessToken,refreshToken:r.refreshToken,expiresAt:r.expiresAt,refreshExpiresAt:r.refreshExpiresAt}),k.getTokenData().isValid===!1){if(this.log("Restored access token is invalid or expired"),Date.now()<r.refreshExpiresAt&&(this.log("Access token expired but refresh is valid, attempting refresh..."),await this.refreshTokens())){this.log("Session restored successfully via token refresh");let i=g.getTokens();return i&&this.config.onSessionRestored?.(i),!0}return g.clearTokens(),await k.logout(),!1}return this.log("Session restored successfully"),this.lastActivityTime=Date.now(),this.config.onSessionRestored?.(r),!0}catch(r){return this.log("Session restore error:",r),g.clearTokens(),await k.logout(),!1}}isAuthenticated(){return k.isLogin()||g.hasValidTokens()}getTokenInfo(){let r=k.getTokenData(),e=g.getExpirationInfo();return{isLoggedIn:this.isAuthenticated(),crudifyTokens:r,storageInfo:e,hasValidTokens:g.hasValidTokens()}}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 r=await k.refreshAccessToken();if(!r.success)return this.log("Token refresh failed:",r.errors),g.clearTokens(),this.config.showNotification?.(this.getSessionExpiredMessage(),"warning"),this.config.onSessionExpired?.(),!1;let e={accessToken:r.data.token,refreshToken:r.data.refreshToken,expiresAt:r.data.expiresAt,refreshExpiresAt:r.data.refreshExpiresAt};return g.saveTokens(e),this.log("Tokens refreshed and saved successfully"),this.lastActivityTime=Date.now(),!0}catch(r){return this.log("Token refresh error:",r),g.clearTokens(),this.config.showNotification?.(this.getSessionExpiredMessage(),"warning"),this.config.onSessionExpired?.(),!1}}isRefreshing(){return this.isRefreshingLocally}setupResponseInterceptor(){k.setResponseInterceptor(async r=>{this.updateLastActivity();let e=this.detectAuthorizationError(r);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"}),r;e.shouldTriggerLogout&&(g.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 r}),this.log("Response interceptor configured (non-blocking mode)")}detectAuthorizationError(r){let e={isAuthError:!1,isRefreshTokenInvalid:!1,isTokenRefreshFailed:!1,isTokenExpired:!1,isUnauthorized:!1,isIrrecoverable:!1,shouldTriggerLogout:!1,errorType:"",errorDetails:null,userFriendlyMessage:""};if(r.errors&&Array.isArray(r.errors)){let t=r.errors.find(i=>i.errorType==="Unauthorized"||i.message?.includes("Unauthorized")||i.message?.includes("Not Authorized")||i.message?.includes("NOT_AUTHORIZED")||i.message?.includes("Token")||i.message?.includes("TOKEN")||i.message?.includes("Authentication")||i.message?.includes("UNAUTHENTICATED")||i.extensions?.code==="UNAUTHENTICATED"||i.extensions?.code==="FORBIDDEN");t&&(e.isAuthError=!0,e.errorType="GraphQL Array",e.errorDetails=t,e.shouldTriggerLogout=!0,e.userFriendlyMessage="Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente.",(t.message?.includes("TOKEN")||t.message?.includes("Token"))&&(e.isTokenExpired=!0),t.extensions?.code==="UNAUTHENTICATED"&&(e.isUnauthorized=!0))}if(!e.isAuthError&&r.errors&&typeof r.errors=="object"&&!Array.isArray(r.errors)){let i=Object.values(r.errors).flat().find(u=>typeof u=="string"&&(u.includes("NOT_AUTHORIZED")||u.includes("TOKEN_REFRESH_FAILED")||u.includes("TOKEN_HAS_EXPIRED")||u.includes("PLEASE_LOGIN")||u.includes("Unauthorized")||u.includes("UNAUTHENTICATED")||u.includes("SESSION_EXPIRED")||u.includes("INVALID_TOKEN")));i&&typeof i=="string"&&(e.isAuthError=!0,e.errorType="GraphQL Object",e.errorDetails=r.errors,e.shouldTriggerLogout=!0,i.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."):i.includes("TOKEN_HAS_EXPIRED")||i.includes("SESSION_EXPIRED")?(e.isTokenExpired=!0,e.userFriendlyMessage="Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente."):i.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&&r.data?.response?.status){let t=r.data.response.status.toUpperCase();(t==="UNAUTHORIZED"||t==="UNAUTHENTICATED")&&(e.isAuthError=!0,e.errorType="Status",e.errorDetails=r.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&&r.data?.response?.data)try{let t=typeof r.data.response.data=="string"?JSON.parse(r.data.response.data):r.data.response.data;(t.error==="REFRESH_TOKEN_INVALID"||t.error==="TOKEN_EXPIRED"||t.error==="INVALID_TOKEN")&&(e.isAuthError=!0,e.errorType="Parsed Data",e.errorDetails=t,e.shouldTriggerLogout=!0,e.isIrrecoverable=!0,t.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&&r.errorCode){let t=r.errorCode.toUpperCase();(t==="UNAUTHORIZED"||t==="UNAUTHENTICATED"||t==="TOKEN_EXPIRED"||t==="INVALID_TOKEN")&&(e.isAuthError=!0,e.errorType="Error Code",e.errorDetails={errorCode:t},e.shouldTriggerLogout=!0,t==="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 r=this.getTimeSinceLastActivity(),e=k.getTokenData();if(this.lastActivityTime===0)return"none";let t=900*1e3,i=300*1e3,u=300*1e3;return r>t?(this.log(`Inactivity timeout: ${Math.floor(r/6e4)} minutes since last activity`),"logout"):r<i&&e.expiresIn<u&&e.expiresIn>0?(this.log(`User active recently (${Math.floor(r/6e4)}min ago) and token expiring soon, should refresh`),"refresh"):"none"}clearSession(){g.clearTokens(),k.logout(),this.lastActivityTime=0,this.log("Session cleared completely")}getSessionExpiredMessage(){return this.config.translateFn?G("SESSION_EXPIRED",{translateFn:this.config.translateFn,enableDebug:this.config.enableLogging}):"Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente."}log(r,...e){this.config.enableLogging&&console.log(`[SessionManager] ${r}`,...e)}formatError(r){return r?typeof r=="string"?r:typeof r=="object"?Object.values(r).flat().join(", "):"Authentication failed":"Unknown error"}};import{useState as te,useEffect as K,useCallback as R}from"react";function j(o={}){let[r,e]=te({isAuthenticated:!1,isLoading:!0,isInitialized:!1,tokens:null,error:null}),t=C.getInstance(),i=R(async()=>{try{e(a=>({...a,isLoading:!0,error:null}));let c={autoRestore:o.autoRestore??!0,enableLogging:o.enableLogging??!1,showNotification:o.showNotification,translateFn:o.translateFn,onSessionExpired:()=>{e(a=>({...a,isAuthenticated:!1,tokens:null,error:"Session expired"})),o.onSessionExpired?.()},onSessionRestored:a=>{e(d=>({...d,isAuthenticated:!0,tokens:a,error:null})),o.onSessionRestored?.(a)},onLoginSuccess:a=>{e(d=>({...d,isAuthenticated:!0,tokens:a,error:null}))},onLogout:()=>{e(a=>({...a,isAuthenticated:!1,tokens:null,error:null}))}};await t.initialize(c),t.setupResponseInterceptor();let s=t.isAuthenticated(),n=t.getTokenInfo();e(a=>({...a,isAuthenticated:s,isInitialized:!0,isLoading:!1,tokens:n.crudifyTokens.accessToken?{accessToken:n.crudifyTokens.accessToken,refreshToken:n.crudifyTokens.refreshToken,expiresAt:n.crudifyTokens.expiresAt,refreshExpiresAt:n.crudifyTokens.refreshExpiresAt}:null}))}catch(c){let s=c instanceof Error?c.message:"Initialization failed";e(n=>({...n,isLoading:!1,isInitialized:!0,error:s}))}},[o.autoRestore,o.enableLogging,o.onSessionExpired,o.onSessionRestored]),u=R(async(c,s)=>{e(n=>({...n,isLoading:!0,error:null}));try{let n=await t.login(c,s);return n.success&&n.tokens?e(a=>({...a,isAuthenticated:!0,tokens:n.tokens,isLoading:!1,error:null})):e(a=>({...a,isAuthenticated:!1,tokens:null,isLoading:!1,error:null})),n}catch(n){let a=n instanceof Error?n.message:"Login failed",d=a.includes("INVALID_CREDENTIALS")||a.includes("Invalid email")||a.includes("Invalid password")||a.includes("credentials");return e(m=>({...m,isAuthenticated:!1,tokens:null,isLoading:!1,error:d?null:a})),{success:!1,error:a}}},[t]),E=R(async()=>{e(c=>({...c,isLoading:!0}));try{await t.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"}))}},[t]),h=R(async()=>{try{let c=await t.refreshTokens();if(c){let s=t.getTokenInfo();e(n=>({...n,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}},[t]),S=R(()=>{e(c=>({...c,error:null}))},[]),y=R(()=>t.getTokenInfo(),[t]);K(()=>{i()},[i]),K(()=>{if(!r.isAuthenticated||!r.tokens)return;let c=X.getInstance(),s=()=>{t.updateLastActivity(),o.enableLogging&&console.log("\u{1F4CD} User navigating - activity updated")},n=c.subscribe(s);window.addEventListener("popstate",s);let a=setInterval(async()=>{if(t.isRefreshing()){o.enableLogging&&console.log("\u23F8\uFE0F Refresh already in progress, skipping inactivity check");return}let d=t.checkInactivity();if(d==="logout")o.enableLogging&&console.log("\u23F1\uFE0F Inactivity timeout - logging out user"),await E();else if(d==="refresh")if(o.enableLogging&&console.log("\u{1F504} User active, token expiring soon - refreshing..."),e(p=>({...p,isLoading:!0})),await t.refreshTokens()){let p=t.getTokenInfo();e(x=>({...x,isLoading:!1,tokens:p.crudifyTokens.accessToken?{accessToken:p.crudifyTokens.accessToken,refreshToken:p.crudifyTokens.refreshToken,expiresAt:p.crudifyTokens.expiresAt,refreshExpiresAt:p.crudifyTokens.refreshExpiresAt}:null}))}else e(p=>({...p,isLoading:!1,isAuthenticated:!1,tokens:null}))},120*1e3);return()=>{clearInterval(a),window.removeEventListener("popstate",s),n()}},[r.isAuthenticated,r.tokens,t,o.enableLogging,E]),K(()=>{let c=v.subscribe(async s=>{if(o.enableLogging&&console.log(`\u{1F4E2} useSession: Received auth event: ${s.type}`),s.type==="TOKEN_EXPIRED"){if(t.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(n=>({...n,isLoading:!0}));try{if(await t.refreshTokens()){o.enableLogging&&console.log("\u2705 Token refreshed successfully");let a=t.getTokenInfo();e(d=>({...d,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(n){o.enableLogging&&console.error("\u274C Error during token refresh:",n),v.emit("SESSION_EXPIRED",{message:n instanceof Error?n.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(n=>({...n,isAuthenticated:!1,tokens:null,isLoading:!1,error:s.details?.message||"Session expired"})),o.onSessionExpired?.())});return()=>c()},[o.enableLogging,o.onSessionExpired,t]),K(()=>{let c=g.subscribeToChanges(s=>{s?(o.enableLogging&&console.log("\u{1F504} Tokens updated in another tab"),e(n=>({...n,tokens:s,isAuthenticated:!0}))):(o.enableLogging&&console.log("\u{1F504} Logout detected in another tab"),e(n=>({...n,isAuthenticated:!1,tokens:null})),v.emit("SESSION_EXPIRED",{message:"Sesi\xF3n cerrada en otra pesta\xF1a",source:"CrossTabSync"}))});return()=>c()},[o.enableLogging]);let N=R(()=>{t.updateLastActivity()},[t]);return{...r,login:u,logout:E,refreshTokens:h,clearError:S,getTokenInfo:y,updateActivity:N,isExpiringSoon:r.tokens?r.tokens.expiresAt-Date.now()<300*1e3:!1,expiresIn:r.tokens?Math.max(0,r.tokens.expiresAt-Date.now()):0,refreshExpiresIn:r.tokens?Math.max(0,r.tokens.refreshExpiresAt-Date.now()):0}}import{useState as B,createContext as oe,useContext as se,useCallback as U,useEffect as ie}from"react";import{Snackbar as ne,Alert as ae,Box as le,Portal as ce}from"@mui/material";import{v4 as ue}from"uuid";import fe from"dompurify";import{jsx as D,jsxs as pe}from"react/jsx-runtime";var W=oe(null),de=o=>fe.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}),$=({children:o,maxNotifications:r=5,defaultAutoHideDuration:e=6e3,position:t={vertical:"top",horizontal:"right"},enabled:i=!1,allowHtml:u=!1})=>{let[E,h]=B([]),S=U((s,n="info",a)=>{if(!i)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 d=ue(),m={id:d,message:s,severity:n,autoHideDuration:a?.autoHideDuration??e,persistent:a?.persistent??!1,allowHtml:a?.allowHtml??u};return h(p=>[...p.length>=r?p.slice(-(r-1)):p,m]),d},[r,e,i,u]),y=U(s=>{h(n=>n.filter(a=>a.id!==s))},[]),N=U(()=>{h([])},[]),c={showNotification:S,hideNotification:y,clearAllNotifications:N};return pe(W.Provider,{value:c,children:[o,i&&D(ce,{children:D(le,{sx:{position:"fixed",zIndex:9999,[t.vertical]:(t.vertical==="top",24),[t.horizontal]:t.horizontal==="right"||t.horizontal==="left"?24:"50%",...t.horizontal==="center"&&{transform:"translateX(-50%)"},display:"flex",flexDirection:t.vertical==="top"?"column":"column-reverse",gap:1,maxWidth:"400px",width:"auto"},children:E.map(s=>D(ge,{notification:s,onClose:()=>y(s.id)},s.id))})})]})},ge=({notification:o,onClose:r})=>{let[e,t]=B(!0),i=U((u,E)=>{E!=="clickaway"&&(t(!1),setTimeout(r,300))},[r]);return ie(()=>{if(!o.persistent&&o.autoHideDuration){let u=setTimeout(()=>{i()},o.autoHideDuration);return()=>clearTimeout(u)}},[o.autoHideDuration,o.persistent,i]),D(ne,{open:e,onClose:i,sx:{position:"relative","& .MuiSnackbarContent-root":{minWidth:"auto"}},TransitionProps:{enter:!0,exit:!0},children:D(ae,{variant:"filled",severity:o.severity,onClose:i,sx:{width:"100%",minWidth:"280px",maxWidth:"400px",wordBreak:"break-word"},children:o.allowHtml?D("span",{dangerouslySetInnerHTML:{__html:de(o.message)}}):D("span",{children:o.message})})})},J=()=>{let o=se(W);if(!o)throw new Error("useGlobalNotification debe ser usado dentro de un GlobalNotificationProvider");return o};import he,{createContext as Te,useContext as ye,useMemo as Z}from"react";import{Fragment as z,jsx as T,jsxs as b}from"react/jsx-runtime";var q=Te(void 0);function ke({children:o,options:r={},config:e,showNotifications:t=!1,notificationOptions:i={}}){let u;try{let{showNotification:s}=J();u=s}catch{}let E=he.useMemo(()=>({...r,showNotification:u,onSessionExpired:()=>{r.onSessionExpired?.()}}),[r,u]),h=j(E),S=Z(()=>{let s,n,a,d,m,p="unknown";if(e?.publicApiKey&&(s=e.publicApiKey,p="props"),e?.env&&(n=e.env),e?.appName&&(a=e.appName),e?.loginActions&&(d=e.loginActions),e?.logo&&(m=e.logo),!s){let x=w("publicApiKey"),I=w("environment"),L=w("appName"),A=w("loginActions"),f=w("logo");x&&(s=x,p="cookies"),I&&["dev","stg","prod"].includes(I)&&(n=I),L&&(a=decodeURIComponent(L)),A&&(d=decodeURIComponent(A).split(",").map(P=>P.trim()).filter(Boolean)),f&&(m=decodeURIComponent(f))}return{publicApiKey:s,env:n,appName:a,loginActions:d,logo:m}},[e]),y=Z(()=>{if(!h.tokens?.accessToken||!h.isAuthenticated)return null;try{let s=V(h.tokens.accessToken);if(s&&s.sub&&s.email&&s.subscriber){let n={_id:s.sub,email:s.email,subscriberKey:s.subscriber};return Object.keys(s).forEach(a=>{["sub","email","subscriber"].includes(a)||(n[a]=s[a])}),n}}catch(s){console.error("Error decoding JWT token for sessionData:",s)}return null},[h.tokens?.accessToken,h.isAuthenticated]),N={...h,sessionData:y,config:S},c={enabled:t,maxNotifications:i.maxNotifications||5,defaultAutoHideDuration:i.defaultAutoHideDuration||6e3,position:i.position||{vertical:"top",horizontal:"right"}};return T(q.Provider,{value:N,children:o})}function Qe(o){let r={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 T($,{...r,children:T(ke,{...o})})}function Q(){let o=ye(q);if(o===void 0)throw new Error("useSessionContext must be used within a SessionProvider");return o}function er({children:o,fallback:r=T("div",{children:"Please log in to access this content"}),redirectTo:e}){let{isAuthenticated:t,isLoading:i,isInitialized:u}=Q();return!u||i?T("div",{children:"Loading..."}):t?T(z,{children:o}):e?(e(),null):T(z,{children:r})}function rr(){let o=Q();return o.isInitialized?b("div",{style:{padding:"10px",margin:"10px",border:"1px solid #ccc",borderRadius:"4px",fontSize:"12px",fontFamily:"monospace"},children:[T("h4",{children:"Session Debug Info"}),b("div",{children:[T("strong",{children:"Authenticated:"})," ",o.isAuthenticated?"Yes":"No"]}),b("div",{children:[T("strong",{children:"Loading:"})," ",o.isLoading?"Yes":"No"]}),b("div",{children:[T("strong",{children:"Error:"})," ",o.error||"None"]}),o.tokens&&b(z,{children:[b("div",{children:[T("strong",{children:"Access Token:"})," ",o.tokens.accessToken.substring(0,20),"..."]}),b("div",{children:[T("strong",{children:"Refresh Token:"})," ",o.tokens.refreshToken.substring(0,20),"..."]}),b("div",{children:[T("strong",{children:"Access Expires In:"})," ",Math.round(o.expiresIn/1e3/60)," minutes"]}),b("div",{children:[T("strong",{children:"Refresh Expires In:"})," ",Math.round(o.refreshExpiresIn/1e3/60/60)," hours"]}),b("div",{children:[T("strong",{children:"Expiring Soon:"})," ",o.isExpiringSoon?"Yes":"No"]})]})]}):T("div",{children:"Session not initialized"})}import{useState as F,useEffect as ee,useCallback as re,useRef as M}from"react";import Ee from"@nocios/crudify-browser";var ar=(o={})=>{let{autoFetch:r=!0,retryOnError:e=!1,maxRetries:t=3}=o,[i,u]=F(null),[E,h]=F(!1),[S,y]=F(null),[N,c]=F({}),s=M(null),n=M(!0),a=M(0),d=M(0),m=re(()=>{u(null),y(null),h(!1),c({})},[]),p=re(async()=>{let x=Y();if(!x){n.current&&(y("No user email available"),h(!1));return}s.current&&s.current.abort();let I=new AbortController;s.current=I;let L=++a.current;try{n.current&&(h(!0),y(null));let A=await Ee.readItems("users",{filter:{email:x},pagination:{limit:1}});if(L===a.current&&n.current&&!I.signal.aborted)if(A.success&&A.data&&A.data.length>0){let f=A.data[0];u(f);let H={fullProfile:f,totalFields:Object.keys(f).length,displayData:{id:f.id,email:f.email,username:f.username,firstName:f.firstName,lastName:f.lastName,fullName:f.fullName||`${f.firstName||""} ${f.lastName||""}`.trim(),role:f.role,permissions:f.permissions||[],isActive:f.isActive,lastLogin:f.lastLogin,createdAt:f.createdAt,updatedAt:f.updatedAt,...Object.keys(f).filter(P=>!["id","email","username","firstName","lastName","fullName","role","permissions","isActive","lastLogin","createdAt","updatedAt"].includes(P)).reduce((P,_)=>({...P,[_]:f[_]}),{})}};c(H),y(null),d.current=0}else y("User profile not found"),u(null),c({})}catch(A){if(L===a.current&&n.current){let f=A;if(f.name==="AbortError")return;e&&d.current<t&&(f.message?.includes("Network Error")||f.message?.includes("Failed to fetch"))?(d.current++,setTimeout(()=>{n.current&&p()},1e3*d.current)):(y("Failed to load user profile"),u(null),c({}))}}finally{L===a.current&&n.current&&h(!1),s.current===I&&(s.current=null)}},[e,t]);return ee(()=>{r&&p()},[r,p]),ee(()=>(n.current=!0,()=>{n.current=!1,s.current&&(s.current.abort(),s.current=null)}),[]),{userProfile:i,loading:E,error:S,extendedData:N,refreshProfile:p,clearProfile:m}};export{g as a,C as b,j as c,$ as d,J as e,Qe as f,Q as g,er as h,rr as i,ar as j};
1
+ import{a as w,b as _,f as v,g as G,h as X,i as V}from"./chunk-5JKS55SE.mjs";import O from"crypto-js";var l=class l{static setStorageType(r){l.storageType=r}static generateEncryptionKey(){let r=[navigator.userAgent,navigator.language,navigator.platform,screen.width,screen.height,Date.now().toString(),Math.random().toString(36)].join("|");return O.SHA256(r).toString()}static getEncryptionKey(){if(l.encryptionKey)return l.encryptionKey;let r=window.localStorage;if(!r)return l.encryptionKey=l.generateEncryptionKey(),l.encryptionKey;try{let e=r.getItem(l.ENCRYPTION_KEY_STORAGE);return(!e||e.length<32)&&(e=l.generateEncryptionKey(),r.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(r){try{let e=window[r],t="__storage_test__";return e.setItem(t,"test"),e.removeItem(t),!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(r){try{let e=l.getEncryptionKey();return O.AES.encrypt(r,e).toString()}catch(e){return console.error("Crudify: Encryption failed",e),r}}static decrypt(r){try{let e=l.getEncryptionKey();return O.AES.decrypt(r,e).toString(O.enc.Utf8)||r}catch(e){return console.error("Crudify: Decryption failed",e),r}}static saveTokens(r){let e=l.getStorage();if(e)try{let t={accessToken:r.accessToken,refreshToken:r.refreshToken,expiresAt:r.expiresAt,refreshExpiresAt:r.refreshExpiresAt,savedAt:Date.now()},i=l.encrypt(JSON.stringify(t));e.setItem(l.TOKEN_KEY,i),console.debug("Crudify: Tokens saved successfully")}catch(t){console.error("Crudify: Failed to save tokens",t)}}static getTokens(){let r=l.getStorage();if(!r)return null;try{let e=r.getItem(l.TOKEN_KEY);if(!e)return null;let t=l.decrypt(e),i=JSON.parse(t);return!i.accessToken||!i.refreshToken||!i.expiresAt||!i.refreshExpiresAt?(console.warn("Crudify: Incomplete token data found, clearing storage"),l.clearTokens(),null):Date.now()>=i.refreshExpiresAt?(console.info("Crudify: Refresh token expired, clearing storage"),l.clearTokens(),null):{accessToken:i.accessToken,refreshToken:i.refreshToken,expiresAt:i.expiresAt,refreshExpiresAt:i.refreshExpiresAt}}catch(e){return console.error("Crudify: Failed to retrieve tokens",e),l.clearTokens(),null}}static clearTokens(){let r=l.getStorage();if(r)try{r.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 r=window.localStorage;r&&r.removeItem(l.ENCRYPTION_KEY_STORAGE),console.info("Crudify: Encryption key rotated successfully")}catch(r){console.error("Crudify: Failed to rotate encryption key",r)}}static hasValidTokens(){return l.getTokens()!==null}static getExpirationInfo(){let r=l.getTokens();if(!r)return null;let e=Date.now();return{accessExpired:e>=r.expiresAt,refreshExpired:e>=r.refreshExpiresAt,accessExpiresIn:Math.max(0,r.expiresAt-e),refreshExpiresIn:Math.max(0,r.refreshExpiresAt-e)}}static updateAccessToken(r,e){let t=l.getTokens();if(!t){console.warn("Crudify: Cannot update access token, no existing tokens found");return}l.saveTokens({...t,accessToken:r,expiresAt:e})}static subscribeToChanges(r){let e=t=>{if(t.key===l.TOKEN_KEY){if(t.newValue===null){console.debug("Crudify: Tokens removed in another tab"),r(null);return}if(t.newValue){console.debug("Crudify: Tokens updated in another tab");let i=l.getTokens();r(i)}}};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 g=l;import y from"@nocios/crudify-browser";var C=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(r={}){if(this.initialized){console.warn("SessionManager: Already initialized");return}this.config={storageType:"localStorage",autoRestore:!0,enableLogging:!1,...r},g.setStorageType(this.config.storageType||"localStorage"),this.config.enableLogging,y.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"})}),this.config.autoRestore&&await this.restoreSession(),this.initialized=!0,this.log("SessionManager initialized successfully")}async login(r,e){try{this.log("Attempting login...");let t=await y.login(r,e);if(!t.success)return this.log("Login failed:",t.errors),{success:!1,error:this.formatError(t.errors),rawResponse:t};let i={accessToken:t.data.token,refreshToken:t.data.refreshToken,expiresAt:t.data.expiresAt,refreshExpiresAt:t.data.refreshExpiresAt};return g.saveTokens(i),this.lastActivityTime=Date.now(),this.log("Login successful, tokens saved"),this.config.onLoginSuccess?.(i),{success:!0,tokens:i,data:t.data}}catch(t){return this.log("Login error:",t),{success:!1,error:t instanceof Error?t.message:"Unknown error"}}}async logout(){try{this.log("Logging out..."),await y.logout(),g.clearTokens(),this.log("Logout successful"),this.config.onLogout?.()}catch(r){this.log("Logout error:",r),g.clearTokens()}}async restoreSession(){try{this.log("Attempting to restore session...");let r=g.getTokens();if(!r)return this.log("No valid tokens found in storage"),!1;if(Date.now()>=r.refreshExpiresAt)return this.log("Refresh token expired, clearing storage"),g.clearTokens(),!1;if(y.setTokens({accessToken:r.accessToken,refreshToken:r.refreshToken,expiresAt:r.expiresAt,refreshExpiresAt:r.refreshExpiresAt}),y.getTokenData().isValid===!1){if(this.log("Restored access token is invalid or expired"),Date.now()<r.refreshExpiresAt&&(this.log("Access token expired but refresh is valid, attempting refresh..."),await this.refreshTokens())){this.log("Session restored successfully via token refresh");let i=g.getTokens();return i&&this.config.onSessionRestored?.(i),!0}return g.clearTokens(),await y.logout(),!1}return this.log("Session restored successfully"),this.lastActivityTime=Date.now(),this.config.onSessionRestored?.(r),!0}catch(r){return this.log("Session restore error:",r),g.clearTokens(),await y.logout(),!1}}isAuthenticated(){return y.isLogin()||g.hasValidTokens()}getTokenInfo(){let r=y.getTokenData(),e=g.getExpirationInfo();return{isLoggedIn:this.isAuthenticated(),crudifyTokens:r,storageInfo:e,hasValidTokens:g.hasValidTokens()}}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 r=await y.refreshAccessToken();if(!r.success)return this.log("Token refresh failed:",r.errors),g.clearTokens(),this.config.showNotification?.(this.getSessionExpiredMessage(),"warning"),this.config.onSessionExpired?.(),!1;let e={accessToken:r.data.token,refreshToken:r.data.refreshToken,expiresAt:r.data.expiresAt,refreshExpiresAt:r.data.refreshExpiresAt};return g.saveTokens(e),this.log("Tokens refreshed and saved successfully"),this.lastActivityTime=Date.now(),!0}catch(r){return this.log("Token refresh error:",r),g.clearTokens(),this.config.showNotification?.(this.getSessionExpiredMessage(),"warning"),this.config.onSessionExpired?.(),!1}}isRefreshing(){return this.isRefreshingLocally}setupResponseInterceptor(){y.setResponseInterceptor(async r=>{this.updateLastActivity();let e=this.detectAuthorizationError(r);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"}),r;e.shouldTriggerLogout&&(g.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 r}),this.log("Response interceptor configured (non-blocking mode)")}detectAuthorizationError(r){let e={isAuthError:!1,isRefreshTokenInvalid:!1,isTokenRefreshFailed:!1,isTokenExpired:!1,isUnauthorized:!1,isIrrecoverable:!1,shouldTriggerLogout:!1,errorType:"",errorDetails:null,userFriendlyMessage:""};if(r.errors&&Array.isArray(r.errors)){let t=r.errors.find(i=>i.errorType==="Unauthorized"||i.message?.includes("Unauthorized")||i.message?.includes("Not Authorized")||i.message?.includes("NOT_AUTHORIZED")||i.message?.includes("Token")||i.message?.includes("TOKEN")||i.message?.includes("Authentication")||i.message?.includes("UNAUTHENTICATED")||i.extensions?.code==="UNAUTHENTICATED"||i.extensions?.code==="FORBIDDEN");t&&(e.isAuthError=!0,e.errorType="GraphQL Array",e.errorDetails=t,e.shouldTriggerLogout=!0,e.userFriendlyMessage="Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente.",(t.message?.includes("TOKEN")||t.message?.includes("Token"))&&(e.isTokenExpired=!0),t.extensions?.code==="UNAUTHENTICATED"&&(e.isUnauthorized=!0))}if(!e.isAuthError&&r.errors&&typeof r.errors=="object"&&!Array.isArray(r.errors)){let i=Object.values(r.errors).flat().find(u=>typeof u=="string"&&(u.includes("NOT_AUTHORIZED")||u.includes("TOKEN_REFRESH_FAILED")||u.includes("TOKEN_HAS_EXPIRED")||u.includes("PLEASE_LOGIN")||u.includes("Unauthorized")||u.includes("UNAUTHENTICATED")||u.includes("SESSION_EXPIRED")||u.includes("INVALID_TOKEN")));i&&typeof i=="string"&&(e.isAuthError=!0,e.errorType="GraphQL Object",e.errorDetails=r.errors,e.shouldTriggerLogout=!0,i.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."):i.includes("TOKEN_HAS_EXPIRED")||i.includes("SESSION_EXPIRED")?(e.isTokenExpired=!0,e.userFriendlyMessage="Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente."):i.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&&r.data?.response?.status){let t=r.data.response.status.toUpperCase();(t==="UNAUTHORIZED"||t==="UNAUTHENTICATED")&&(e.isAuthError=!0,e.errorType="Status",e.errorDetails=r.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&&r.data?.response?.data)try{let t=typeof r.data.response.data=="string"?JSON.parse(r.data.response.data):r.data.response.data;(t.error==="REFRESH_TOKEN_INVALID"||t.error==="TOKEN_EXPIRED"||t.error==="INVALID_TOKEN")&&(e.isAuthError=!0,e.errorType="Parsed Data",e.errorDetails=t,e.shouldTriggerLogout=!0,e.isIrrecoverable=!0,t.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&&r.errorCode){let t=r.errorCode.toUpperCase();(t==="UNAUTHORIZED"||t==="UNAUTHENTICATED"||t==="TOKEN_EXPIRED"||t==="INVALID_TOKEN")&&(e.isAuthError=!0,e.errorType="Error Code",e.errorDetails={errorCode:t},e.shouldTriggerLogout=!0,t==="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 r=this.getTimeSinceLastActivity(),e=y.getTokenData();if(this.lastActivityTime===0)return"none";let t=900*1e3,i=300*1e3,u=300*1e3;return r>t?(this.log(`Inactivity timeout: ${Math.floor(r/6e4)} minutes since last activity`),"logout"):r<i&&e.expiresIn<u&&e.expiresIn>0?(this.log(`User active recently (${Math.floor(r/6e4)}min ago) and token expiring soon, should refresh`),"refresh"):"none"}clearSession(){g.clearTokens(),y.logout(),this.lastActivityTime=0,this.log("Session cleared completely")}getSessionExpiredMessage(){return this.config.translateFn?_("SESSION_EXPIRED",{translateFn:this.config.translateFn,enableDebug:this.config.enableLogging}):"Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente."}log(r,...e){this.config.enableLogging&&console.log(`[SessionManager] ${r}`,...e)}formatError(r){return r?typeof r=="string"?r:typeof r=="object"?Object.values(r).flat().join(", "):"Authentication failed":"Unknown error"}};import{useState as ee,useEffect as K,useCallback as R}from"react";function Y(o={}){let[r,e]=ee({isAuthenticated:!1,isLoading:!0,isInitialized:!1,tokens:null,error:null}),t=C.getInstance(),i=R(async()=>{try{e(a=>({...a,isLoading:!0,error:null}));let c={autoRestore:o.autoRestore??!0,enableLogging:o.enableLogging??!1,showNotification:o.showNotification,translateFn:o.translateFn,onSessionExpired:()=>{e(a=>({...a,isAuthenticated:!1,tokens:null,error:"Session expired"})),o.onSessionExpired?.()},onSessionRestored:a=>{e(d=>({...d,isAuthenticated:!0,tokens:a,error:null})),o.onSessionRestored?.(a)},onLoginSuccess:a=>{e(d=>({...d,isAuthenticated:!0,tokens:a,error:null}))},onLogout:()=>{e(a=>({...a,isAuthenticated:!1,tokens:null,error:null}))}};await t.initialize(c),t.setupResponseInterceptor();let s=t.isAuthenticated(),n=t.getTokenInfo();e(a=>({...a,isAuthenticated:s,isInitialized:!0,isLoading:!1,tokens:n.crudifyTokens.accessToken?{accessToken:n.crudifyTokens.accessToken,refreshToken:n.crudifyTokens.refreshToken,expiresAt:n.crudifyTokens.expiresAt,refreshExpiresAt:n.crudifyTokens.refreshExpiresAt}:null}))}catch(c){let s=c instanceof Error?c.message:"Initialization failed";e(n=>({...n,isLoading:!1,isInitialized:!0,error:s}))}},[o.autoRestore,o.enableLogging,o.onSessionExpired,o.onSessionRestored]),u=R(async(c,s)=>{e(n=>({...n,isLoading:!0,error:null}));try{let n=await t.login(c,s);return n.success&&n.tokens?e(a=>({...a,isAuthenticated:!0,tokens:n.tokens,isLoading:!1,error:null})):e(a=>({...a,isAuthenticated:!1,tokens:null,isLoading:!1,error:null})),n}catch(n){let a=n instanceof Error?n.message:"Login failed",d=a.includes("INVALID_CREDENTIALS")||a.includes("Invalid email")||a.includes("Invalid password")||a.includes("credentials");return e(m=>({...m,isAuthenticated:!1,tokens:null,isLoading:!1,error:d?null:a})),{success:!1,error:a}}},[t]),E=R(async()=>{e(c=>({...c,isLoading:!0}));try{await t.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"}))}},[t]),h=R(async()=>{try{let c=await t.refreshTokens();if(c){let s=t.getTokenInfo();e(n=>({...n,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}},[t]),S=R(()=>{e(c=>({...c,error:null}))},[]),T=R(()=>t.getTokenInfo(),[t]);K(()=>{i()},[i]),K(()=>{if(!r.isAuthenticated||!r.tokens)return;let c=G.getInstance(),s=()=>{t.updateLastActivity(),o.enableLogging&&console.log("\u{1F4CD} User navigating - activity updated")},n=c.subscribe(s);window.addEventListener("popstate",s);let a=setInterval(async()=>{if(t.isRefreshing()){o.enableLogging&&console.log("\u23F8\uFE0F Refresh already in progress, skipping inactivity check");return}let d=t.checkInactivity();if(d==="logout")o.enableLogging&&console.log("\u23F1\uFE0F Inactivity timeout - logging out user"),await E();else if(d==="refresh")if(o.enableLogging&&console.log("\u{1F504} User active, token expiring soon - refreshing..."),e(p=>({...p,isLoading:!0})),await t.refreshTokens()){let p=t.getTokenInfo();e(x=>({...x,isLoading:!1,tokens:p.crudifyTokens.accessToken?{accessToken:p.crudifyTokens.accessToken,refreshToken:p.crudifyTokens.refreshToken,expiresAt:p.crudifyTokens.expiresAt,refreshExpiresAt:p.crudifyTokens.refreshExpiresAt}:null}))}else e(p=>({...p,isLoading:!1,isAuthenticated:!1,tokens:null}))},120*1e3);return()=>{clearInterval(a),window.removeEventListener("popstate",s),n()}},[r.isAuthenticated,r.tokens,t,o.enableLogging,E]),K(()=>{let c=v.subscribe(async s=>{if(o.enableLogging&&console.log(`\u{1F4E2} useSession: Received auth event: ${s.type}`),s.type==="TOKEN_EXPIRED"){if(t.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(n=>({...n,isLoading:!0}));try{if(await t.refreshTokens()){o.enableLogging&&console.log("\u2705 Token refreshed successfully");let a=t.getTokenInfo();e(d=>({...d,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(n){o.enableLogging&&console.error("\u274C Error during token refresh:",n),v.emit("SESSION_EXPIRED",{message:n instanceof Error?n.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(n=>({...n,isAuthenticated:!1,tokens:null,isLoading:!1,error:s.details?.message||"Session expired"})),o.onSessionExpired?.())});return()=>c()},[o.enableLogging,o.onSessionExpired,t]),K(()=>{let c=g.subscribeToChanges(s=>{s?(o.enableLogging&&console.log("\u{1F504} Tokens updated in another tab"),e(n=>({...n,tokens:s,isAuthenticated:!0}))):(o.enableLogging&&console.log("\u{1F504} Logout detected in another tab"),e(n=>({...n,isAuthenticated:!1,tokens:null})),v.emit("SESSION_EXPIRED",{message:"Sesi\xF3n cerrada en otra pesta\xF1a",source:"CrossTabSync"}))});return()=>c()},[o.enableLogging]);let N=R(()=>{t.updateLastActivity()},[t]);return{...r,login:u,logout:E,refreshTokens:h,clearError:S,getTokenInfo:T,updateActivity:N,isExpiringSoon:r.tokens?r.tokens.expiresAt-Date.now()<300*1e3:!1,expiresIn:r.tokens?Math.max(0,r.tokens.expiresAt-Date.now()):0,refreshExpiresIn:r.tokens?Math.max(0,r.tokens.refreshExpiresAt-Date.now()):0}}import{useState as j,createContext as re,useContext as te,useCallback as U,useEffect as oe}from"react";import{Snackbar as se,Alert as ie,Box as ne,Portal as ae}from"@mui/material";import{v4 as le}from"uuid";import ce from"dompurify";import{jsx as D,jsxs as de}from"react/jsx-runtime";var B=re(null),ue=o=>ce.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}),W=({children:o,maxNotifications:r=5,defaultAutoHideDuration:e=6e3,position:t={vertical:"top",horizontal:"right"},enabled:i=!1,allowHtml:u=!1})=>{let[E,h]=j([]),S=U((s,n="info",a)=>{if(!i)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 d=le(),m={id:d,message:s,severity:n,autoHideDuration:a?.autoHideDuration??e,persistent:a?.persistent??!1,allowHtml:a?.allowHtml??u};return h(p=>[...p.length>=r?p.slice(-(r-1)):p,m]),d},[r,e,i,u]),T=U(s=>{h(n=>n.filter(a=>a.id!==s))},[]),N=U(()=>{h([])},[]),c={showNotification:S,hideNotification:T,clearAllNotifications:N};return de(B.Provider,{value:c,children:[o,i&&D(ae,{children:D(ne,{sx:{position:"fixed",zIndex:9999,[t.vertical]:(t.vertical==="top",24),[t.horizontal]:t.horizontal==="right"||t.horizontal==="left"?24:"50%",...t.horizontal==="center"&&{transform:"translateX(-50%)"},display:"flex",flexDirection:t.vertical==="top"?"column":"column-reverse",gap:1,maxWidth:"400px",width:"auto"},children:E.map(s=>D(fe,{notification:s,onClose:()=>T(s.id)},s.id))})})]})},fe=({notification:o,onClose:r})=>{let[e,t]=j(!0),i=U((u,E)=>{E!=="clickaway"&&(t(!1),setTimeout(r,300))},[r]);return oe(()=>{if(!o.persistent&&o.autoHideDuration){let u=setTimeout(()=>{i()},o.autoHideDuration);return()=>clearTimeout(u)}},[o.autoHideDuration,o.persistent,i]),D(se,{open:e,onClose:i,sx:{position:"relative","& .MuiSnackbarContent-root":{minWidth:"auto"}},TransitionProps:{enter:!0,exit:!0},children:D(ie,{variant:"filled",severity:o.severity,onClose:i,sx:{width:"100%",minWidth:"280px",maxWidth:"400px",wordBreak:"break-word"},children:o.allowHtml?D("span",{dangerouslySetInnerHTML:{__html:ue(o.message)}}):D("span",{children:o.message})})})},$=()=>{let o=te(B);if(!o)throw new Error("useGlobalNotification debe ser usado dentro de un GlobalNotificationProvider");return o};import ge,{createContext as pe,useContext as he,useMemo as J}from"react";import{Fragment as ke,jsx as k,jsxs as b}from"react/jsx-runtime";var Z=pe(void 0);function Te({children:o,options:r={},config:e,showNotifications:t=!1,notificationOptions:i={}}){let u;try{let{showNotification:s}=$();u=s}catch{}let E=ge.useMemo(()=>({...r,showNotification:u,onSessionExpired:()=>{r.onSessionExpired?.()}}),[r,u]),h=Y(E),S=J(()=>{let s,n,a,d,m,p="unknown";if(e?.publicApiKey&&(s=e.publicApiKey,p="props"),e?.env&&(n=e.env),e?.appName&&(a=e.appName),e?.loginActions&&(d=e.loginActions),e?.logo&&(m=e.logo),!s){let x=w("publicApiKey"),I=w("environment"),L=w("appName"),A=w("loginActions"),f=w("logo");x&&(s=x,p="cookies"),I&&["dev","stg","prod"].includes(I)&&(n=I),L&&(a=decodeURIComponent(L)),A&&(d=decodeURIComponent(A).split(",").map(P=>P.trim()).filter(Boolean)),f&&(m=decodeURIComponent(f))}return{publicApiKey:s,env:n,appName:a,loginActions:d,logo:m}},[e]),T=J(()=>{if(!h.tokens?.accessToken||!h.isAuthenticated)return null;try{let s=X(h.tokens.accessToken);if(s&&s.sub&&s.email&&s.subscriber){let n={_id:s.sub,email:s.email,subscriberKey:s.subscriber};return Object.keys(s).forEach(a=>{["sub","email","subscriber"].includes(a)||(n[a]=s[a])}),n}}catch(s){console.error("Error decoding JWT token for sessionData:",s)}return null},[h.tokens?.accessToken,h.isAuthenticated]),N={...h,sessionData:T,config:S},c={enabled:t,maxNotifications:i.maxNotifications||5,defaultAutoHideDuration:i.defaultAutoHideDuration||6e3,position:i.position||{vertical:"top",horizontal:"right"}};return k(Z.Provider,{value:N,children:o})}function Qe(o){let r={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 k(W,{...r,children:k(Te,{...o})})}function ye(){let o=he(Z);if(o===void 0)throw new Error("useSessionContext must be used within a SessionProvider");return o}function er(){let o=ye();return o.isInitialized?b("div",{style:{padding:"10px",margin:"10px",border:"1px solid #ccc",borderRadius:"4px",fontSize:"12px",fontFamily:"monospace"},children:[k("h4",{children:"Session Debug Info"}),b("div",{children:[k("strong",{children:"Authenticated:"})," ",o.isAuthenticated?"Yes":"No"]}),b("div",{children:[k("strong",{children:"Loading:"})," ",o.isLoading?"Yes":"No"]}),b("div",{children:[k("strong",{children:"Error:"})," ",o.error||"None"]}),o.tokens&&b(ke,{children:[b("div",{children:[k("strong",{children:"Access Token:"})," ",o.tokens.accessToken.substring(0,20),"..."]}),b("div",{children:[k("strong",{children:"Refresh Token:"})," ",o.tokens.refreshToken.substring(0,20),"..."]}),b("div",{children:[k("strong",{children:"Access Expires In:"})," ",Math.round(o.expiresIn/1e3/60)," minutes"]}),b("div",{children:[k("strong",{children:"Refresh Expires In:"})," ",Math.round(o.refreshExpiresIn/1e3/60/60)," hours"]}),b("div",{children:[k("strong",{children:"Expiring Soon:"})," ",o.isExpiringSoon?"Yes":"No"]})]})]}):k("div",{children:"Session not initialized"})}import{useState as F,useEffect as q,useCallback as Q,useRef as M}from"react";import Ee from"@nocios/crudify-browser";var nr=(o={})=>{let{autoFetch:r=!0,retryOnError:e=!1,maxRetries:t=3}=o,[i,u]=F(null),[E,h]=F(!1),[S,T]=F(null),[N,c]=F({}),s=M(null),n=M(!0),a=M(0),d=M(0),m=Q(()=>{u(null),T(null),h(!1),c({})},[]),p=Q(async()=>{let x=V();if(!x){n.current&&(T("No user email available"),h(!1));return}s.current&&s.current.abort();let I=new AbortController;s.current=I;let L=++a.current;try{n.current&&(h(!0),T(null));let A=await Ee.readItems("users",{filter:{email:x},pagination:{limit:1}});if(L===a.current&&n.current&&!I.signal.aborted)if(A.success&&A.data&&A.data.length>0){let f=A.data[0];u(f);let H={fullProfile:f,totalFields:Object.keys(f).length,displayData:{id:f.id,email:f.email,username:f.username,firstName:f.firstName,lastName:f.lastName,fullName:f.fullName||`${f.firstName||""} ${f.lastName||""}`.trim(),role:f.role,permissions:f.permissions||[],isActive:f.isActive,lastLogin:f.lastLogin,createdAt:f.createdAt,updatedAt:f.updatedAt,...Object.keys(f).filter(P=>!["id","email","username","firstName","lastName","fullName","role","permissions","isActive","lastLogin","createdAt","updatedAt"].includes(P)).reduce((P,z)=>({...P,[z]:f[z]}),{})}};c(H),T(null),d.current=0}else T("User profile not found"),u(null),c({})}catch(A){if(L===a.current&&n.current){let f=A;if(f.name==="AbortError")return;e&&d.current<t&&(f.message?.includes("Network Error")||f.message?.includes("Failed to fetch"))?(d.current++,setTimeout(()=>{n.current&&p()},1e3*d.current)):(T("Failed to load user profile"),u(null),c({}))}}finally{L===a.current&&n.current&&h(!1),s.current===I&&(s.current=null)}},[e,t]);return q(()=>{r&&p()},[r,p]),q(()=>(n.current=!0,()=>{n.current=!1,s.current&&(s.current.abort(),s.current=null)}),[]),{userProfile:i,loading:E,error:S,extendedData:N,refreshProfile:p,clearProfile:m}};export{g as a,C as b,Y as c,W as d,$ as e,Qe as f,ye as g,er as h,nr as i};
@@ -1 +1 @@
1
- import{e as $,g as D}from"./chunk-IO4RPCSZ.mjs";import{useState as K,useEffect as z,useCallback as j,useRef as F}from"react";import Q from"@nocios/crudify-browser";var G=(S={})=>{let{autoFetch:c=!0,retryOnError:N=!1,maxRetries:g=3}=S,{isAuthenticated:T,isInitialized:I,sessionData:a,tokens:R}=D(),[E,d]=K(null),[y,O]=K(!1),[A,p]=K(null),u=F(null),o=F(!0),m=F(0),l=F(0),L=j(()=>a&&(a.email||a["cognito:username"])||null,[a]),P=j(()=>{d(null),p(null),O(!1),l.current=0},[]),w=j(async()=>{let x=L();if(!x){o.current&&(p("No user email available from session data"),O(!1));return}if(!I){o.current&&(p("Session not initialized"),O(!1));return}u.current&&u.current.abort();let e=new AbortController;u.current=e;let i=++m.current;try{o.current&&(O(!0),p(null));let r=await Q.readItems("users",{filter:{email:x},pagination:{limit:1}});if(i===m.current&&o.current&&!e.signal.aborted){let t=null;if(r.success){if(Array.isArray(r.data)&&r.data.length>0)t=r.data[0];else if(r.data?.response?.data)try{let s=r.data.response.data,n=typeof s=="string"?JSON.parse(s):s;n&&n.items&&Array.isArray(n.items)&&n.items.length>0&&(t=n.items[0])}catch{}else if(r.data&&typeof r.data=="object")r.data.items&&Array.isArray(r.data.items)&&r.data.items.length>0&&(t=r.data.items[0]);else if(r.data?.data?.response?.data)try{let s=r.data.data.response.data,n=typeof s=="string"?JSON.parse(s):s;n&&n.items&&Array.isArray(n.items)&&n.items.length>0&&(t=n.items[0])}catch{}}t?(d(t),p(null),l.current=0):(p("User profile not found in database"),d(null))}}catch(r){if(i===m.current&&o.current){let t=r;if(t.name==="AbortError")return;N&&l.current<g&&(t.message?.includes("Network Error")||t.message?.includes("Failed to fetch"))?(l.current++,setTimeout(()=>{o.current&&w()},1e3*l.current)):(p("Failed to load user profile from database"),d(null))}}finally{i===m.current&&o.current&&O(!1),u.current===e&&(u.current=null)}},[I,L,N,g]);return z(()=>{c&&T&&I?w():T||P()},[c,T,I,w,P]),z(()=>(o.current=!0,()=>{o.current=!1,u.current&&(u.current.abort(),u.current=null)}),[]),{user:{session:a,data:E},loading:y,error:A,refreshProfile:w,clearProfile:P}};import{useCallback as W}from"react";var ee=()=>{let{isAuthenticated:S,isLoading:c,isInitialized:N,tokens:g,error:T,sessionData:I,login:a,logout:R,refreshTokens:E,clearError:d,getTokenInfo:y,isExpiringSoon:O,expiresIn:A,refreshExpiresIn:p}=D(),u=W(m=>{m?console.warn("useAuth.setToken() is deprecated. Use login() method instead for better security."):R()},[R]),o=g?.expiresAt?new Date(g.expiresAt):null;return{isAuthenticated:S,loading:c,error:T,token:g?.accessToken||null,user:I,tokenExpiration:o,setToken:u,logout:R,refreshToken:E,login:a,isExpiringSoon:O,expiresIn:A,refreshExpiresIn:p,getTokenInfo:y,clearError:d}};import{useCallback as h}from"react";import U from"@nocios/crudify-browser";var oe=()=>{let{isInitialized:S,isLoading:c,error:N,isAuthenticated:g,login:T}=D(),I=h(()=>S&&!c&&!N,[S,c,N]),a=h(async()=>new Promise((o,m)=>{let l=()=>{I()?o():N?m(new Error(N)):setTimeout(l,100)};l()}),[I,N]),R=h(async()=>{if(!I())throw new Error("System not ready. Check isInitialized, isLoading, and error states.")},[I]),E=h(async(o,m,l)=>(await R(),await U.readItems(o,m||{},l)),[R]),d=h(async(o,m,l)=>(await R(),await U.readItem(o,m,l)),[R]),y=h(async(o,m,l)=>(await R(),await U.createItem(o,m,l)),[R]),O=h(async(o,m,l)=>(await R(),await U.updateItem(o,m,l)),[R]),A=h(async(o,m,l)=>(await R(),await U.deleteItem(o,m,l)),[R]),p=h(async(o,m)=>(await R(),await U.transaction(o,m)),[R]),u=h(async(o,m)=>{try{let l=await T(o,m);return l.success?{success:!0,data:l.tokens}:{success:!1,errors:l.error||"Login failed"}}catch(l){return{success:!1,errors:l instanceof Error?l.message:"Login failed"}}},[T]);return{readItems:E,readItem:d,createItem:y,updateItem:O,deleteItem:A,transaction:p,login:u,isInitialized:S,isInitializing:c,initializationError:N,isReady:I,waitForReady:a}};import{useCallback as C}from"react";import b from"@nocios/crudify-browser";var Y={INVALID_CREDENTIALS:"warning",UNAUTHORIZED:"warning",INVALID_API_KEY:"error",USER_NOT_FOUND:"warning",USER_NOT_ACTIVE:"warning",NO_PERMISSION:"warning",ITEM_NOT_FOUND:"info",NOT_FOUND:"info",IN_USE:"warning",FIELD_ERROR:"warning",BAD_REQUEST:"warning",INTERNAL_SERVER_ERROR:"error",DATABASE_CONNECTION_ERROR:"error",INVALID_CONFIGURATION:"error",UNKNOWN_OPERATION:"error",TOO_MANY_REQUESTS:"warning"},v={INVALID_CREDENTIALS:"errors.auth.INVALID_CREDENTIALS",UNAUTHORIZED:"errors.auth.UNAUTHORIZED",INVALID_API_KEY:"errors.auth.INVALID_API_KEY",USER_NOT_FOUND:"errors.auth.USER_NOT_FOUND",USER_NOT_ACTIVE:"errors.auth.USER_NOT_ACTIVE",NO_PERMISSION:"errors.auth.NO_PERMISSION",ITEM_NOT_FOUND:"errors.data.ITEM_NOT_FOUND",NOT_FOUND:"errors.data.NOT_FOUND",IN_USE:"errors.data.IN_USE",FIELD_ERROR:"errors.data.FIELD_ERROR",BAD_REQUEST:"errors.data.BAD_REQUEST",INTERNAL_SERVER_ERROR:"errors.system.INTERNAL_SERVER_ERROR",DATABASE_CONNECTION_ERROR:"errors.system.DATABASE_CONNECTION_ERROR",INVALID_CONFIGURATION:"errors.system.INVALID_CONFIGURATION",UNKNOWN_OPERATION:"errors.system.UNKNOWN_OPERATION",TOO_MANY_REQUESTS:"errors.system.TOO_MANY_REQUESTS"},le=(S={})=>{let{showNotification:c}=$(),{showSuccessNotifications:N=!1,showErrorNotifications:g=!0,customErrorMessages:T={},defaultErrorMessage:I="Ha ocurrido un error inesperado",autoHideDuration:a=6e3,appStructure:R=[],translateFn:E=e=>e}=S,d=C(e=>!(!e.success&&e.errors&&(Object.keys(e.errors).some(r=>r!=="_error"&&r!=="_graphql"&&r!=="_transaction")||e.errors._transaction?.includes("ONE_OR_MORE_OPERATIONS_FAILED")||e.errors._error?.includes("TOO_MANY_REQUESTS"))||!e.success&&e.data?.response?.status==="TOO_MANY_REQUESTS"),[]),y=C((e,i)=>{let r=E(e);return r===e?i||E("error.unknown"):r},[E]),O=C(e=>["create","update","delete"].includes(e),[]),A=C((e,i)=>N?O(e)&&i?!0:R.some(r=>r.key===e):!1,[N,R,O]),p=C((e,i,r)=>{let t=r?.key&&typeof r.key=="string"?r.key:e,s=`action.onSuccess.${t}`,n=y(s);if(n!==E("error.unknown")){if(O(t)&&i){let f=`action.${i}Singular`,_=y(f);if(_!==E("error.unknown"))return E(s,{item:_});{let M=`action.onSuccess.${t}WithoutItem`,k=y(M);return k!==E("error.unknown")?k:n}}return n}return E("success.transaction")},[y,E,O]),u=C(e=>{if(e.errorCode&&T[e.errorCode])return T[e.errorCode];if(e.errorCode&&v[e.errorCode])return y(v[e.errorCode]);if(e.errorCode){let i=[`errors.auth.${e.errorCode}`,`errors.data.${e.errorCode}`,`errors.system.${e.errorCode}`,`errors.${e.errorCode}`];for(let r of i){let t=y(r);if(t!==E("error.unknown"))return t}}if(typeof e.data=="string"&&e.data.startsWith("errors.")){let i=y(e.data);if(i!==E("error.unknown"))return i}if(e.errors&&Object.keys(e.errors).length>0){let i=Object.keys(e.errors);if(i.length===1&&i[0]==="_transaction"){let r=e.errors._transaction;if(r?.includes("ONE_OR_MORE_OPERATIONS_FAILED"))return"";if(Array.isArray(r)&&r.length>0){let t=r[0];if(typeof t=="string"&&t!=="ONE_OR_MORE_OPERATIONS_FAILED")try{let s=JSON.parse(t);if(Array.isArray(s)&&s.length>0){let n=s[0];if(n?.response?.errorCode){let f=n.response.errorCode;if(v[f])return y(v[f]);let _=[`errors.auth.${f}`,`errors.data.${f}`,`errors.system.${f}`,`errors.${f}`];for(let M of _){let k=y(M);if(k!==y("error.unknown"))return k}}if(n?.response?.data)return n.response.data}if(s?.response?.message){let n=s.response.message.toLowerCase();return n.includes("expired")?y("resetPassword.linkExpired","El enlace ha expirado"):n.includes("invalid")?y("resetPassword.invalidCode","C\xF3digo inv\xE1lido"):s.response.message}}catch{return t.toLowerCase().includes("expired")?y("resetPassword.linkExpired","El enlace ha expirado"):t.toLowerCase().includes("invalid")?y("resetPassword.invalidCode","C\xF3digo inv\xE1lido"):t}}return y("error.transaction","Error en la operaci\xF3n")}if(i.length===1&&i[0]==="_error"){let r=e.errors._error;return Array.isArray(r)?r[0]:String(r)}return i.length===1&&i[0]==="_graphql"?y("errors.system.DATABASE_CONNECTION_ERROR"):`${y("errors.data.FIELD_ERROR")}: ${i.join(", ")}`}return I||E("error.unknown")},[T,I,E,y]),o=C(e=>e.errorCode&&Y[e.errorCode]?Y[e.errorCode]:"error",[]),m=C(async(e,i,r)=>{let t=await b.createItem(e,i,r);if(!t.success&&g&&d(t)){let s=u(t),n=o(t);c(s,n,{autoHideDuration:a})}else if(t.success){let s=r?.actionConfig,n=s?.key||"create",f=s?.moduleKey||e;if(A(n,f)){let _=p(n,f,s);c(_,"success",{autoHideDuration:a})}}return t},[g,A,c,u,o,p,a,d]),l=C(async(e,i,r)=>{let t=await b.updateItem(e,i,r);if(!t.success&&g&&d(t)){let s=u(t),n=o(t);c(s,n,{autoHideDuration:a})}else if(t.success){let s=r?.actionConfig,n=s?.key||"update",f=s?.moduleKey||e;if(A(n,f)){let _=p(n,f,s);c(_,"success",{autoHideDuration:a})}}return t},[g,A,c,u,o,p,a,d]),L=C(async(e,i,r)=>{let t=await b.deleteItem(e,i,r);if(!t.success&&g&&d(t)){let s=u(t),n=o(t);c(s,n,{autoHideDuration:a})}else if(t.success){let s=r?.actionConfig,n=s?.key||"delete",f=s?.moduleKey||e;if(A(n,f)){let _=p(n,f,s);c(_,"success",{autoHideDuration:a})}}return t},[g,A,c,u,o,p,a,d]),P=C(async(e,i,r)=>{let t=await b.readItem(e,i,r);if(!t.success&&g&&d(t)){let s=u(t),n=o(t);c(s,n,{autoHideDuration:a})}return t},[g,c,u,o,a,d]),w=C(async(e,i,r)=>{let t=await b.readItems(e,i,r);if(!t.success&&g&&d(t)){let s=u(t),n=o(t);c(s,n,{autoHideDuration:a})}return t},[g,c,u,o,a,d]),V=C(async(e,i)=>{let r=await b.transaction(e,i),t=i?.skipNotifications===!0;if(!t&&!r.success&&g&&d(r)){let s=u(r),n=o(r);c(s,n,{autoHideDuration:a})}else if(!t&&r.success){let s="transaction",n,f=null;if(i?.actionConfig?(f=i.actionConfig,s=f.key,n=f.moduleKey):Array.isArray(e)&&e.length>0&&e[0].operation&&(s=e[0].operation,f=R.find(_=>_.key===s),f&&(n=f.moduleKey)),A(s,n)){let _=p(s,n,f);c(_,"success",{autoHideDuration:a})}}return r},[g,A,c,u,o,p,a,d,R]),x=C((e,i)=>{if(!e.success&&g&&d(e)){let r=u(e),t=o(e);c(r,t,{autoHideDuration:a})}else e.success&&N&&i&&c(i,"success",{autoHideDuration:a});return e},[g,N,c,u,o,a,d,E]);return{createItem:m,updateItem:l,deleteItem:L,readItem:P,readItems:w,transaction:V,handleResponse:x,getErrorMessage:u,getErrorSeverity:o,shouldShowNotification:d}};export{G as a,ee as b,oe as c,le as d};
1
+ import{e as $,g as D}from"./chunk-CTDQEJAU.mjs";import{useState as K,useEffect as z,useCallback as j,useRef as F}from"react";import Q from"@nocios/crudify-browser";var G=(S={})=>{let{autoFetch:c=!0,retryOnError:N=!1,maxRetries:g=3}=S,{isAuthenticated:T,isInitialized:I,sessionData:a,tokens:R}=D(),[E,d]=K(null),[y,O]=K(!1),[A,p]=K(null),u=F(null),o=F(!0),m=F(0),l=F(0),L=j(()=>a&&(a.email||a["cognito:username"])||null,[a]),P=j(()=>{d(null),p(null),O(!1),l.current=0},[]),w=j(async()=>{let x=L();if(!x){o.current&&(p("No user email available from session data"),O(!1));return}if(!I){o.current&&(p("Session not initialized"),O(!1));return}u.current&&u.current.abort();let e=new AbortController;u.current=e;let i=++m.current;try{o.current&&(O(!0),p(null));let r=await Q.readItems("users",{filter:{email:x},pagination:{limit:1}});if(i===m.current&&o.current&&!e.signal.aborted){let t=null;if(r.success){if(Array.isArray(r.data)&&r.data.length>0)t=r.data[0];else if(r.data?.response?.data)try{let s=r.data.response.data,n=typeof s=="string"?JSON.parse(s):s;n&&n.items&&Array.isArray(n.items)&&n.items.length>0&&(t=n.items[0])}catch{}else if(r.data&&typeof r.data=="object")r.data.items&&Array.isArray(r.data.items)&&r.data.items.length>0&&(t=r.data.items[0]);else if(r.data?.data?.response?.data)try{let s=r.data.data.response.data,n=typeof s=="string"?JSON.parse(s):s;n&&n.items&&Array.isArray(n.items)&&n.items.length>0&&(t=n.items[0])}catch{}}t?(d(t),p(null),l.current=0):(p("User profile not found in database"),d(null))}}catch(r){if(i===m.current&&o.current){let t=r;if(t.name==="AbortError")return;N&&l.current<g&&(t.message?.includes("Network Error")||t.message?.includes("Failed to fetch"))?(l.current++,setTimeout(()=>{o.current&&w()},1e3*l.current)):(p("Failed to load user profile from database"),d(null))}}finally{i===m.current&&o.current&&O(!1),u.current===e&&(u.current=null)}},[I,L,N,g]);return z(()=>{c&&T&&I?w():T||P()},[c,T,I,w,P]),z(()=>(o.current=!0,()=>{o.current=!1,u.current&&(u.current.abort(),u.current=null)}),[]),{user:{session:a,data:E},loading:y,error:A,refreshProfile:w,clearProfile:P}};import{useCallback as W}from"react";var ee=()=>{let{isAuthenticated:S,isLoading:c,isInitialized:N,tokens:g,error:T,sessionData:I,login:a,logout:R,refreshTokens:E,clearError:d,getTokenInfo:y,isExpiringSoon:O,expiresIn:A,refreshExpiresIn:p}=D(),u=W(m=>{m?console.warn("useAuth.setToken() is deprecated. Use login() method instead for better security."):R()},[R]),o=g?.expiresAt?new Date(g.expiresAt):null;return{isAuthenticated:S,loading:c,error:T,token:g?.accessToken||null,user:I,tokenExpiration:o,setToken:u,logout:R,refreshToken:E,login:a,isExpiringSoon:O,expiresIn:A,refreshExpiresIn:p,getTokenInfo:y,clearError:d}};import{useCallback as h}from"react";import U from"@nocios/crudify-browser";var oe=()=>{let{isInitialized:S,isLoading:c,error:N,isAuthenticated:g,login:T}=D(),I=h(()=>S&&!c&&!N,[S,c,N]),a=h(async()=>new Promise((o,m)=>{let l=()=>{I()?o():N?m(new Error(N)):setTimeout(l,100)};l()}),[I,N]),R=h(async()=>{if(!I())throw new Error("System not ready. Check isInitialized, isLoading, and error states.")},[I]),E=h(async(o,m,l)=>(await R(),await U.readItems(o,m||{},l)),[R]),d=h(async(o,m,l)=>(await R(),await U.readItem(o,m,l)),[R]),y=h(async(o,m,l)=>(await R(),await U.createItem(o,m,l)),[R]),O=h(async(o,m,l)=>(await R(),await U.updateItem(o,m,l)),[R]),A=h(async(o,m,l)=>(await R(),await U.deleteItem(o,m,l)),[R]),p=h(async(o,m)=>(await R(),await U.transaction(o,m)),[R]),u=h(async(o,m)=>{try{let l=await T(o,m);return l.success?{success:!0,data:l.tokens}:{success:!1,errors:l.error||"Login failed"}}catch(l){return{success:!1,errors:l instanceof Error?l.message:"Login failed"}}},[T]);return{readItems:E,readItem:d,createItem:y,updateItem:O,deleteItem:A,transaction:p,login:u,isInitialized:S,isInitializing:c,initializationError:N,isReady:I,waitForReady:a}};import{useCallback as C}from"react";import b from"@nocios/crudify-browser";var Y={INVALID_CREDENTIALS:"warning",UNAUTHORIZED:"warning",INVALID_API_KEY:"error",USER_NOT_FOUND:"warning",USER_NOT_ACTIVE:"warning",NO_PERMISSION:"warning",ITEM_NOT_FOUND:"info",NOT_FOUND:"info",IN_USE:"warning",FIELD_ERROR:"warning",BAD_REQUEST:"warning",INTERNAL_SERVER_ERROR:"error",DATABASE_CONNECTION_ERROR:"error",INVALID_CONFIGURATION:"error",UNKNOWN_OPERATION:"error",TOO_MANY_REQUESTS:"warning"},v={INVALID_CREDENTIALS:"errors.auth.INVALID_CREDENTIALS",UNAUTHORIZED:"errors.auth.UNAUTHORIZED",INVALID_API_KEY:"errors.auth.INVALID_API_KEY",USER_NOT_FOUND:"errors.auth.USER_NOT_FOUND",USER_NOT_ACTIVE:"errors.auth.USER_NOT_ACTIVE",NO_PERMISSION:"errors.auth.NO_PERMISSION",ITEM_NOT_FOUND:"errors.data.ITEM_NOT_FOUND",NOT_FOUND:"errors.data.NOT_FOUND",IN_USE:"errors.data.IN_USE",FIELD_ERROR:"errors.data.FIELD_ERROR",BAD_REQUEST:"errors.data.BAD_REQUEST",INTERNAL_SERVER_ERROR:"errors.system.INTERNAL_SERVER_ERROR",DATABASE_CONNECTION_ERROR:"errors.system.DATABASE_CONNECTION_ERROR",INVALID_CONFIGURATION:"errors.system.INVALID_CONFIGURATION",UNKNOWN_OPERATION:"errors.system.UNKNOWN_OPERATION",TOO_MANY_REQUESTS:"errors.system.TOO_MANY_REQUESTS"},le=(S={})=>{let{showNotification:c}=$(),{showSuccessNotifications:N=!1,showErrorNotifications:g=!0,customErrorMessages:T={},defaultErrorMessage:I="Ha ocurrido un error inesperado",autoHideDuration:a=6e3,appStructure:R=[],translateFn:E=e=>e}=S,d=C(e=>!(!e.success&&e.errors&&(Object.keys(e.errors).some(r=>r!=="_error"&&r!=="_graphql"&&r!=="_transaction")||e.errors._transaction?.includes("ONE_OR_MORE_OPERATIONS_FAILED")||e.errors._error?.includes("TOO_MANY_REQUESTS"))||!e.success&&e.data?.response?.status==="TOO_MANY_REQUESTS"),[]),y=C((e,i)=>{let r=E(e);return r===e?i||E("error.unknown"):r},[E]),O=C(e=>["create","update","delete"].includes(e),[]),A=C((e,i)=>N?O(e)&&i?!0:R.some(r=>r.key===e):!1,[N,R,O]),p=C((e,i,r)=>{let t=r?.key&&typeof r.key=="string"?r.key:e,s=`action.onSuccess.${t}`,n=y(s);if(n!==E("error.unknown")){if(O(t)&&i){let f=`action.${i}Singular`,_=y(f);if(_!==E("error.unknown"))return E(s,{item:_});{let M=`action.onSuccess.${t}WithoutItem`,k=y(M);return k!==E("error.unknown")?k:n}}return n}return E("success.transaction")},[y,E,O]),u=C(e=>{if(e.errorCode&&T[e.errorCode])return T[e.errorCode];if(e.errorCode&&v[e.errorCode])return y(v[e.errorCode]);if(e.errorCode){let i=[`errors.auth.${e.errorCode}`,`errors.data.${e.errorCode}`,`errors.system.${e.errorCode}`,`errors.${e.errorCode}`];for(let r of i){let t=y(r);if(t!==E("error.unknown"))return t}}if(typeof e.data=="string"&&e.data.startsWith("errors.")){let i=y(e.data);if(i!==E("error.unknown"))return i}if(e.errors&&Object.keys(e.errors).length>0){let i=Object.keys(e.errors);if(i.length===1&&i[0]==="_transaction"){let r=e.errors._transaction;if(r?.includes("ONE_OR_MORE_OPERATIONS_FAILED"))return"";if(Array.isArray(r)&&r.length>0){let t=r[0];if(typeof t=="string"&&t!=="ONE_OR_MORE_OPERATIONS_FAILED")try{let s=JSON.parse(t);if(Array.isArray(s)&&s.length>0){let n=s[0];if(n?.response?.errorCode){let f=n.response.errorCode;if(v[f])return y(v[f]);let _=[`errors.auth.${f}`,`errors.data.${f}`,`errors.system.${f}`,`errors.${f}`];for(let M of _){let k=y(M);if(k!==y("error.unknown"))return k}}if(n?.response?.data)return n.response.data}if(s?.response?.message){let n=s.response.message.toLowerCase();return n.includes("expired")?y("resetPassword.linkExpired","El enlace ha expirado"):n.includes("invalid")?y("resetPassword.invalidCode","C\xF3digo inv\xE1lido"):s.response.message}}catch{return t.toLowerCase().includes("expired")?y("resetPassword.linkExpired","El enlace ha expirado"):t.toLowerCase().includes("invalid")?y("resetPassword.invalidCode","C\xF3digo inv\xE1lido"):t}}return y("error.transaction","Error en la operaci\xF3n")}if(i.length===1&&i[0]==="_error"){let r=e.errors._error;return Array.isArray(r)?r[0]:String(r)}return i.length===1&&i[0]==="_graphql"?y("errors.system.DATABASE_CONNECTION_ERROR"):`${y("errors.data.FIELD_ERROR")}: ${i.join(", ")}`}return I||E("error.unknown")},[T,I,E,y]),o=C(e=>e.errorCode&&Y[e.errorCode]?Y[e.errorCode]:"error",[]),m=C(async(e,i,r)=>{let t=await b.createItem(e,i,r);if(!t.success&&g&&d(t)){let s=u(t),n=o(t);c(s,n,{autoHideDuration:a})}else if(t.success){let s=r?.actionConfig,n=s?.key||"create",f=s?.moduleKey||e;if(A(n,f)){let _=p(n,f,s);c(_,"success",{autoHideDuration:a})}}return t},[g,A,c,u,o,p,a,d]),l=C(async(e,i,r)=>{let t=await b.updateItem(e,i,r);if(!t.success&&g&&d(t)){let s=u(t),n=o(t);c(s,n,{autoHideDuration:a})}else if(t.success){let s=r?.actionConfig,n=s?.key||"update",f=s?.moduleKey||e;if(A(n,f)){let _=p(n,f,s);c(_,"success",{autoHideDuration:a})}}return t},[g,A,c,u,o,p,a,d]),L=C(async(e,i,r)=>{let t=await b.deleteItem(e,i,r);if(!t.success&&g&&d(t)){let s=u(t),n=o(t);c(s,n,{autoHideDuration:a})}else if(t.success){let s=r?.actionConfig,n=s?.key||"delete",f=s?.moduleKey||e;if(A(n,f)){let _=p(n,f,s);c(_,"success",{autoHideDuration:a})}}return t},[g,A,c,u,o,p,a,d]),P=C(async(e,i,r)=>{let t=await b.readItem(e,i,r);if(!t.success&&g&&d(t)){let s=u(t),n=o(t);c(s,n,{autoHideDuration:a})}return t},[g,c,u,o,a,d]),w=C(async(e,i,r)=>{let t=await b.readItems(e,i,r);if(!t.success&&g&&d(t)){let s=u(t),n=o(t);c(s,n,{autoHideDuration:a})}return t},[g,c,u,o,a,d]),V=C(async(e,i)=>{let r=await b.transaction(e,i),t=i?.skipNotifications===!0;if(!t&&!r.success&&g&&d(r)){let s=u(r),n=o(r);c(s,n,{autoHideDuration:a})}else if(!t&&r.success){let s="transaction",n,f=null;if(i?.actionConfig?(f=i.actionConfig,s=f.key,n=f.moduleKey):Array.isArray(e)&&e.length>0&&e[0].operation&&(s=e[0].operation,f=R.find(_=>_.key===s),f&&(n=f.moduleKey)),A(s,n)){let _=p(s,n,f);c(_,"success",{autoHideDuration:a})}}return r},[g,A,c,u,o,p,a,d,R]),x=C((e,i)=>{if(!e.success&&g&&d(e)){let r=u(e),t=o(e);c(r,t,{autoHideDuration:a})}else e.success&&N&&i&&c(i,"success",{autoHideDuration:a});return e},[g,N,c,u,o,a,d,E]);return{createItem:m,updateItem:l,deleteItem:L,readItem:P,readItems:w,transaction:V,handleResponse:x,getErrorMessage:u,getErrorSeverity:o,shouldShowNotification:d}};export{G as a,ee as b,oe as c,le as d};
@@ -1 +1 @@
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 _chunkAT74WV5Wjs = require('./chunk-AT74WV5W.js');var _cryptojs = require('crypto-js'); var _cryptojs2 = _interopRequireDefault(_cryptojs);var l=class l{static setStorageType(r){l.storageType=r}static generateEncryptionKey(){let r=[navigator.userAgent,navigator.language,navigator.platform,screen.width,screen.height,Date.now().toString(),Math.random().toString(36)].join("|");return _cryptojs2.default.SHA256(r).toString()}static getEncryptionKey(){if(l.encryptionKey)return l.encryptionKey;let r=window.localStorage;if(!r)return l.encryptionKey=l.generateEncryptionKey(),l.encryptionKey;try{let e=r.getItem(l.ENCRYPTION_KEY_STORAGE);return(!e||e.length<32)&&(e=l.generateEncryptionKey(),r.setItem(l.ENCRYPTION_KEY_STORAGE,e)),l.encryptionKey=e,e}catch (e2){return console.warn("Crudify: Cannot persist encryption key, using temporary key"),l.encryptionKey=l.generateEncryptionKey(),l.encryptionKey}}static isStorageAvailable(r){try{let e=window[r],t="__storage_test__";return e.setItem(t,"test"),e.removeItem(t),!0}catch (e3){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(r){try{let e=l.getEncryptionKey();return _cryptojs2.default.AES.encrypt(r,e).toString()}catch(e){return console.error("Crudify: Encryption failed",e),r}}static decrypt(r){try{let e=l.getEncryptionKey();return _cryptojs2.default.AES.decrypt(r,e).toString(_cryptojs2.default.enc.Utf8)||r}catch(e){return console.error("Crudify: Decryption failed",e),r}}static saveTokens(r){let e=l.getStorage();if(e)try{let t={accessToken:r.accessToken,refreshToken:r.refreshToken,expiresAt:r.expiresAt,refreshExpiresAt:r.refreshExpiresAt,savedAt:Date.now()},i=l.encrypt(JSON.stringify(t));e.setItem(l.TOKEN_KEY,i),console.debug("Crudify: Tokens saved successfully")}catch(t){console.error("Crudify: Failed to save tokens",t)}}static getTokens(){let r=l.getStorage();if(!r)return null;try{let e=r.getItem(l.TOKEN_KEY);if(!e)return null;let t=l.decrypt(e),i=JSON.parse(t);return!i.accessToken||!i.refreshToken||!i.expiresAt||!i.refreshExpiresAt?(console.warn("Crudify: Incomplete token data found, clearing storage"),l.clearTokens(),null):Date.now()>=i.refreshExpiresAt?(console.info("Crudify: Refresh token expired, clearing storage"),l.clearTokens(),null):{accessToken:i.accessToken,refreshToken:i.refreshToken,expiresAt:i.expiresAt,refreshExpiresAt:i.refreshExpiresAt}}catch(e){return console.error("Crudify: Failed to retrieve tokens",e),l.clearTokens(),null}}static clearTokens(){let r=l.getStorage();if(r)try{r.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 r=window.localStorage;r&&r.removeItem(l.ENCRYPTION_KEY_STORAGE),console.info("Crudify: Encryption key rotated successfully")}catch(r){console.error("Crudify: Failed to rotate encryption key",r)}}static hasValidTokens(){return l.getTokens()!==null}static getExpirationInfo(){let r=l.getTokens();if(!r)return null;let e=Date.now();return{accessExpired:e>=r.expiresAt,refreshExpired:e>=r.refreshExpiresAt,accessExpiresIn:Math.max(0,r.expiresAt-e),refreshExpiresIn:Math.max(0,r.refreshExpiresAt-e)}}static updateAccessToken(r,e){let t=l.getTokens();if(!t){console.warn("Crudify: Cannot update access token, no existing tokens found");return}l.saveTokens({...t,accessToken:r,expiresAt:e})}static subscribeToChanges(r){let e=t=>{if(t.key===l.TOKEN_KEY){if(t.newValue===null){console.debug("Crudify: Tokens removed in another tab"),r(null);return}if(t.newValue){console.debug("Crudify: Tokens updated in another tab");let i=l.getTokens();r(i)}}};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 g=l;var _crudifybrowser = require('@nocios/crudify-browser'); var _crudifybrowser2 = _interopRequireDefault(_crudifybrowser);var C=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(r={}){if(this.initialized){console.warn("SessionManager: Already initialized");return}this.config={storageType:"localStorage",autoRestore:!0,enableLogging:!1,...r},g.setStorageType(this.config.storageType||"localStorage"),this.config.enableLogging,_crudifybrowser2.default.setTokenInvalidationCallback(()=>{this.log("\u{1F514} Tokens invalidated by crudify-core"),_chunkAT74WV5Wjs.f.emit("SESSION_EXPIRED",{message:"Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente.",source:"crudify-core.clearTokensAndRefreshState"})}),this.config.autoRestore&&await this.restoreSession(),this.initialized=!0,this.log("SessionManager initialized successfully")}async login(r,e){try{this.log("Attempting login...");let t=await _crudifybrowser2.default.login(r,e);if(!t.success)return this.log("Login failed:",t.errors),{success:!1,error:this.formatError(t.errors),rawResponse:t};let i={accessToken:t.data.token,refreshToken:t.data.refreshToken,expiresAt:t.data.expiresAt,refreshExpiresAt:t.data.refreshExpiresAt};return g.saveTokens(i),this.lastActivityTime=Date.now(),this.log("Login successful, tokens saved"),_optionalChain([this, 'access', _2 => _2.config, 'access', _3 => _3.onLoginSuccess, 'optionalCall', _4 => _4(i)]),{success:!0,tokens:i,data:t.data}}catch(t){return this.log("Login error:",t),{success:!1,error:t instanceof Error?t.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(r){this.log("Logout error:",r),g.clearTokens()}}async restoreSession(){try{this.log("Attempting to restore session...");let r=g.getTokens();if(!r)return this.log("No valid tokens found in storage"),!1;if(Date.now()>=r.refreshExpiresAt)return this.log("Refresh token expired, clearing storage"),g.clearTokens(),!1;if(_crudifybrowser2.default.setTokens({accessToken:r.accessToken,refreshToken:r.refreshToken,expiresAt:r.expiresAt,refreshExpiresAt:r.refreshExpiresAt}),_crudifybrowser2.default.getTokenData().isValid===!1){if(this.log("Restored access token is invalid or expired"),Date.now()<r.refreshExpiresAt&&(this.log("Access token expired but refresh is valid, attempting refresh..."),await this.refreshTokens())){this.log("Session restored successfully via token refresh");let i=g.getTokens();return i&&_optionalChain([this, 'access', _8 => _8.config, 'access', _9 => _9.onSessionRestored, 'optionalCall', _10 => _10(i)]),!0}return g.clearTokens(),await _crudifybrowser2.default.logout(),!1}return this.log("Session restored successfully"),this.lastActivityTime=Date.now(),_optionalChain([this, 'access', _11 => _11.config, 'access', _12 => _12.onSessionRestored, 'optionalCall', _13 => _13(r)]),!0}catch(r){return this.log("Session restore error:",r),g.clearTokens(),await _crudifybrowser2.default.logout(),!1}}isAuthenticated(){return _crudifybrowser2.default.isLogin()||g.hasValidTokens()}getTokenInfo(){let r=_crudifybrowser2.default.getTokenData(),e=g.getExpirationInfo();return{isLoggedIn:this.isAuthenticated(),crudifyTokens:r,storageInfo:e,hasValidTokens:g.hasValidTokens()}}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 r=await _crudifybrowser2.default.refreshAccessToken();if(!r.success)return this.log("Token refresh failed:",r.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 e={accessToken:r.data.token,refreshToken:r.data.refreshToken,expiresAt:r.data.expiresAt,refreshExpiresAt:r.data.refreshExpiresAt};return g.saveTokens(e),this.log("Tokens refreshed and saved successfully"),this.lastActivityTime=Date.now(),!0}catch(r){return this.log("Token refresh error:",r),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}}isRefreshing(){return this.isRefreshingLocally}setupResponseInterceptor(){_crudifybrowser2.default.setResponseInterceptor(async r=>{this.updateLastActivity();let e=this.detectAuthorizationError(r);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"),_chunkAT74WV5Wjs.f.emit("TOKEN_REFRESH_FAILED",{message:e.userFriendlyMessage,error:e.errorDetails,source:"SessionManager.setupResponseInterceptor"}),r;e.shouldTriggerLogout&&(g.hasValidTokens()&&!e.isIrrecoverable?(this.log("Access token expired, emitting TOKEN_EXPIRED event"),_chunkAT74WV5Wjs.f.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"),_chunkAT74WV5Wjs.f.emit("SESSION_EXPIRED",{message:e.userFriendlyMessage,error:e.errorDetails,source:"SessionManager.setupResponseInterceptor"})))}return r}),this.log("Response interceptor configured (non-blocking mode)")}detectAuthorizationError(r){let e={isAuthError:!1,isRefreshTokenInvalid:!1,isTokenRefreshFailed:!1,isTokenExpired:!1,isUnauthorized:!1,isIrrecoverable:!1,shouldTriggerLogout:!1,errorType:"",errorDetails:null,userFriendlyMessage:""};if(r.errors&&Array.isArray(r.errors)){let t=r.errors.find(i=>i.errorType==="Unauthorized"||_optionalChain([i, 'access', _26 => _26.message, 'optionalAccess', _27 => _27.includes, 'call', _28 => _28("Unauthorized")])||_optionalChain([i, 'access', _29 => _29.message, 'optionalAccess', _30 => _30.includes, 'call', _31 => _31("Not Authorized")])||_optionalChain([i, 'access', _32 => _32.message, 'optionalAccess', _33 => _33.includes, 'call', _34 => _34("NOT_AUTHORIZED")])||_optionalChain([i, 'access', _35 => _35.message, 'optionalAccess', _36 => _36.includes, 'call', _37 => _37("Token")])||_optionalChain([i, 'access', _38 => _38.message, 'optionalAccess', _39 => _39.includes, 'call', _40 => _40("TOKEN")])||_optionalChain([i, 'access', _41 => _41.message, 'optionalAccess', _42 => _42.includes, 'call', _43 => _43("Authentication")])||_optionalChain([i, 'access', _44 => _44.message, 'optionalAccess', _45 => _45.includes, 'call', _46 => _46("UNAUTHENTICATED")])||_optionalChain([i, 'access', _47 => _47.extensions, 'optionalAccess', _48 => _48.code])==="UNAUTHENTICATED"||_optionalChain([i, 'access', _49 => _49.extensions, 'optionalAccess', _50 => _50.code])==="FORBIDDEN");t&&(e.isAuthError=!0,e.errorType="GraphQL Array",e.errorDetails=t,e.shouldTriggerLogout=!0,e.userFriendlyMessage="Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente.",(_optionalChain([t, 'access', _51 => _51.message, 'optionalAccess', _52 => _52.includes, 'call', _53 => _53("TOKEN")])||_optionalChain([t, 'access', _54 => _54.message, 'optionalAccess', _55 => _55.includes, 'call', _56 => _56("Token")]))&&(e.isTokenExpired=!0),_optionalChain([t, 'access', _57 => _57.extensions, 'optionalAccess', _58 => _58.code])==="UNAUTHENTICATED"&&(e.isUnauthorized=!0))}if(!e.isAuthError&&r.errors&&typeof r.errors=="object"&&!Array.isArray(r.errors)){let i=Object.values(r.errors).flat().find(u=>typeof u=="string"&&(u.includes("NOT_AUTHORIZED")||u.includes("TOKEN_REFRESH_FAILED")||u.includes("TOKEN_HAS_EXPIRED")||u.includes("PLEASE_LOGIN")||u.includes("Unauthorized")||u.includes("UNAUTHENTICATED")||u.includes("SESSION_EXPIRED")||u.includes("INVALID_TOKEN")));i&&typeof i=="string"&&(e.isAuthError=!0,e.errorType="GraphQL Object",e.errorDetails=r.errors,e.shouldTriggerLogout=!0,i.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."):i.includes("TOKEN_HAS_EXPIRED")||i.includes("SESSION_EXPIRED")?(e.isTokenExpired=!0,e.userFriendlyMessage="Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente."):i.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&&_optionalChain([r, 'access', _59 => _59.data, 'optionalAccess', _60 => _60.response, 'optionalAccess', _61 => _61.status])){let t=r.data.response.status.toUpperCase();(t==="UNAUTHORIZED"||t==="UNAUTHENTICATED")&&(e.isAuthError=!0,e.errorType="Status",e.errorDetails=r.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&&_optionalChain([r, 'access', _62 => _62.data, 'optionalAccess', _63 => _63.response, 'optionalAccess', _64 => _64.data]))try{let t=typeof r.data.response.data=="string"?JSON.parse(r.data.response.data):r.data.response.data;(t.error==="REFRESH_TOKEN_INVALID"||t.error==="TOKEN_EXPIRED"||t.error==="INVALID_TOKEN")&&(e.isAuthError=!0,e.errorType="Parsed Data",e.errorDetails=t,e.shouldTriggerLogout=!0,e.isIrrecoverable=!0,t.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 (e4){}if(!e.isAuthError&&r.errorCode){let t=r.errorCode.toUpperCase();(t==="UNAUTHORIZED"||t==="UNAUTHENTICATED"||t==="TOKEN_EXPIRED"||t==="INVALID_TOKEN")&&(e.isAuthError=!0,e.errorType="Error Code",e.errorDetails={errorCode:t},e.shouldTriggerLogout=!0,t==="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 r=this.getTimeSinceLastActivity(),e=_crudifybrowser2.default.getTokenData();if(this.lastActivityTime===0)return"none";let t=900*1e3,i=300*1e3,u=300*1e3;return r>t?(this.log(`Inactivity timeout: ${Math.floor(r/6e4)} minutes since last activity`),"logout"):r<i&&e.expiresIn<u&&e.expiresIn>0?(this.log(`User active recently (${Math.floor(r/6e4)}min ago) and token expiring soon, should refresh`),"refresh"):"none"}clearSession(){g.clearTokens(),_crudifybrowser2.default.logout(),this.lastActivityTime=0,this.log("Session cleared completely")}getSessionExpiredMessage(){return this.config.translateFn?_chunkAT74WV5Wjs.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(r,...e){this.config.enableLogging&&console.log(`[SessionManager] ${r}`,...e)}formatError(r){return r?typeof r=="string"?r:typeof r=="object"?Object.values(r).flat().join(", "):"Authentication failed":"Unknown error"}};var _react = require('react'); var _react2 = _interopRequireDefault(_react);function j(o={}){let[r,e]=_react.useState.call(void 0, {isAuthenticated:!1,isLoading:!0,isInitialized:!1,tokens:null,error:null}),t=C.getInstance(),i=_react.useCallback.call(void 0, async()=>{try{e(a=>({...a,isLoading:!0,error:null}));let c={autoRestore:_nullishCoalesce(o.autoRestore, () => (!0)),enableLogging:_nullishCoalesce(o.enableLogging, () => (!1)),showNotification:o.showNotification,translateFn:o.translateFn,onSessionExpired:()=>{e(a=>({...a,isAuthenticated:!1,tokens:null,error:"Session expired"})),_optionalChain([o, 'access', _65 => _65.onSessionExpired, 'optionalCall', _66 => _66()])},onSessionRestored:a=>{e(d=>({...d,isAuthenticated:!0,tokens:a,error:null})),_optionalChain([o, 'access', _67 => _67.onSessionRestored, 'optionalCall', _68 => _68(a)])},onLoginSuccess:a=>{e(d=>({...d,isAuthenticated:!0,tokens:a,error:null}))},onLogout:()=>{e(a=>({...a,isAuthenticated:!1,tokens:null,error:null}))}};await t.initialize(c),t.setupResponseInterceptor();let s=t.isAuthenticated(),n=t.getTokenInfo();e(a=>({...a,isAuthenticated:s,isInitialized:!0,isLoading:!1,tokens:n.crudifyTokens.accessToken?{accessToken:n.crudifyTokens.accessToken,refreshToken:n.crudifyTokens.refreshToken,expiresAt:n.crudifyTokens.expiresAt,refreshExpiresAt:n.crudifyTokens.refreshExpiresAt}:null}))}catch(c){let s=c instanceof Error?c.message:"Initialization failed";e(n=>({...n,isLoading:!1,isInitialized:!0,error:s}))}},[o.autoRestore,o.enableLogging,o.onSessionExpired,o.onSessionRestored]),u=_react.useCallback.call(void 0, async(c,s)=>{e(n=>({...n,isLoading:!0,error:null}));try{let n=await t.login(c,s);return n.success&&n.tokens?e(a=>({...a,isAuthenticated:!0,tokens:n.tokens,isLoading:!1,error:null})):e(a=>({...a,isAuthenticated:!1,tokens:null,isLoading:!1,error:null})),n}catch(n){let a=n instanceof Error?n.message:"Login failed",d=a.includes("INVALID_CREDENTIALS")||a.includes("Invalid email")||a.includes("Invalid password")||a.includes("credentials");return e(m=>({...m,isAuthenticated:!1,tokens:null,isLoading:!1,error:d?null:a})),{success:!1,error:a}}},[t]),E=_react.useCallback.call(void 0, async()=>{e(c=>({...c,isLoading:!0}));try{await t.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"}))}},[t]),h=_react.useCallback.call(void 0, async()=>{try{let c=await t.refreshTokens();if(c){let s=t.getTokenInfo();e(n=>({...n,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}},[t]),S=_react.useCallback.call(void 0, ()=>{e(c=>({...c,error:null}))},[]),y=_react.useCallback.call(void 0, ()=>t.getTokenInfo(),[t]);_react.useEffect.call(void 0, ()=>{i()},[i]),_react.useEffect.call(void 0, ()=>{if(!r.isAuthenticated||!r.tokens)return;let c=_chunkAT74WV5Wjs.g.getInstance(),s=()=>{t.updateLastActivity(),o.enableLogging&&console.log("\u{1F4CD} User navigating - activity updated")},n=c.subscribe(s);window.addEventListener("popstate",s);let a=setInterval(async()=>{if(t.isRefreshing()){o.enableLogging&&console.log("\u23F8\uFE0F Refresh already in progress, skipping inactivity check");return}let d=t.checkInactivity();if(d==="logout")o.enableLogging&&console.log("\u23F1\uFE0F Inactivity timeout - logging out user"),await E();else if(d==="refresh")if(o.enableLogging&&console.log("\u{1F504} User active, token expiring soon - refreshing..."),e(p=>({...p,isLoading:!0})),await t.refreshTokens()){let p=t.getTokenInfo();e(x=>({...x,isLoading:!1,tokens:p.crudifyTokens.accessToken?{accessToken:p.crudifyTokens.accessToken,refreshToken:p.crudifyTokens.refreshToken,expiresAt:p.crudifyTokens.expiresAt,refreshExpiresAt:p.crudifyTokens.refreshExpiresAt}:null}))}else e(p=>({...p,isLoading:!1,isAuthenticated:!1,tokens:null}))},120*1e3);return()=>{clearInterval(a),window.removeEventListener("popstate",s),n()}},[r.isAuthenticated,r.tokens,t,o.enableLogging,E]),_react.useEffect.call(void 0, ()=>{let c=_chunkAT74WV5Wjs.f.subscribe(async s=>{if(o.enableLogging&&console.log(`\u{1F4E2} useSession: Received auth event: ${s.type}`),s.type==="TOKEN_EXPIRED"){if(t.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(n=>({...n,isLoading:!0}));try{if(await t.refreshTokens()){o.enableLogging&&console.log("\u2705 Token refreshed successfully");let a=t.getTokenInfo();e(d=>({...d,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"),_chunkAT74WV5Wjs.f.emit("SESSION_EXPIRED",{message:"Failed to refresh token after detecting expiration",source:"useSession.TOKEN_EXPIRED handler"})}catch(n){o.enableLogging&&console.error("\u274C Error during token refresh:",n),_chunkAT74WV5Wjs.f.emit("SESSION_EXPIRED",{message:n instanceof Error?n.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(n=>({...n,isAuthenticated:!1,tokens:null,isLoading:!1,error:_optionalChain([s, 'access', _69 => _69.details, 'optionalAccess', _70 => _70.message])||"Session expired"})),_optionalChain([o, 'access', _71 => _71.onSessionExpired, 'optionalCall', _72 => _72()]))});return()=>c()},[o.enableLogging,o.onSessionExpired,t]),_react.useEffect.call(void 0, ()=>{let c=g.subscribeToChanges(s=>{s?(o.enableLogging&&console.log("\u{1F504} Tokens updated in another tab"),e(n=>({...n,tokens:s,isAuthenticated:!0}))):(o.enableLogging&&console.log("\u{1F504} Logout detected in another tab"),e(n=>({...n,isAuthenticated:!1,tokens:null})),_chunkAT74WV5Wjs.f.emit("SESSION_EXPIRED",{message:"Sesi\xF3n cerrada en otra pesta\xF1a",source:"CrossTabSync"}))});return()=>c()},[o.enableLogging]);let N=_react.useCallback.call(void 0, ()=>{t.updateLastActivity()},[t]);return{...r,login:u,logout:E,refreshTokens:h,clearError:S,getTokenInfo:y,updateActivity:N,isExpiringSoon:r.tokens?r.tokens.expiresAt-Date.now()<300*1e3:!1,expiresIn:r.tokens?Math.max(0,r.tokens.expiresAt-Date.now()):0,refreshExpiresIn:r.tokens?Math.max(0,r.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),de=o=>_dompurify2.default.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}),$= exports.d =({children:o,maxNotifications:r=5,defaultAutoHideDuration:e=6e3,position:t={vertical:"top",horizontal:"right"},enabled:i=!1,allowHtml:u=!1})=>{let[E,h]=_react.useState.call(void 0, []),S=_react.useCallback.call(void 0, (s,n="info",a)=>{if(!i)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 d=_uuid.v4.call(void 0, ),m={id:d,message:s,severity:n,autoHideDuration:_nullishCoalesce(_optionalChain([a, 'optionalAccess', _73 => _73.autoHideDuration]), () => (e)),persistent:_nullishCoalesce(_optionalChain([a, 'optionalAccess', _74 => _74.persistent]), () => (!1)),allowHtml:_nullishCoalesce(_optionalChain([a, 'optionalAccess', _75 => _75.allowHtml]), () => (u))};return h(p=>[...p.length>=r?p.slice(-(r-1)):p,m]),d},[r,e,i,u]),y=_react.useCallback.call(void 0, s=>{h(n=>n.filter(a=>a.id!==s))},[]),N=_react.useCallback.call(void 0, ()=>{h([])},[]),c={showNotification:S,hideNotification:y,clearAllNotifications:N};return _jsxruntime.jsxs.call(void 0, W.Provider,{value:c,children:[o,i&&_jsxruntime.jsx.call(void 0, _material.Portal,{children:_jsxruntime.jsx.call(void 0, _material.Box,{sx:{position:"fixed",zIndex:9999,[t.vertical]:(t.vertical==="top",24),[t.horizontal]:t.horizontal==="right"||t.horizontal==="left"?24:"50%",...t.horizontal==="center"&&{transform:"translateX(-50%)"},display:"flex",flexDirection:t.vertical==="top"?"column":"column-reverse",gap:1,maxWidth:"400px",width:"auto"},children:E.map(s=>_jsxruntime.jsx.call(void 0, ge,{notification:s,onClose:()=>y(s.id)},s.id))})})]})},ge=({notification:o,onClose:r})=>{let[e,t]=_react.useState.call(void 0, !0),i=_react.useCallback.call(void 0, (u,E)=>{E!=="clickaway"&&(t(!1),setTimeout(r,300))},[r]);return _react.useEffect.call(void 0, ()=>{if(!o.persistent&&o.autoHideDuration){let u=setTimeout(()=>{i()},o.autoHideDuration);return()=>clearTimeout(u)}},[o.autoHideDuration,o.persistent,i]),_jsxruntime.jsx.call(void 0, _material.Snackbar,{open:e,onClose:i,sx:{position:"relative","& .MuiSnackbarContent-root":{minWidth:"auto"}},TransitionProps:{enter:!0,exit:!0},children:_jsxruntime.jsx.call(void 0, _material.Alert,{variant:"filled",severity:o.severity,onClose:i,sx:{width:"100%",minWidth:"280px",maxWidth:"400px",wordBreak:"break-word"},children:o.allowHtml?_jsxruntime.jsx.call(void 0, "span",{dangerouslySetInnerHTML:{__html:de(o.message)}}):_jsxruntime.jsx.call(void 0, "span",{children:o.message})})})},J= exports.e =()=>{let o=_react.useContext.call(void 0, W);if(!o)throw new Error("useGlobalNotification debe ser usado dentro de un GlobalNotificationProvider");return o};var q=_react.createContext.call(void 0, void 0);function ke({children:o,options:r={},config:e,showNotifications:t=!1,notificationOptions:i={}}){let u;try{let{showNotification:s}=J();u=s}catch (e5){}let E=_react2.default.useMemo(()=>({...r,showNotification:u,onSessionExpired:()=>{_optionalChain([r, 'access', _76 => _76.onSessionExpired, 'optionalCall', _77 => _77()])}}),[r,u]),h=j(E),S=_react.useMemo.call(void 0, ()=>{let s,n,a,d,m,p="unknown";if(_optionalChain([e, 'optionalAccess', _78 => _78.publicApiKey])&&(s=e.publicApiKey,p="props"),_optionalChain([e, 'optionalAccess', _79 => _79.env])&&(n=e.env),_optionalChain([e, 'optionalAccess', _80 => _80.appName])&&(a=e.appName),_optionalChain([e, 'optionalAccess', _81 => _81.loginActions])&&(d=e.loginActions),_optionalChain([e, 'optionalAccess', _82 => _82.logo])&&(m=e.logo),!s){let x=_chunkAT74WV5Wjs.a.call(void 0, "publicApiKey"),I=_chunkAT74WV5Wjs.a.call(void 0, "environment"),L=_chunkAT74WV5Wjs.a.call(void 0, "appName"),A=_chunkAT74WV5Wjs.a.call(void 0, "loginActions"),f=_chunkAT74WV5Wjs.a.call(void 0, "logo");x&&(s=x,p="cookies"),I&&["dev","stg","prod"].includes(I)&&(n=I),L&&(a=decodeURIComponent(L)),A&&(d=decodeURIComponent(A).split(",").map(P=>P.trim()).filter(Boolean)),f&&(m=decodeURIComponent(f))}return{publicApiKey:s,env:n,appName:a,loginActions:d,logo:m}},[e]),y=_react.useMemo.call(void 0, ()=>{if(!_optionalChain([h, 'access', _83 => _83.tokens, 'optionalAccess', _84 => _84.accessToken])||!h.isAuthenticated)return null;try{let s=_chunkAT74WV5Wjs.h.call(void 0, h.tokens.accessToken);if(s&&s.sub&&s.email&&s.subscriber){let n={_id:s.sub,email:s.email,subscriberKey:s.subscriber};return Object.keys(s).forEach(a=>{["sub","email","subscriber"].includes(a)||(n[a]=s[a])}),n}}catch(s){console.error("Error decoding JWT token for sessionData:",s)}return null},[_optionalChain([h, 'access', _85 => _85.tokens, 'optionalAccess', _86 => _86.accessToken]),h.isAuthenticated]),N={...h,sessionData:y,config:S},c={enabled:t,maxNotifications:i.maxNotifications||5,defaultAutoHideDuration:i.defaultAutoHideDuration||6e3,position:i.position||{vertical:"top",horizontal:"right"}};return _jsxruntime.jsx.call(void 0, q.Provider,{value:N,children:o})}function Qe(o){let r={enabled:o.showNotifications,maxNotifications:_optionalChain([o, 'access', _87 => _87.notificationOptions, 'optionalAccess', _88 => _88.maxNotifications])||5,defaultAutoHideDuration:_optionalChain([o, 'access', _89 => _89.notificationOptions, 'optionalAccess', _90 => _90.defaultAutoHideDuration])||6e3,position:_optionalChain([o, 'access', _91 => _91.notificationOptions, 'optionalAccess', _92 => _92.position])||{vertical:"top",horizontal:"right"},allowHtml:_optionalChain([o, 'access', _93 => _93.notificationOptions, 'optionalAccess', _94 => _94.allowHtml])||!1};return _jsxruntime.jsx.call(void 0, $,{...r,children:_jsxruntime.jsx.call(void 0, ke,{...o})})}function Q(){let o=_react.useContext.call(void 0, q);if(o===void 0)throw new Error("useSessionContext must be used within a SessionProvider");return o}function er({children:o,fallback:r=_jsxruntime.jsx.call(void 0, "div",{children:"Please log in to access this content"}),redirectTo:e}){let{isAuthenticated:t,isLoading:i,isInitialized:u}=Q();return!u||i?_jsxruntime.jsx.call(void 0, "div",{children:"Loading..."}):t?_jsxruntime.jsx.call(void 0, _jsxruntime.Fragment,{children:o}):e?(e(),null):_jsxruntime.jsx.call(void 0, _jsxruntime.Fragment,{children:r})}function rr(){let o=Q();return o.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:"})," ",o.isAuthenticated?"Yes":"No"]}),_jsxruntime.jsxs.call(void 0, "div",{children:[_jsxruntime.jsx.call(void 0, "strong",{children:"Loading:"})," ",o.isLoading?"Yes":"No"]}),_jsxruntime.jsxs.call(void 0, "div",{children:[_jsxruntime.jsx.call(void 0, "strong",{children:"Error:"})," ",o.error||"None"]}),o.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:"})," ",o.tokens.accessToken.substring(0,20),"..."]}),_jsxruntime.jsxs.call(void 0, "div",{children:[_jsxruntime.jsx.call(void 0, "strong",{children:"Refresh Token:"})," ",o.tokens.refreshToken.substring(0,20),"..."]}),_jsxruntime.jsxs.call(void 0, "div",{children:[_jsxruntime.jsx.call(void 0, "strong",{children:"Access Expires In:"})," ",Math.round(o.expiresIn/1e3/60)," minutes"]}),_jsxruntime.jsxs.call(void 0, "div",{children:[_jsxruntime.jsx.call(void 0, "strong",{children:"Refresh Expires In:"})," ",Math.round(o.refreshExpiresIn/1e3/60/60)," hours"]}),_jsxruntime.jsxs.call(void 0, "div",{children:[_jsxruntime.jsx.call(void 0, "strong",{children:"Expiring Soon:"})," ",o.isExpiringSoon?"Yes":"No"]})]})]}):_jsxruntime.jsx.call(void 0, "div",{children:"Session not initialized"})}var ar=(o={})=>{let{autoFetch:r=!0,retryOnError:e=!1,maxRetries:t=3}=o,[i,u]=_react.useState.call(void 0, null),[E,h]=_react.useState.call(void 0, !1),[S,y]=_react.useState.call(void 0, null),[N,c]=_react.useState.call(void 0, {}),s=_react.useRef.call(void 0, null),n=_react.useRef.call(void 0, !0),a=_react.useRef.call(void 0, 0),d=_react.useRef.call(void 0, 0),m=_react.useCallback.call(void 0, ()=>{u(null),y(null),h(!1),c({})},[]),p=_react.useCallback.call(void 0, async()=>{let x=_chunkAT74WV5Wjs.i.call(void 0, );if(!x){n.current&&(y("No user email available"),h(!1));return}s.current&&s.current.abort();let I=new AbortController;s.current=I;let L=++a.current;try{n.current&&(h(!0),y(null));let A=await _crudifybrowser2.default.readItems("users",{filter:{email:x},pagination:{limit:1}});if(L===a.current&&n.current&&!I.signal.aborted)if(A.success&&A.data&&A.data.length>0){let f=A.data[0];u(f);let H={fullProfile:f,totalFields:Object.keys(f).length,displayData:{id:f.id,email:f.email,username:f.username,firstName:f.firstName,lastName:f.lastName,fullName:f.fullName||`${f.firstName||""} ${f.lastName||""}`.trim(),role:f.role,permissions:f.permissions||[],isActive:f.isActive,lastLogin:f.lastLogin,createdAt:f.createdAt,updatedAt:f.updatedAt,...Object.keys(f).filter(P=>!["id","email","username","firstName","lastName","fullName","role","permissions","isActive","lastLogin","createdAt","updatedAt"].includes(P)).reduce((P,_)=>({...P,[_]:f[_]}),{})}};c(H),y(null),d.current=0}else y("User profile not found"),u(null),c({})}catch(A){if(L===a.current&&n.current){let f=A;if(f.name==="AbortError")return;e&&d.current<t&&(_optionalChain([f, 'access', _95 => _95.message, 'optionalAccess', _96 => _96.includes, 'call', _97 => _97("Network Error")])||_optionalChain([f, 'access', _98 => _98.message, 'optionalAccess', _99 => _99.includes, 'call', _100 => _100("Failed to fetch")]))?(d.current++,setTimeout(()=>{n.current&&p()},1e3*d.current)):(y("Failed to load user profile"),u(null),c({}))}}finally{L===a.current&&n.current&&h(!1),s.current===I&&(s.current=null)}},[e,t]);return _react.useEffect.call(void 0, ()=>{r&&p()},[r,p]),_react.useEffect.call(void 0, ()=>(n.current=!0,()=>{n.current=!1,s.current&&(s.current.abort(),s.current=null)}),[]),{userProfile:i,loading:E,error:S,extendedData:N,refreshProfile:p,clearProfile:m}};exports.a = g; exports.b = C; exports.c = j; exports.d = $; exports.e = J; exports.f = Qe; exports.g = Q; exports.h = er; exports.i = rr; exports.j = ar;
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 _chunkAT74WV5Wjs = require('./chunk-AT74WV5W.js');var _cryptojs = require('crypto-js'); var _cryptojs2 = _interopRequireDefault(_cryptojs);var l=class l{static setStorageType(r){l.storageType=r}static generateEncryptionKey(){let r=[navigator.userAgent,navigator.language,navigator.platform,screen.width,screen.height,Date.now().toString(),Math.random().toString(36)].join("|");return _cryptojs2.default.SHA256(r).toString()}static getEncryptionKey(){if(l.encryptionKey)return l.encryptionKey;let r=window.localStorage;if(!r)return l.encryptionKey=l.generateEncryptionKey(),l.encryptionKey;try{let e=r.getItem(l.ENCRYPTION_KEY_STORAGE);return(!e||e.length<32)&&(e=l.generateEncryptionKey(),r.setItem(l.ENCRYPTION_KEY_STORAGE,e)),l.encryptionKey=e,e}catch (e2){return console.warn("Crudify: Cannot persist encryption key, using temporary key"),l.encryptionKey=l.generateEncryptionKey(),l.encryptionKey}}static isStorageAvailable(r){try{let e=window[r],t="__storage_test__";return e.setItem(t,"test"),e.removeItem(t),!0}catch (e3){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(r){try{let e=l.getEncryptionKey();return _cryptojs2.default.AES.encrypt(r,e).toString()}catch(e){return console.error("Crudify: Encryption failed",e),r}}static decrypt(r){try{let e=l.getEncryptionKey();return _cryptojs2.default.AES.decrypt(r,e).toString(_cryptojs2.default.enc.Utf8)||r}catch(e){return console.error("Crudify: Decryption failed",e),r}}static saveTokens(r){let e=l.getStorage();if(e)try{let t={accessToken:r.accessToken,refreshToken:r.refreshToken,expiresAt:r.expiresAt,refreshExpiresAt:r.refreshExpiresAt,savedAt:Date.now()},i=l.encrypt(JSON.stringify(t));e.setItem(l.TOKEN_KEY,i),console.debug("Crudify: Tokens saved successfully")}catch(t){console.error("Crudify: Failed to save tokens",t)}}static getTokens(){let r=l.getStorage();if(!r)return null;try{let e=r.getItem(l.TOKEN_KEY);if(!e)return null;let t=l.decrypt(e),i=JSON.parse(t);return!i.accessToken||!i.refreshToken||!i.expiresAt||!i.refreshExpiresAt?(console.warn("Crudify: Incomplete token data found, clearing storage"),l.clearTokens(),null):Date.now()>=i.refreshExpiresAt?(console.info("Crudify: Refresh token expired, clearing storage"),l.clearTokens(),null):{accessToken:i.accessToken,refreshToken:i.refreshToken,expiresAt:i.expiresAt,refreshExpiresAt:i.refreshExpiresAt}}catch(e){return console.error("Crudify: Failed to retrieve tokens",e),l.clearTokens(),null}}static clearTokens(){let r=l.getStorage();if(r)try{r.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 r=window.localStorage;r&&r.removeItem(l.ENCRYPTION_KEY_STORAGE),console.info("Crudify: Encryption key rotated successfully")}catch(r){console.error("Crudify: Failed to rotate encryption key",r)}}static hasValidTokens(){return l.getTokens()!==null}static getExpirationInfo(){let r=l.getTokens();if(!r)return null;let e=Date.now();return{accessExpired:e>=r.expiresAt,refreshExpired:e>=r.refreshExpiresAt,accessExpiresIn:Math.max(0,r.expiresAt-e),refreshExpiresIn:Math.max(0,r.refreshExpiresAt-e)}}static updateAccessToken(r,e){let t=l.getTokens();if(!t){console.warn("Crudify: Cannot update access token, no existing tokens found");return}l.saveTokens({...t,accessToken:r,expiresAt:e})}static subscribeToChanges(r){let e=t=>{if(t.key===l.TOKEN_KEY){if(t.newValue===null){console.debug("Crudify: Tokens removed in another tab"),r(null);return}if(t.newValue){console.debug("Crudify: Tokens updated in another tab");let i=l.getTokens();r(i)}}};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 g=l;var _crudifybrowser = require('@nocios/crudify-browser'); var _crudifybrowser2 = _interopRequireDefault(_crudifybrowser);var C=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(r={}){if(this.initialized){console.warn("SessionManager: Already initialized");return}this.config={storageType:"localStorage",autoRestore:!0,enableLogging:!1,...r},g.setStorageType(this.config.storageType||"localStorage"),this.config.enableLogging,_crudifybrowser2.default.setTokenInvalidationCallback(()=>{this.log("\u{1F514} Tokens invalidated by crudify-core"),_chunkAT74WV5Wjs.f.emit("SESSION_EXPIRED",{message:"Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente.",source:"crudify-core.clearTokensAndRefreshState"})}),this.config.autoRestore&&await this.restoreSession(),this.initialized=!0,this.log("SessionManager initialized successfully")}async login(r,e){try{this.log("Attempting login...");let t=await _crudifybrowser2.default.login(r,e);if(!t.success)return this.log("Login failed:",t.errors),{success:!1,error:this.formatError(t.errors),rawResponse:t};let i={accessToken:t.data.token,refreshToken:t.data.refreshToken,expiresAt:t.data.expiresAt,refreshExpiresAt:t.data.refreshExpiresAt};return g.saveTokens(i),this.lastActivityTime=Date.now(),this.log("Login successful, tokens saved"),_optionalChain([this, 'access', _2 => _2.config, 'access', _3 => _3.onLoginSuccess, 'optionalCall', _4 => _4(i)]),{success:!0,tokens:i,data:t.data}}catch(t){return this.log("Login error:",t),{success:!1,error:t instanceof Error?t.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(r){this.log("Logout error:",r),g.clearTokens()}}async restoreSession(){try{this.log("Attempting to restore session...");let r=g.getTokens();if(!r)return this.log("No valid tokens found in storage"),!1;if(Date.now()>=r.refreshExpiresAt)return this.log("Refresh token expired, clearing storage"),g.clearTokens(),!1;if(_crudifybrowser2.default.setTokens({accessToken:r.accessToken,refreshToken:r.refreshToken,expiresAt:r.expiresAt,refreshExpiresAt:r.refreshExpiresAt}),_crudifybrowser2.default.getTokenData().isValid===!1){if(this.log("Restored access token is invalid or expired"),Date.now()<r.refreshExpiresAt&&(this.log("Access token expired but refresh is valid, attempting refresh..."),await this.refreshTokens())){this.log("Session restored successfully via token refresh");let i=g.getTokens();return i&&_optionalChain([this, 'access', _8 => _8.config, 'access', _9 => _9.onSessionRestored, 'optionalCall', _10 => _10(i)]),!0}return g.clearTokens(),await _crudifybrowser2.default.logout(),!1}return this.log("Session restored successfully"),this.lastActivityTime=Date.now(),_optionalChain([this, 'access', _11 => _11.config, 'access', _12 => _12.onSessionRestored, 'optionalCall', _13 => _13(r)]),!0}catch(r){return this.log("Session restore error:",r),g.clearTokens(),await _crudifybrowser2.default.logout(),!1}}isAuthenticated(){return _crudifybrowser2.default.isLogin()||g.hasValidTokens()}getTokenInfo(){let r=_crudifybrowser2.default.getTokenData(),e=g.getExpirationInfo();return{isLoggedIn:this.isAuthenticated(),crudifyTokens:r,storageInfo:e,hasValidTokens:g.hasValidTokens()}}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 r=await _crudifybrowser2.default.refreshAccessToken();if(!r.success)return this.log("Token refresh failed:",r.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 e={accessToken:r.data.token,refreshToken:r.data.refreshToken,expiresAt:r.data.expiresAt,refreshExpiresAt:r.data.refreshExpiresAt};return g.saveTokens(e),this.log("Tokens refreshed and saved successfully"),this.lastActivityTime=Date.now(),!0}catch(r){return this.log("Token refresh error:",r),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}}isRefreshing(){return this.isRefreshingLocally}setupResponseInterceptor(){_crudifybrowser2.default.setResponseInterceptor(async r=>{this.updateLastActivity();let e=this.detectAuthorizationError(r);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"),_chunkAT74WV5Wjs.f.emit("TOKEN_REFRESH_FAILED",{message:e.userFriendlyMessage,error:e.errorDetails,source:"SessionManager.setupResponseInterceptor"}),r;e.shouldTriggerLogout&&(g.hasValidTokens()&&!e.isIrrecoverable?(this.log("Access token expired, emitting TOKEN_EXPIRED event"),_chunkAT74WV5Wjs.f.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"),_chunkAT74WV5Wjs.f.emit("SESSION_EXPIRED",{message:e.userFriendlyMessage,error:e.errorDetails,source:"SessionManager.setupResponseInterceptor"})))}return r}),this.log("Response interceptor configured (non-blocking mode)")}detectAuthorizationError(r){let e={isAuthError:!1,isRefreshTokenInvalid:!1,isTokenRefreshFailed:!1,isTokenExpired:!1,isUnauthorized:!1,isIrrecoverable:!1,shouldTriggerLogout:!1,errorType:"",errorDetails:null,userFriendlyMessage:""};if(r.errors&&Array.isArray(r.errors)){let t=r.errors.find(i=>i.errorType==="Unauthorized"||_optionalChain([i, 'access', _26 => _26.message, 'optionalAccess', _27 => _27.includes, 'call', _28 => _28("Unauthorized")])||_optionalChain([i, 'access', _29 => _29.message, 'optionalAccess', _30 => _30.includes, 'call', _31 => _31("Not Authorized")])||_optionalChain([i, 'access', _32 => _32.message, 'optionalAccess', _33 => _33.includes, 'call', _34 => _34("NOT_AUTHORIZED")])||_optionalChain([i, 'access', _35 => _35.message, 'optionalAccess', _36 => _36.includes, 'call', _37 => _37("Token")])||_optionalChain([i, 'access', _38 => _38.message, 'optionalAccess', _39 => _39.includes, 'call', _40 => _40("TOKEN")])||_optionalChain([i, 'access', _41 => _41.message, 'optionalAccess', _42 => _42.includes, 'call', _43 => _43("Authentication")])||_optionalChain([i, 'access', _44 => _44.message, 'optionalAccess', _45 => _45.includes, 'call', _46 => _46("UNAUTHENTICATED")])||_optionalChain([i, 'access', _47 => _47.extensions, 'optionalAccess', _48 => _48.code])==="UNAUTHENTICATED"||_optionalChain([i, 'access', _49 => _49.extensions, 'optionalAccess', _50 => _50.code])==="FORBIDDEN");t&&(e.isAuthError=!0,e.errorType="GraphQL Array",e.errorDetails=t,e.shouldTriggerLogout=!0,e.userFriendlyMessage="Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente.",(_optionalChain([t, 'access', _51 => _51.message, 'optionalAccess', _52 => _52.includes, 'call', _53 => _53("TOKEN")])||_optionalChain([t, 'access', _54 => _54.message, 'optionalAccess', _55 => _55.includes, 'call', _56 => _56("Token")]))&&(e.isTokenExpired=!0),_optionalChain([t, 'access', _57 => _57.extensions, 'optionalAccess', _58 => _58.code])==="UNAUTHENTICATED"&&(e.isUnauthorized=!0))}if(!e.isAuthError&&r.errors&&typeof r.errors=="object"&&!Array.isArray(r.errors)){let i=Object.values(r.errors).flat().find(u=>typeof u=="string"&&(u.includes("NOT_AUTHORIZED")||u.includes("TOKEN_REFRESH_FAILED")||u.includes("TOKEN_HAS_EXPIRED")||u.includes("PLEASE_LOGIN")||u.includes("Unauthorized")||u.includes("UNAUTHENTICATED")||u.includes("SESSION_EXPIRED")||u.includes("INVALID_TOKEN")));i&&typeof i=="string"&&(e.isAuthError=!0,e.errorType="GraphQL Object",e.errorDetails=r.errors,e.shouldTriggerLogout=!0,i.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."):i.includes("TOKEN_HAS_EXPIRED")||i.includes("SESSION_EXPIRED")?(e.isTokenExpired=!0,e.userFriendlyMessage="Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente."):i.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&&_optionalChain([r, 'access', _59 => _59.data, 'optionalAccess', _60 => _60.response, 'optionalAccess', _61 => _61.status])){let t=r.data.response.status.toUpperCase();(t==="UNAUTHORIZED"||t==="UNAUTHENTICATED")&&(e.isAuthError=!0,e.errorType="Status",e.errorDetails=r.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&&_optionalChain([r, 'access', _62 => _62.data, 'optionalAccess', _63 => _63.response, 'optionalAccess', _64 => _64.data]))try{let t=typeof r.data.response.data=="string"?JSON.parse(r.data.response.data):r.data.response.data;(t.error==="REFRESH_TOKEN_INVALID"||t.error==="TOKEN_EXPIRED"||t.error==="INVALID_TOKEN")&&(e.isAuthError=!0,e.errorType="Parsed Data",e.errorDetails=t,e.shouldTriggerLogout=!0,e.isIrrecoverable=!0,t.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 (e4){}if(!e.isAuthError&&r.errorCode){let t=r.errorCode.toUpperCase();(t==="UNAUTHORIZED"||t==="UNAUTHENTICATED"||t==="TOKEN_EXPIRED"||t==="INVALID_TOKEN")&&(e.isAuthError=!0,e.errorType="Error Code",e.errorDetails={errorCode:t},e.shouldTriggerLogout=!0,t==="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 r=this.getTimeSinceLastActivity(),e=_crudifybrowser2.default.getTokenData();if(this.lastActivityTime===0)return"none";let t=900*1e3,i=300*1e3,u=300*1e3;return r>t?(this.log(`Inactivity timeout: ${Math.floor(r/6e4)} minutes since last activity`),"logout"):r<i&&e.expiresIn<u&&e.expiresIn>0?(this.log(`User active recently (${Math.floor(r/6e4)}min ago) and token expiring soon, should refresh`),"refresh"):"none"}clearSession(){g.clearTokens(),_crudifybrowser2.default.logout(),this.lastActivityTime=0,this.log("Session cleared completely")}getSessionExpiredMessage(){return this.config.translateFn?_chunkAT74WV5Wjs.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(r,...e){this.config.enableLogging&&console.log(`[SessionManager] ${r}`,...e)}formatError(r){return r?typeof r=="string"?r:typeof r=="object"?Object.values(r).flat().join(", "):"Authentication failed":"Unknown error"}};var _react = require('react'); var _react2 = _interopRequireDefault(_react);function Y(o={}){let[r,e]=_react.useState.call(void 0, {isAuthenticated:!1,isLoading:!0,isInitialized:!1,tokens:null,error:null}),t=C.getInstance(),i=_react.useCallback.call(void 0, async()=>{try{e(a=>({...a,isLoading:!0,error:null}));let c={autoRestore:_nullishCoalesce(o.autoRestore, () => (!0)),enableLogging:_nullishCoalesce(o.enableLogging, () => (!1)),showNotification:o.showNotification,translateFn:o.translateFn,onSessionExpired:()=>{e(a=>({...a,isAuthenticated:!1,tokens:null,error:"Session expired"})),_optionalChain([o, 'access', _65 => _65.onSessionExpired, 'optionalCall', _66 => _66()])},onSessionRestored:a=>{e(d=>({...d,isAuthenticated:!0,tokens:a,error:null})),_optionalChain([o, 'access', _67 => _67.onSessionRestored, 'optionalCall', _68 => _68(a)])},onLoginSuccess:a=>{e(d=>({...d,isAuthenticated:!0,tokens:a,error:null}))},onLogout:()=>{e(a=>({...a,isAuthenticated:!1,tokens:null,error:null}))}};await t.initialize(c),t.setupResponseInterceptor();let s=t.isAuthenticated(),n=t.getTokenInfo();e(a=>({...a,isAuthenticated:s,isInitialized:!0,isLoading:!1,tokens:n.crudifyTokens.accessToken?{accessToken:n.crudifyTokens.accessToken,refreshToken:n.crudifyTokens.refreshToken,expiresAt:n.crudifyTokens.expiresAt,refreshExpiresAt:n.crudifyTokens.refreshExpiresAt}:null}))}catch(c){let s=c instanceof Error?c.message:"Initialization failed";e(n=>({...n,isLoading:!1,isInitialized:!0,error:s}))}},[o.autoRestore,o.enableLogging,o.onSessionExpired,o.onSessionRestored]),u=_react.useCallback.call(void 0, async(c,s)=>{e(n=>({...n,isLoading:!0,error:null}));try{let n=await t.login(c,s);return n.success&&n.tokens?e(a=>({...a,isAuthenticated:!0,tokens:n.tokens,isLoading:!1,error:null})):e(a=>({...a,isAuthenticated:!1,tokens:null,isLoading:!1,error:null})),n}catch(n){let a=n instanceof Error?n.message:"Login failed",d=a.includes("INVALID_CREDENTIALS")||a.includes("Invalid email")||a.includes("Invalid password")||a.includes("credentials");return e(m=>({...m,isAuthenticated:!1,tokens:null,isLoading:!1,error:d?null:a})),{success:!1,error:a}}},[t]),E=_react.useCallback.call(void 0, async()=>{e(c=>({...c,isLoading:!0}));try{await t.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"}))}},[t]),h=_react.useCallback.call(void 0, async()=>{try{let c=await t.refreshTokens();if(c){let s=t.getTokenInfo();e(n=>({...n,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}},[t]),S=_react.useCallback.call(void 0, ()=>{e(c=>({...c,error:null}))},[]),T=_react.useCallback.call(void 0, ()=>t.getTokenInfo(),[t]);_react.useEffect.call(void 0, ()=>{i()},[i]),_react.useEffect.call(void 0, ()=>{if(!r.isAuthenticated||!r.tokens)return;let c=_chunkAT74WV5Wjs.g.getInstance(),s=()=>{t.updateLastActivity(),o.enableLogging&&console.log("\u{1F4CD} User navigating - activity updated")},n=c.subscribe(s);window.addEventListener("popstate",s);let a=setInterval(async()=>{if(t.isRefreshing()){o.enableLogging&&console.log("\u23F8\uFE0F Refresh already in progress, skipping inactivity check");return}let d=t.checkInactivity();if(d==="logout")o.enableLogging&&console.log("\u23F1\uFE0F Inactivity timeout - logging out user"),await E();else if(d==="refresh")if(o.enableLogging&&console.log("\u{1F504} User active, token expiring soon - refreshing..."),e(p=>({...p,isLoading:!0})),await t.refreshTokens()){let p=t.getTokenInfo();e(x=>({...x,isLoading:!1,tokens:p.crudifyTokens.accessToken?{accessToken:p.crudifyTokens.accessToken,refreshToken:p.crudifyTokens.refreshToken,expiresAt:p.crudifyTokens.expiresAt,refreshExpiresAt:p.crudifyTokens.refreshExpiresAt}:null}))}else e(p=>({...p,isLoading:!1,isAuthenticated:!1,tokens:null}))},120*1e3);return()=>{clearInterval(a),window.removeEventListener("popstate",s),n()}},[r.isAuthenticated,r.tokens,t,o.enableLogging,E]),_react.useEffect.call(void 0, ()=>{let c=_chunkAT74WV5Wjs.f.subscribe(async s=>{if(o.enableLogging&&console.log(`\u{1F4E2} useSession: Received auth event: ${s.type}`),s.type==="TOKEN_EXPIRED"){if(t.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(n=>({...n,isLoading:!0}));try{if(await t.refreshTokens()){o.enableLogging&&console.log("\u2705 Token refreshed successfully");let a=t.getTokenInfo();e(d=>({...d,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"),_chunkAT74WV5Wjs.f.emit("SESSION_EXPIRED",{message:"Failed to refresh token after detecting expiration",source:"useSession.TOKEN_EXPIRED handler"})}catch(n){o.enableLogging&&console.error("\u274C Error during token refresh:",n),_chunkAT74WV5Wjs.f.emit("SESSION_EXPIRED",{message:n instanceof Error?n.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(n=>({...n,isAuthenticated:!1,tokens:null,isLoading:!1,error:_optionalChain([s, 'access', _69 => _69.details, 'optionalAccess', _70 => _70.message])||"Session expired"})),_optionalChain([o, 'access', _71 => _71.onSessionExpired, 'optionalCall', _72 => _72()]))});return()=>c()},[o.enableLogging,o.onSessionExpired,t]),_react.useEffect.call(void 0, ()=>{let c=g.subscribeToChanges(s=>{s?(o.enableLogging&&console.log("\u{1F504} Tokens updated in another tab"),e(n=>({...n,tokens:s,isAuthenticated:!0}))):(o.enableLogging&&console.log("\u{1F504} Logout detected in another tab"),e(n=>({...n,isAuthenticated:!1,tokens:null})),_chunkAT74WV5Wjs.f.emit("SESSION_EXPIRED",{message:"Sesi\xF3n cerrada en otra pesta\xF1a",source:"CrossTabSync"}))});return()=>c()},[o.enableLogging]);let N=_react.useCallback.call(void 0, ()=>{t.updateLastActivity()},[t]);return{...r,login:u,logout:E,refreshTokens:h,clearError:S,getTokenInfo:T,updateActivity:N,isExpiringSoon:r.tokens?r.tokens.expiresAt-Date.now()<300*1e3:!1,expiresIn:r.tokens?Math.max(0,r.tokens.expiresAt-Date.now()):0,refreshExpiresIn:r.tokens?Math.max(0,r.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 B=_react.createContext.call(void 0, null),ue=o=>_dompurify2.default.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}),W= exports.d =({children:o,maxNotifications:r=5,defaultAutoHideDuration:e=6e3,position:t={vertical:"top",horizontal:"right"},enabled:i=!1,allowHtml:u=!1})=>{let[E,h]=_react.useState.call(void 0, []),S=_react.useCallback.call(void 0, (s,n="info",a)=>{if(!i)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 d=_uuid.v4.call(void 0, ),m={id:d,message:s,severity:n,autoHideDuration:_nullishCoalesce(_optionalChain([a, 'optionalAccess', _73 => _73.autoHideDuration]), () => (e)),persistent:_nullishCoalesce(_optionalChain([a, 'optionalAccess', _74 => _74.persistent]), () => (!1)),allowHtml:_nullishCoalesce(_optionalChain([a, 'optionalAccess', _75 => _75.allowHtml]), () => (u))};return h(p=>[...p.length>=r?p.slice(-(r-1)):p,m]),d},[r,e,i,u]),T=_react.useCallback.call(void 0, s=>{h(n=>n.filter(a=>a.id!==s))},[]),N=_react.useCallback.call(void 0, ()=>{h([])},[]),c={showNotification:S,hideNotification:T,clearAllNotifications:N};return _jsxruntime.jsxs.call(void 0, B.Provider,{value:c,children:[o,i&&_jsxruntime.jsx.call(void 0, _material.Portal,{children:_jsxruntime.jsx.call(void 0, _material.Box,{sx:{position:"fixed",zIndex:9999,[t.vertical]:(t.vertical==="top",24),[t.horizontal]:t.horizontal==="right"||t.horizontal==="left"?24:"50%",...t.horizontal==="center"&&{transform:"translateX(-50%)"},display:"flex",flexDirection:t.vertical==="top"?"column":"column-reverse",gap:1,maxWidth:"400px",width:"auto"},children:E.map(s=>_jsxruntime.jsx.call(void 0, fe,{notification:s,onClose:()=>T(s.id)},s.id))})})]})},fe=({notification:o,onClose:r})=>{let[e,t]=_react.useState.call(void 0, !0),i=_react.useCallback.call(void 0, (u,E)=>{E!=="clickaway"&&(t(!1),setTimeout(r,300))},[r]);return _react.useEffect.call(void 0, ()=>{if(!o.persistent&&o.autoHideDuration){let u=setTimeout(()=>{i()},o.autoHideDuration);return()=>clearTimeout(u)}},[o.autoHideDuration,o.persistent,i]),_jsxruntime.jsx.call(void 0, _material.Snackbar,{open:e,onClose:i,sx:{position:"relative","& .MuiSnackbarContent-root":{minWidth:"auto"}},TransitionProps:{enter:!0,exit:!0},children:_jsxruntime.jsx.call(void 0, _material.Alert,{variant:"filled",severity:o.severity,onClose:i,sx:{width:"100%",minWidth:"280px",maxWidth:"400px",wordBreak:"break-word"},children:o.allowHtml?_jsxruntime.jsx.call(void 0, "span",{dangerouslySetInnerHTML:{__html:ue(o.message)}}):_jsxruntime.jsx.call(void 0, "span",{children:o.message})})})},$= exports.e =()=>{let o=_react.useContext.call(void 0, B);if(!o)throw new Error("useGlobalNotification debe ser usado dentro de un GlobalNotificationProvider");return o};var Z=_react.createContext.call(void 0, void 0);function Te({children:o,options:r={},config:e,showNotifications:t=!1,notificationOptions:i={}}){let u;try{let{showNotification:s}=$();u=s}catch (e5){}let E=_react2.default.useMemo(()=>({...r,showNotification:u,onSessionExpired:()=>{_optionalChain([r, 'access', _76 => _76.onSessionExpired, 'optionalCall', _77 => _77()])}}),[r,u]),h=Y(E),S=_react.useMemo.call(void 0, ()=>{let s,n,a,d,m,p="unknown";if(_optionalChain([e, 'optionalAccess', _78 => _78.publicApiKey])&&(s=e.publicApiKey,p="props"),_optionalChain([e, 'optionalAccess', _79 => _79.env])&&(n=e.env),_optionalChain([e, 'optionalAccess', _80 => _80.appName])&&(a=e.appName),_optionalChain([e, 'optionalAccess', _81 => _81.loginActions])&&(d=e.loginActions),_optionalChain([e, 'optionalAccess', _82 => _82.logo])&&(m=e.logo),!s){let x=_chunkAT74WV5Wjs.a.call(void 0, "publicApiKey"),I=_chunkAT74WV5Wjs.a.call(void 0, "environment"),L=_chunkAT74WV5Wjs.a.call(void 0, "appName"),A=_chunkAT74WV5Wjs.a.call(void 0, "loginActions"),f=_chunkAT74WV5Wjs.a.call(void 0, "logo");x&&(s=x,p="cookies"),I&&["dev","stg","prod"].includes(I)&&(n=I),L&&(a=decodeURIComponent(L)),A&&(d=decodeURIComponent(A).split(",").map(P=>P.trim()).filter(Boolean)),f&&(m=decodeURIComponent(f))}return{publicApiKey:s,env:n,appName:a,loginActions:d,logo:m}},[e]),T=_react.useMemo.call(void 0, ()=>{if(!_optionalChain([h, 'access', _83 => _83.tokens, 'optionalAccess', _84 => _84.accessToken])||!h.isAuthenticated)return null;try{let s=_chunkAT74WV5Wjs.h.call(void 0, h.tokens.accessToken);if(s&&s.sub&&s.email&&s.subscriber){let n={_id:s.sub,email:s.email,subscriberKey:s.subscriber};return Object.keys(s).forEach(a=>{["sub","email","subscriber"].includes(a)||(n[a]=s[a])}),n}}catch(s){console.error("Error decoding JWT token for sessionData:",s)}return null},[_optionalChain([h, 'access', _85 => _85.tokens, 'optionalAccess', _86 => _86.accessToken]),h.isAuthenticated]),N={...h,sessionData:T,config:S},c={enabled:t,maxNotifications:i.maxNotifications||5,defaultAutoHideDuration:i.defaultAutoHideDuration||6e3,position:i.position||{vertical:"top",horizontal:"right"}};return _jsxruntime.jsx.call(void 0, Z.Provider,{value:N,children:o})}function Qe(o){let r={enabled:o.showNotifications,maxNotifications:_optionalChain([o, 'access', _87 => _87.notificationOptions, 'optionalAccess', _88 => _88.maxNotifications])||5,defaultAutoHideDuration:_optionalChain([o, 'access', _89 => _89.notificationOptions, 'optionalAccess', _90 => _90.defaultAutoHideDuration])||6e3,position:_optionalChain([o, 'access', _91 => _91.notificationOptions, 'optionalAccess', _92 => _92.position])||{vertical:"top",horizontal:"right"},allowHtml:_optionalChain([o, 'access', _93 => _93.notificationOptions, 'optionalAccess', _94 => _94.allowHtml])||!1};return _jsxruntime.jsx.call(void 0, W,{...r,children:_jsxruntime.jsx.call(void 0, Te,{...o})})}function ye(){let o=_react.useContext.call(void 0, Z);if(o===void 0)throw new Error("useSessionContext must be used within a SessionProvider");return o}function er(){let o=ye();return o.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:"})," ",o.isAuthenticated?"Yes":"No"]}),_jsxruntime.jsxs.call(void 0, "div",{children:[_jsxruntime.jsx.call(void 0, "strong",{children:"Loading:"})," ",o.isLoading?"Yes":"No"]}),_jsxruntime.jsxs.call(void 0, "div",{children:[_jsxruntime.jsx.call(void 0, "strong",{children:"Error:"})," ",o.error||"None"]}),o.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:"})," ",o.tokens.accessToken.substring(0,20),"..."]}),_jsxruntime.jsxs.call(void 0, "div",{children:[_jsxruntime.jsx.call(void 0, "strong",{children:"Refresh Token:"})," ",o.tokens.refreshToken.substring(0,20),"..."]}),_jsxruntime.jsxs.call(void 0, "div",{children:[_jsxruntime.jsx.call(void 0, "strong",{children:"Access Expires In:"})," ",Math.round(o.expiresIn/1e3/60)," minutes"]}),_jsxruntime.jsxs.call(void 0, "div",{children:[_jsxruntime.jsx.call(void 0, "strong",{children:"Refresh Expires In:"})," ",Math.round(o.refreshExpiresIn/1e3/60/60)," hours"]}),_jsxruntime.jsxs.call(void 0, "div",{children:[_jsxruntime.jsx.call(void 0, "strong",{children:"Expiring Soon:"})," ",o.isExpiringSoon?"Yes":"No"]})]})]}):_jsxruntime.jsx.call(void 0, "div",{children:"Session not initialized"})}var nr=(o={})=>{let{autoFetch:r=!0,retryOnError:e=!1,maxRetries:t=3}=o,[i,u]=_react.useState.call(void 0, null),[E,h]=_react.useState.call(void 0, !1),[S,T]=_react.useState.call(void 0, null),[N,c]=_react.useState.call(void 0, {}),s=_react.useRef.call(void 0, null),n=_react.useRef.call(void 0, !0),a=_react.useRef.call(void 0, 0),d=_react.useRef.call(void 0, 0),m=_react.useCallback.call(void 0, ()=>{u(null),T(null),h(!1),c({})},[]),p=_react.useCallback.call(void 0, async()=>{let x=_chunkAT74WV5Wjs.i.call(void 0, );if(!x){n.current&&(T("No user email available"),h(!1));return}s.current&&s.current.abort();let I=new AbortController;s.current=I;let L=++a.current;try{n.current&&(h(!0),T(null));let A=await _crudifybrowser2.default.readItems("users",{filter:{email:x},pagination:{limit:1}});if(L===a.current&&n.current&&!I.signal.aborted)if(A.success&&A.data&&A.data.length>0){let f=A.data[0];u(f);let H={fullProfile:f,totalFields:Object.keys(f).length,displayData:{id:f.id,email:f.email,username:f.username,firstName:f.firstName,lastName:f.lastName,fullName:f.fullName||`${f.firstName||""} ${f.lastName||""}`.trim(),role:f.role,permissions:f.permissions||[],isActive:f.isActive,lastLogin:f.lastLogin,createdAt:f.createdAt,updatedAt:f.updatedAt,...Object.keys(f).filter(P=>!["id","email","username","firstName","lastName","fullName","role","permissions","isActive","lastLogin","createdAt","updatedAt"].includes(P)).reduce((P,z)=>({...P,[z]:f[z]}),{})}};c(H),T(null),d.current=0}else T("User profile not found"),u(null),c({})}catch(A){if(L===a.current&&n.current){let f=A;if(f.name==="AbortError")return;e&&d.current<t&&(_optionalChain([f, 'access', _95 => _95.message, 'optionalAccess', _96 => _96.includes, 'call', _97 => _97("Network Error")])||_optionalChain([f, 'access', _98 => _98.message, 'optionalAccess', _99 => _99.includes, 'call', _100 => _100("Failed to fetch")]))?(d.current++,setTimeout(()=>{n.current&&p()},1e3*d.current)):(T("Failed to load user profile"),u(null),c({}))}}finally{L===a.current&&n.current&&h(!1),s.current===I&&(s.current=null)}},[e,t]);return _react.useEffect.call(void 0, ()=>{r&&p()},[r,p]),_react.useEffect.call(void 0, ()=>(n.current=!0,()=>{n.current=!1,s.current&&(s.current.abort(),s.current=null)}),[]),{userProfile:i,loading:E,error:S,extendedData:N,refreshProfile:p,clearProfile:m}};exports.a = g; exports.b = C; exports.c = Y; exports.d = W; exports.e = $; exports.f = Qe; exports.g = ye; exports.h = er; exports.i = nr;
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } 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 _chunkVQUXX5W3js = require('./chunk-VQUXX5W3.js');var _react = require('react');var _crudifybrowser = require('@nocios/crudify-browser'); var _crudifybrowser2 = _interopRequireDefault(_crudifybrowser);var G=(S={})=>{let{autoFetch:c=!0,retryOnError:N=!1,maxRetries:g=3}=S,{isAuthenticated:T,isInitialized:I,sessionData:a,tokens:R}=_chunkVQUXX5W3js.g.call(void 0, ),[E,d]=_react.useState.call(void 0, null),[y,O]=_react.useState.call(void 0, !1),[A,p]=_react.useState.call(void 0, null),u=_react.useRef.call(void 0, null),o=_react.useRef.call(void 0, !0),m=_react.useRef.call(void 0, 0),l=_react.useRef.call(void 0, 0),L=_react.useCallback.call(void 0, ()=>a&&(a.email||a["cognito:username"])||null,[a]),P=_react.useCallback.call(void 0, ()=>{d(null),p(null),O(!1),l.current=0},[]),w=_react.useCallback.call(void 0, async()=>{let x=L();if(!x){o.current&&(p("No user email available from session data"),O(!1));return}if(!I){o.current&&(p("Session not initialized"),O(!1));return}u.current&&u.current.abort();let e=new AbortController;u.current=e;let i=++m.current;try{o.current&&(O(!0),p(null));let r=await _crudifybrowser2.default.readItems("users",{filter:{email:x},pagination:{limit:1}});if(i===m.current&&o.current&&!e.signal.aborted){let t=null;if(r.success){if(Array.isArray(r.data)&&r.data.length>0)t=r.data[0];else if(_optionalChain([r, 'access', _2 => _2.data, 'optionalAccess', _3 => _3.response, 'optionalAccess', _4 => _4.data]))try{let s=r.data.response.data,n=typeof s=="string"?JSON.parse(s):s;n&&n.items&&Array.isArray(n.items)&&n.items.length>0&&(t=n.items[0])}catch (e2){}else if(r.data&&typeof r.data=="object")r.data.items&&Array.isArray(r.data.items)&&r.data.items.length>0&&(t=r.data.items[0]);else if(_optionalChain([r, 'access', _5 => _5.data, 'optionalAccess', _6 => _6.data, 'optionalAccess', _7 => _7.response, 'optionalAccess', _8 => _8.data]))try{let s=r.data.data.response.data,n=typeof s=="string"?JSON.parse(s):s;n&&n.items&&Array.isArray(n.items)&&n.items.length>0&&(t=n.items[0])}catch (e3){}}t?(d(t),p(null),l.current=0):(p("User profile not found in database"),d(null))}}catch(r){if(i===m.current&&o.current){let t=r;if(t.name==="AbortError")return;N&&l.current<g&&(_optionalChain([t, 'access', _9 => _9.message, 'optionalAccess', _10 => _10.includes, 'call', _11 => _11("Network Error")])||_optionalChain([t, 'access', _12 => _12.message, 'optionalAccess', _13 => _13.includes, 'call', _14 => _14("Failed to fetch")]))?(l.current++,setTimeout(()=>{o.current&&w()},1e3*l.current)):(p("Failed to load user profile from database"),d(null))}}finally{i===m.current&&o.current&&O(!1),u.current===e&&(u.current=null)}},[I,L,N,g]);return _react.useEffect.call(void 0, ()=>{c&&T&&I?w():T||P()},[c,T,I,w,P]),_react.useEffect.call(void 0, ()=>(o.current=!0,()=>{o.current=!1,u.current&&(u.current.abort(),u.current=null)}),[]),{user:{session:a,data:E},loading:y,error:A,refreshProfile:w,clearProfile:P}};var ee=()=>{let{isAuthenticated:S,isLoading:c,isInitialized:N,tokens:g,error:T,sessionData:I,login:a,logout:R,refreshTokens:E,clearError:d,getTokenInfo:y,isExpiringSoon:O,expiresIn:A,refreshExpiresIn:p}=_chunkVQUXX5W3js.g.call(void 0, ),u=_react.useCallback.call(void 0, m=>{m?console.warn("useAuth.setToken() is deprecated. Use login() method instead for better security."):R()},[R]),o=_optionalChain([g, 'optionalAccess', _15 => _15.expiresAt])?new Date(g.expiresAt):null;return{isAuthenticated:S,loading:c,error:T,token:_optionalChain([g, 'optionalAccess', _16 => _16.accessToken])||null,user:I,tokenExpiration:o,setToken:u,logout:R,refreshToken:E,login:a,isExpiringSoon:O,expiresIn:A,refreshExpiresIn:p,getTokenInfo:y,clearError:d}};var oe=()=>{let{isInitialized:S,isLoading:c,error:N,isAuthenticated:g,login:T}=_chunkVQUXX5W3js.g.call(void 0, ),I=_react.useCallback.call(void 0, ()=>S&&!c&&!N,[S,c,N]),a=_react.useCallback.call(void 0, async()=>new Promise((o,m)=>{let l=()=>{I()?o():N?m(new Error(N)):setTimeout(l,100)};l()}),[I,N]),R=_react.useCallback.call(void 0, async()=>{if(!I())throw new Error("System not ready. Check isInitialized, isLoading, and error states.")},[I]),E=_react.useCallback.call(void 0, async(o,m,l)=>(await R(),await _crudifybrowser2.default.readItems(o,m||{},l)),[R]),d=_react.useCallback.call(void 0, async(o,m,l)=>(await R(),await _crudifybrowser2.default.readItem(o,m,l)),[R]),y=_react.useCallback.call(void 0, async(o,m,l)=>(await R(),await _crudifybrowser2.default.createItem(o,m,l)),[R]),O=_react.useCallback.call(void 0, async(o,m,l)=>(await R(),await _crudifybrowser2.default.updateItem(o,m,l)),[R]),A=_react.useCallback.call(void 0, async(o,m,l)=>(await R(),await _crudifybrowser2.default.deleteItem(o,m,l)),[R]),p=_react.useCallback.call(void 0, async(o,m)=>(await R(),await _crudifybrowser2.default.transaction(o,m)),[R]),u=_react.useCallback.call(void 0, async(o,m)=>{try{let l=await T(o,m);return l.success?{success:!0,data:l.tokens}:{success:!1,errors:l.error||"Login failed"}}catch(l){return{success:!1,errors:l instanceof Error?l.message:"Login failed"}}},[T]);return{readItems:E,readItem:d,createItem:y,updateItem:O,deleteItem:A,transaction:p,login:u,isInitialized:S,isInitializing:c,initializationError:N,isReady:I,waitForReady:a}};var Y={INVALID_CREDENTIALS:"warning",UNAUTHORIZED:"warning",INVALID_API_KEY:"error",USER_NOT_FOUND:"warning",USER_NOT_ACTIVE:"warning",NO_PERMISSION:"warning",ITEM_NOT_FOUND:"info",NOT_FOUND:"info",IN_USE:"warning",FIELD_ERROR:"warning",BAD_REQUEST:"warning",INTERNAL_SERVER_ERROR:"error",DATABASE_CONNECTION_ERROR:"error",INVALID_CONFIGURATION:"error",UNKNOWN_OPERATION:"error",TOO_MANY_REQUESTS:"warning"},v={INVALID_CREDENTIALS:"errors.auth.INVALID_CREDENTIALS",UNAUTHORIZED:"errors.auth.UNAUTHORIZED",INVALID_API_KEY:"errors.auth.INVALID_API_KEY",USER_NOT_FOUND:"errors.auth.USER_NOT_FOUND",USER_NOT_ACTIVE:"errors.auth.USER_NOT_ACTIVE",NO_PERMISSION:"errors.auth.NO_PERMISSION",ITEM_NOT_FOUND:"errors.data.ITEM_NOT_FOUND",NOT_FOUND:"errors.data.NOT_FOUND",IN_USE:"errors.data.IN_USE",FIELD_ERROR:"errors.data.FIELD_ERROR",BAD_REQUEST:"errors.data.BAD_REQUEST",INTERNAL_SERVER_ERROR:"errors.system.INTERNAL_SERVER_ERROR",DATABASE_CONNECTION_ERROR:"errors.system.DATABASE_CONNECTION_ERROR",INVALID_CONFIGURATION:"errors.system.INVALID_CONFIGURATION",UNKNOWN_OPERATION:"errors.system.UNKNOWN_OPERATION",TOO_MANY_REQUESTS:"errors.system.TOO_MANY_REQUESTS"},le= exports.d =(S={})=>{let{showNotification:c}=_chunkVQUXX5W3js.e.call(void 0, ),{showSuccessNotifications:N=!1,showErrorNotifications:g=!0,customErrorMessages:T={},defaultErrorMessage:I="Ha ocurrido un error inesperado",autoHideDuration:a=6e3,appStructure:R=[],translateFn:E=e=>e}=S,d=_react.useCallback.call(void 0, e=>!(!e.success&&e.errors&&(Object.keys(e.errors).some(r=>r!=="_error"&&r!=="_graphql"&&r!=="_transaction")||_optionalChain([e, 'access', _17 => _17.errors, 'access', _18 => _18._transaction, 'optionalAccess', _19 => _19.includes, 'call', _20 => _20("ONE_OR_MORE_OPERATIONS_FAILED")])||_optionalChain([e, 'access', _21 => _21.errors, 'access', _22 => _22._error, 'optionalAccess', _23 => _23.includes, 'call', _24 => _24("TOO_MANY_REQUESTS")]))||!e.success&&_optionalChain([e, 'access', _25 => _25.data, 'optionalAccess', _26 => _26.response, 'optionalAccess', _27 => _27.status])==="TOO_MANY_REQUESTS"),[]),y=_react.useCallback.call(void 0, (e,i)=>{let r=E(e);return r===e?i||E("error.unknown"):r},[E]),O=_react.useCallback.call(void 0, e=>["create","update","delete"].includes(e),[]),A=_react.useCallback.call(void 0, (e,i)=>N?O(e)&&i?!0:R.some(r=>r.key===e):!1,[N,R,O]),p=_react.useCallback.call(void 0, (e,i,r)=>{let t=_optionalChain([r, 'optionalAccess', _28 => _28.key])&&typeof r.key=="string"?r.key:e,s=`action.onSuccess.${t}`,n=y(s);if(n!==E("error.unknown")){if(O(t)&&i){let f=`action.${i}Singular`,_=y(f);if(_!==E("error.unknown"))return E(s,{item:_});{let M=`action.onSuccess.${t}WithoutItem`,k=y(M);return k!==E("error.unknown")?k:n}}return n}return E("success.transaction")},[y,E,O]),u=_react.useCallback.call(void 0, e=>{if(e.errorCode&&T[e.errorCode])return T[e.errorCode];if(e.errorCode&&v[e.errorCode])return y(v[e.errorCode]);if(e.errorCode){let i=[`errors.auth.${e.errorCode}`,`errors.data.${e.errorCode}`,`errors.system.${e.errorCode}`,`errors.${e.errorCode}`];for(let r of i){let t=y(r);if(t!==E("error.unknown"))return t}}if(typeof e.data=="string"&&e.data.startsWith("errors.")){let i=y(e.data);if(i!==E("error.unknown"))return i}if(e.errors&&Object.keys(e.errors).length>0){let i=Object.keys(e.errors);if(i.length===1&&i[0]==="_transaction"){let r=e.errors._transaction;if(_optionalChain([r, 'optionalAccess', _29 => _29.includes, 'call', _30 => _30("ONE_OR_MORE_OPERATIONS_FAILED")]))return"";if(Array.isArray(r)&&r.length>0){let t=r[0];if(typeof t=="string"&&t!=="ONE_OR_MORE_OPERATIONS_FAILED")try{let s=JSON.parse(t);if(Array.isArray(s)&&s.length>0){let n=s[0];if(_optionalChain([n, 'optionalAccess', _31 => _31.response, 'optionalAccess', _32 => _32.errorCode])){let f=n.response.errorCode;if(v[f])return y(v[f]);let _=[`errors.auth.${f}`,`errors.data.${f}`,`errors.system.${f}`,`errors.${f}`];for(let M of _){let k=y(M);if(k!==y("error.unknown"))return k}}if(_optionalChain([n, 'optionalAccess', _33 => _33.response, 'optionalAccess', _34 => _34.data]))return n.response.data}if(_optionalChain([s, 'optionalAccess', _35 => _35.response, 'optionalAccess', _36 => _36.message])){let n=s.response.message.toLowerCase();return n.includes("expired")?y("resetPassword.linkExpired","El enlace ha expirado"):n.includes("invalid")?y("resetPassword.invalidCode","C\xF3digo inv\xE1lido"):s.response.message}}catch (e4){return t.toLowerCase().includes("expired")?y("resetPassword.linkExpired","El enlace ha expirado"):t.toLowerCase().includes("invalid")?y("resetPassword.invalidCode","C\xF3digo inv\xE1lido"):t}}return y("error.transaction","Error en la operaci\xF3n")}if(i.length===1&&i[0]==="_error"){let r=e.errors._error;return Array.isArray(r)?r[0]:String(r)}return i.length===1&&i[0]==="_graphql"?y("errors.system.DATABASE_CONNECTION_ERROR"):`${y("errors.data.FIELD_ERROR")}: ${i.join(", ")}`}return I||E("error.unknown")},[T,I,E,y]),o=_react.useCallback.call(void 0, e=>e.errorCode&&Y[e.errorCode]?Y[e.errorCode]:"error",[]),m=_react.useCallback.call(void 0, async(e,i,r)=>{let t=await _crudifybrowser2.default.createItem(e,i,r);if(!t.success&&g&&d(t)){let s=u(t),n=o(t);c(s,n,{autoHideDuration:a})}else if(t.success){let s=_optionalChain([r, 'optionalAccess', _37 => _37.actionConfig]),n=_optionalChain([s, 'optionalAccess', _38 => _38.key])||"create",f=_optionalChain([s, 'optionalAccess', _39 => _39.moduleKey])||e;if(A(n,f)){let _=p(n,f,s);c(_,"success",{autoHideDuration:a})}}return t},[g,A,c,u,o,p,a,d]),l=_react.useCallback.call(void 0, async(e,i,r)=>{let t=await _crudifybrowser2.default.updateItem(e,i,r);if(!t.success&&g&&d(t)){let s=u(t),n=o(t);c(s,n,{autoHideDuration:a})}else if(t.success){let s=_optionalChain([r, 'optionalAccess', _40 => _40.actionConfig]),n=_optionalChain([s, 'optionalAccess', _41 => _41.key])||"update",f=_optionalChain([s, 'optionalAccess', _42 => _42.moduleKey])||e;if(A(n,f)){let _=p(n,f,s);c(_,"success",{autoHideDuration:a})}}return t},[g,A,c,u,o,p,a,d]),L=_react.useCallback.call(void 0, async(e,i,r)=>{let t=await _crudifybrowser2.default.deleteItem(e,i,r);if(!t.success&&g&&d(t)){let s=u(t),n=o(t);c(s,n,{autoHideDuration:a})}else if(t.success){let s=_optionalChain([r, 'optionalAccess', _43 => _43.actionConfig]),n=_optionalChain([s, 'optionalAccess', _44 => _44.key])||"delete",f=_optionalChain([s, 'optionalAccess', _45 => _45.moduleKey])||e;if(A(n,f)){let _=p(n,f,s);c(_,"success",{autoHideDuration:a})}}return t},[g,A,c,u,o,p,a,d]),P=_react.useCallback.call(void 0, async(e,i,r)=>{let t=await _crudifybrowser2.default.readItem(e,i,r);if(!t.success&&g&&d(t)){let s=u(t),n=o(t);c(s,n,{autoHideDuration:a})}return t},[g,c,u,o,a,d]),w=_react.useCallback.call(void 0, async(e,i,r)=>{let t=await _crudifybrowser2.default.readItems(e,i,r);if(!t.success&&g&&d(t)){let s=u(t),n=o(t);c(s,n,{autoHideDuration:a})}return t},[g,c,u,o,a,d]),V=_react.useCallback.call(void 0, async(e,i)=>{let r=await _crudifybrowser2.default.transaction(e,i),t=_optionalChain([i, 'optionalAccess', _46 => _46.skipNotifications])===!0;if(!t&&!r.success&&g&&d(r)){let s=u(r),n=o(r);c(s,n,{autoHideDuration:a})}else if(!t&&r.success){let s="transaction",n,f=null;if(_optionalChain([i, 'optionalAccess', _47 => _47.actionConfig])?(f=i.actionConfig,s=f.key,n=f.moduleKey):Array.isArray(e)&&e.length>0&&e[0].operation&&(s=e[0].operation,f=R.find(_=>_.key===s),f&&(n=f.moduleKey)),A(s,n)){let _=p(s,n,f);c(_,"success",{autoHideDuration:a})}}return r},[g,A,c,u,o,p,a,d,R]),x=_react.useCallback.call(void 0, (e,i)=>{if(!e.success&&g&&d(e)){let r=u(e),t=o(e);c(r,t,{autoHideDuration:a})}else e.success&&N&&i&&c(i,"success",{autoHideDuration:a});return e},[g,N,c,u,o,a,d,E]);return{createItem:m,updateItem:l,deleteItem:L,readItem:P,readItems:w,transaction:V,handleResponse:x,getErrorMessage:u,getErrorSeverity:o,shouldShowNotification:d}};exports.a = G; exports.b = ee; exports.c = oe; exports.d = le;
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } 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 _chunkTLGRXZCSjs = require('./chunk-TLGRXZCS.js');var _react = require('react');var _crudifybrowser = require('@nocios/crudify-browser'); var _crudifybrowser2 = _interopRequireDefault(_crudifybrowser);var G=(S={})=>{let{autoFetch:c=!0,retryOnError:N=!1,maxRetries:g=3}=S,{isAuthenticated:T,isInitialized:I,sessionData:a,tokens:R}=_chunkTLGRXZCSjs.g.call(void 0, ),[E,d]=_react.useState.call(void 0, null),[y,O]=_react.useState.call(void 0, !1),[A,p]=_react.useState.call(void 0, null),u=_react.useRef.call(void 0, null),o=_react.useRef.call(void 0, !0),m=_react.useRef.call(void 0, 0),l=_react.useRef.call(void 0, 0),L=_react.useCallback.call(void 0, ()=>a&&(a.email||a["cognito:username"])||null,[a]),P=_react.useCallback.call(void 0, ()=>{d(null),p(null),O(!1),l.current=0},[]),w=_react.useCallback.call(void 0, async()=>{let x=L();if(!x){o.current&&(p("No user email available from session data"),O(!1));return}if(!I){o.current&&(p("Session not initialized"),O(!1));return}u.current&&u.current.abort();let e=new AbortController;u.current=e;let i=++m.current;try{o.current&&(O(!0),p(null));let r=await _crudifybrowser2.default.readItems("users",{filter:{email:x},pagination:{limit:1}});if(i===m.current&&o.current&&!e.signal.aborted){let t=null;if(r.success){if(Array.isArray(r.data)&&r.data.length>0)t=r.data[0];else if(_optionalChain([r, 'access', _2 => _2.data, 'optionalAccess', _3 => _3.response, 'optionalAccess', _4 => _4.data]))try{let s=r.data.response.data,n=typeof s=="string"?JSON.parse(s):s;n&&n.items&&Array.isArray(n.items)&&n.items.length>0&&(t=n.items[0])}catch (e2){}else if(r.data&&typeof r.data=="object")r.data.items&&Array.isArray(r.data.items)&&r.data.items.length>0&&(t=r.data.items[0]);else if(_optionalChain([r, 'access', _5 => _5.data, 'optionalAccess', _6 => _6.data, 'optionalAccess', _7 => _7.response, 'optionalAccess', _8 => _8.data]))try{let s=r.data.data.response.data,n=typeof s=="string"?JSON.parse(s):s;n&&n.items&&Array.isArray(n.items)&&n.items.length>0&&(t=n.items[0])}catch (e3){}}t?(d(t),p(null),l.current=0):(p("User profile not found in database"),d(null))}}catch(r){if(i===m.current&&o.current){let t=r;if(t.name==="AbortError")return;N&&l.current<g&&(_optionalChain([t, 'access', _9 => _9.message, 'optionalAccess', _10 => _10.includes, 'call', _11 => _11("Network Error")])||_optionalChain([t, 'access', _12 => _12.message, 'optionalAccess', _13 => _13.includes, 'call', _14 => _14("Failed to fetch")]))?(l.current++,setTimeout(()=>{o.current&&w()},1e3*l.current)):(p("Failed to load user profile from database"),d(null))}}finally{i===m.current&&o.current&&O(!1),u.current===e&&(u.current=null)}},[I,L,N,g]);return _react.useEffect.call(void 0, ()=>{c&&T&&I?w():T||P()},[c,T,I,w,P]),_react.useEffect.call(void 0, ()=>(o.current=!0,()=>{o.current=!1,u.current&&(u.current.abort(),u.current=null)}),[]),{user:{session:a,data:E},loading:y,error:A,refreshProfile:w,clearProfile:P}};var ee=()=>{let{isAuthenticated:S,isLoading:c,isInitialized:N,tokens:g,error:T,sessionData:I,login:a,logout:R,refreshTokens:E,clearError:d,getTokenInfo:y,isExpiringSoon:O,expiresIn:A,refreshExpiresIn:p}=_chunkTLGRXZCSjs.g.call(void 0, ),u=_react.useCallback.call(void 0, m=>{m?console.warn("useAuth.setToken() is deprecated. Use login() method instead for better security."):R()},[R]),o=_optionalChain([g, 'optionalAccess', _15 => _15.expiresAt])?new Date(g.expiresAt):null;return{isAuthenticated:S,loading:c,error:T,token:_optionalChain([g, 'optionalAccess', _16 => _16.accessToken])||null,user:I,tokenExpiration:o,setToken:u,logout:R,refreshToken:E,login:a,isExpiringSoon:O,expiresIn:A,refreshExpiresIn:p,getTokenInfo:y,clearError:d}};var oe=()=>{let{isInitialized:S,isLoading:c,error:N,isAuthenticated:g,login:T}=_chunkTLGRXZCSjs.g.call(void 0, ),I=_react.useCallback.call(void 0, ()=>S&&!c&&!N,[S,c,N]),a=_react.useCallback.call(void 0, async()=>new Promise((o,m)=>{let l=()=>{I()?o():N?m(new Error(N)):setTimeout(l,100)};l()}),[I,N]),R=_react.useCallback.call(void 0, async()=>{if(!I())throw new Error("System not ready. Check isInitialized, isLoading, and error states.")},[I]),E=_react.useCallback.call(void 0, async(o,m,l)=>(await R(),await _crudifybrowser2.default.readItems(o,m||{},l)),[R]),d=_react.useCallback.call(void 0, async(o,m,l)=>(await R(),await _crudifybrowser2.default.readItem(o,m,l)),[R]),y=_react.useCallback.call(void 0, async(o,m,l)=>(await R(),await _crudifybrowser2.default.createItem(o,m,l)),[R]),O=_react.useCallback.call(void 0, async(o,m,l)=>(await R(),await _crudifybrowser2.default.updateItem(o,m,l)),[R]),A=_react.useCallback.call(void 0, async(o,m,l)=>(await R(),await _crudifybrowser2.default.deleteItem(o,m,l)),[R]),p=_react.useCallback.call(void 0, async(o,m)=>(await R(),await _crudifybrowser2.default.transaction(o,m)),[R]),u=_react.useCallback.call(void 0, async(o,m)=>{try{let l=await T(o,m);return l.success?{success:!0,data:l.tokens}:{success:!1,errors:l.error||"Login failed"}}catch(l){return{success:!1,errors:l instanceof Error?l.message:"Login failed"}}},[T]);return{readItems:E,readItem:d,createItem:y,updateItem:O,deleteItem:A,transaction:p,login:u,isInitialized:S,isInitializing:c,initializationError:N,isReady:I,waitForReady:a}};var Y={INVALID_CREDENTIALS:"warning",UNAUTHORIZED:"warning",INVALID_API_KEY:"error",USER_NOT_FOUND:"warning",USER_NOT_ACTIVE:"warning",NO_PERMISSION:"warning",ITEM_NOT_FOUND:"info",NOT_FOUND:"info",IN_USE:"warning",FIELD_ERROR:"warning",BAD_REQUEST:"warning",INTERNAL_SERVER_ERROR:"error",DATABASE_CONNECTION_ERROR:"error",INVALID_CONFIGURATION:"error",UNKNOWN_OPERATION:"error",TOO_MANY_REQUESTS:"warning"},v={INVALID_CREDENTIALS:"errors.auth.INVALID_CREDENTIALS",UNAUTHORIZED:"errors.auth.UNAUTHORIZED",INVALID_API_KEY:"errors.auth.INVALID_API_KEY",USER_NOT_FOUND:"errors.auth.USER_NOT_FOUND",USER_NOT_ACTIVE:"errors.auth.USER_NOT_ACTIVE",NO_PERMISSION:"errors.auth.NO_PERMISSION",ITEM_NOT_FOUND:"errors.data.ITEM_NOT_FOUND",NOT_FOUND:"errors.data.NOT_FOUND",IN_USE:"errors.data.IN_USE",FIELD_ERROR:"errors.data.FIELD_ERROR",BAD_REQUEST:"errors.data.BAD_REQUEST",INTERNAL_SERVER_ERROR:"errors.system.INTERNAL_SERVER_ERROR",DATABASE_CONNECTION_ERROR:"errors.system.DATABASE_CONNECTION_ERROR",INVALID_CONFIGURATION:"errors.system.INVALID_CONFIGURATION",UNKNOWN_OPERATION:"errors.system.UNKNOWN_OPERATION",TOO_MANY_REQUESTS:"errors.system.TOO_MANY_REQUESTS"},le= exports.d =(S={})=>{let{showNotification:c}=_chunkTLGRXZCSjs.e.call(void 0, ),{showSuccessNotifications:N=!1,showErrorNotifications:g=!0,customErrorMessages:T={},defaultErrorMessage:I="Ha ocurrido un error inesperado",autoHideDuration:a=6e3,appStructure:R=[],translateFn:E=e=>e}=S,d=_react.useCallback.call(void 0, e=>!(!e.success&&e.errors&&(Object.keys(e.errors).some(r=>r!=="_error"&&r!=="_graphql"&&r!=="_transaction")||_optionalChain([e, 'access', _17 => _17.errors, 'access', _18 => _18._transaction, 'optionalAccess', _19 => _19.includes, 'call', _20 => _20("ONE_OR_MORE_OPERATIONS_FAILED")])||_optionalChain([e, 'access', _21 => _21.errors, 'access', _22 => _22._error, 'optionalAccess', _23 => _23.includes, 'call', _24 => _24("TOO_MANY_REQUESTS")]))||!e.success&&_optionalChain([e, 'access', _25 => _25.data, 'optionalAccess', _26 => _26.response, 'optionalAccess', _27 => _27.status])==="TOO_MANY_REQUESTS"),[]),y=_react.useCallback.call(void 0, (e,i)=>{let r=E(e);return r===e?i||E("error.unknown"):r},[E]),O=_react.useCallback.call(void 0, e=>["create","update","delete"].includes(e),[]),A=_react.useCallback.call(void 0, (e,i)=>N?O(e)&&i?!0:R.some(r=>r.key===e):!1,[N,R,O]),p=_react.useCallback.call(void 0, (e,i,r)=>{let t=_optionalChain([r, 'optionalAccess', _28 => _28.key])&&typeof r.key=="string"?r.key:e,s=`action.onSuccess.${t}`,n=y(s);if(n!==E("error.unknown")){if(O(t)&&i){let f=`action.${i}Singular`,_=y(f);if(_!==E("error.unknown"))return E(s,{item:_});{let M=`action.onSuccess.${t}WithoutItem`,k=y(M);return k!==E("error.unknown")?k:n}}return n}return E("success.transaction")},[y,E,O]),u=_react.useCallback.call(void 0, e=>{if(e.errorCode&&T[e.errorCode])return T[e.errorCode];if(e.errorCode&&v[e.errorCode])return y(v[e.errorCode]);if(e.errorCode){let i=[`errors.auth.${e.errorCode}`,`errors.data.${e.errorCode}`,`errors.system.${e.errorCode}`,`errors.${e.errorCode}`];for(let r of i){let t=y(r);if(t!==E("error.unknown"))return t}}if(typeof e.data=="string"&&e.data.startsWith("errors.")){let i=y(e.data);if(i!==E("error.unknown"))return i}if(e.errors&&Object.keys(e.errors).length>0){let i=Object.keys(e.errors);if(i.length===1&&i[0]==="_transaction"){let r=e.errors._transaction;if(_optionalChain([r, 'optionalAccess', _29 => _29.includes, 'call', _30 => _30("ONE_OR_MORE_OPERATIONS_FAILED")]))return"";if(Array.isArray(r)&&r.length>0){let t=r[0];if(typeof t=="string"&&t!=="ONE_OR_MORE_OPERATIONS_FAILED")try{let s=JSON.parse(t);if(Array.isArray(s)&&s.length>0){let n=s[0];if(_optionalChain([n, 'optionalAccess', _31 => _31.response, 'optionalAccess', _32 => _32.errorCode])){let f=n.response.errorCode;if(v[f])return y(v[f]);let _=[`errors.auth.${f}`,`errors.data.${f}`,`errors.system.${f}`,`errors.${f}`];for(let M of _){let k=y(M);if(k!==y("error.unknown"))return k}}if(_optionalChain([n, 'optionalAccess', _33 => _33.response, 'optionalAccess', _34 => _34.data]))return n.response.data}if(_optionalChain([s, 'optionalAccess', _35 => _35.response, 'optionalAccess', _36 => _36.message])){let n=s.response.message.toLowerCase();return n.includes("expired")?y("resetPassword.linkExpired","El enlace ha expirado"):n.includes("invalid")?y("resetPassword.invalidCode","C\xF3digo inv\xE1lido"):s.response.message}}catch (e4){return t.toLowerCase().includes("expired")?y("resetPassword.linkExpired","El enlace ha expirado"):t.toLowerCase().includes("invalid")?y("resetPassword.invalidCode","C\xF3digo inv\xE1lido"):t}}return y("error.transaction","Error en la operaci\xF3n")}if(i.length===1&&i[0]==="_error"){let r=e.errors._error;return Array.isArray(r)?r[0]:String(r)}return i.length===1&&i[0]==="_graphql"?y("errors.system.DATABASE_CONNECTION_ERROR"):`${y("errors.data.FIELD_ERROR")}: ${i.join(", ")}`}return I||E("error.unknown")},[T,I,E,y]),o=_react.useCallback.call(void 0, e=>e.errorCode&&Y[e.errorCode]?Y[e.errorCode]:"error",[]),m=_react.useCallback.call(void 0, async(e,i,r)=>{let t=await _crudifybrowser2.default.createItem(e,i,r);if(!t.success&&g&&d(t)){let s=u(t),n=o(t);c(s,n,{autoHideDuration:a})}else if(t.success){let s=_optionalChain([r, 'optionalAccess', _37 => _37.actionConfig]),n=_optionalChain([s, 'optionalAccess', _38 => _38.key])||"create",f=_optionalChain([s, 'optionalAccess', _39 => _39.moduleKey])||e;if(A(n,f)){let _=p(n,f,s);c(_,"success",{autoHideDuration:a})}}return t},[g,A,c,u,o,p,a,d]),l=_react.useCallback.call(void 0, async(e,i,r)=>{let t=await _crudifybrowser2.default.updateItem(e,i,r);if(!t.success&&g&&d(t)){let s=u(t),n=o(t);c(s,n,{autoHideDuration:a})}else if(t.success){let s=_optionalChain([r, 'optionalAccess', _40 => _40.actionConfig]),n=_optionalChain([s, 'optionalAccess', _41 => _41.key])||"update",f=_optionalChain([s, 'optionalAccess', _42 => _42.moduleKey])||e;if(A(n,f)){let _=p(n,f,s);c(_,"success",{autoHideDuration:a})}}return t},[g,A,c,u,o,p,a,d]),L=_react.useCallback.call(void 0, async(e,i,r)=>{let t=await _crudifybrowser2.default.deleteItem(e,i,r);if(!t.success&&g&&d(t)){let s=u(t),n=o(t);c(s,n,{autoHideDuration:a})}else if(t.success){let s=_optionalChain([r, 'optionalAccess', _43 => _43.actionConfig]),n=_optionalChain([s, 'optionalAccess', _44 => _44.key])||"delete",f=_optionalChain([s, 'optionalAccess', _45 => _45.moduleKey])||e;if(A(n,f)){let _=p(n,f,s);c(_,"success",{autoHideDuration:a})}}return t},[g,A,c,u,o,p,a,d]),P=_react.useCallback.call(void 0, async(e,i,r)=>{let t=await _crudifybrowser2.default.readItem(e,i,r);if(!t.success&&g&&d(t)){let s=u(t),n=o(t);c(s,n,{autoHideDuration:a})}return t},[g,c,u,o,a,d]),w=_react.useCallback.call(void 0, async(e,i,r)=>{let t=await _crudifybrowser2.default.readItems(e,i,r);if(!t.success&&g&&d(t)){let s=u(t),n=o(t);c(s,n,{autoHideDuration:a})}return t},[g,c,u,o,a,d]),V=_react.useCallback.call(void 0, async(e,i)=>{let r=await _crudifybrowser2.default.transaction(e,i),t=_optionalChain([i, 'optionalAccess', _46 => _46.skipNotifications])===!0;if(!t&&!r.success&&g&&d(r)){let s=u(r),n=o(r);c(s,n,{autoHideDuration:a})}else if(!t&&r.success){let s="transaction",n,f=null;if(_optionalChain([i, 'optionalAccess', _47 => _47.actionConfig])?(f=i.actionConfig,s=f.key,n=f.moduleKey):Array.isArray(e)&&e.length>0&&e[0].operation&&(s=e[0].operation,f=R.find(_=>_.key===s),f&&(n=f.moduleKey)),A(s,n)){let _=p(s,n,f);c(_,"success",{autoHideDuration:a})}}return r},[g,A,c,u,o,p,a,d,R]),x=_react.useCallback.call(void 0, (e,i)=>{if(!e.success&&g&&d(e)){let r=u(e),t=o(e);c(r,t,{autoHideDuration:a})}else e.success&&N&&i&&c(i,"success",{autoHideDuration:a});return e},[g,N,c,u,o,a,d,E]);return{createItem:m,updateItem:l,deleteItem:L,readItem:P,readItems:w,transaction:V,handleResponse:x,getErrorMessage:u,getErrorSeverity:o,shouldShowNotification:d}};exports.a = G; exports.b = ee; exports.c = oe; exports.d = le;