@nocios/crudify-ui 4.1.46 → 4.1.50
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chunk-5KDBFWCO.mjs +1 -0
- package/dist/chunk-BP6LQCYD.js +1 -0
- package/dist/{chunk-YYT3YOLA.js → chunk-GEIDNOHE.js} +1 -1
- package/dist/{chunk-GCR7Z5DU.mjs → chunk-RQ6YPRUG.mjs} +1 -1
- package/dist/{chunk-CIDTLE52.js → chunk-S2QIQFZJ.js} +1 -1
- package/dist/{chunk-I55IHSY4.mjs → chunk-SQRRFADT.mjs} +1 -1
- package/dist/components.js +1 -1
- package/dist/components.mjs +1 -1
- package/dist/hooks.js +1 -1
- package/dist/hooks.mjs +1 -1
- package/dist/index.d.mts +1 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.js +2 -2
- package/dist/index.mjs +2 -2
- package/package.json +1 -1
- package/dist/chunk-727DU3JS.mjs +0 -1
- package/dist/chunk-MIRR6QT5.js +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a as L,b as Y,f as k,g as B,h as $,i as W}from"./chunk-5JKS55SE.mjs";import{createContext as le,useContext as ce,useEffect as de,useState as w}from"react";import K from"@nocios/crudify-browser";var V=class n{constructor(){this.listeners=[];this.credentials=null;this.isReady=!1}static getInstance(){return n.instance||(n.instance=new n),n.instance}notifyCredentialsReady(i){this.credentials=i,this.isReady=!0,console.log("\u2705 [CredentialsEventBus] Credentials ready, notifying",this.listeners.length,"listeners"),this.listeners.forEach(e=>{try{e(i)}catch(t){console.error("\u274C [CredentialsEventBus] Error in listener:",t)}}),this.listeners=[]}waitForCredentials(){return this.isReady&&this.credentials?(console.log("\u2705 [CredentialsEventBus] Credentials already available"),Promise.resolve(this.credentials)):(console.log("\u23F3 [CredentialsEventBus] Waiting for credentials..."),new Promise(i=>{this.listeners.push(i)}))}reset(){this.credentials=null,this.isReady=!1,this.listeners=[],console.log("\u{1F504} [CredentialsEventBus] Reset")}areCredentialsReady(){return this.isReady&&this.credentials!==null}},j=V.getInstance();import{jsx as ue}from"react/jsx-runtime";var J=le(void 0),Z=({config:n,children:i})=>{let[e,t]=w(!0),[r,u]=w(null),[p,h]=w(!1),[m,T]=w(""),[S,c]=w();console.log("\u{1F50D} CrudifyProvider - Received config:",n),de(()=>{if(console.log("\u{1F50D} CrudifyProvider - useEffect - config.publicApiKey:",n.publicApiKey),console.log("\u{1F50D} CrudifyProvider - useEffect - full config:",n),!n.publicApiKey){console.log("\u274C CrudifyProvider - No publicApiKey provided, setting error"),u("No publicApiKey provided"),t(!1),h(!1);return}console.log("\u2705 CrudifyProvider - publicApiKey found, proceeding with initialization");let o=`${n.publicApiKey}-${n.env}`;if(o===m&&p){t(!1);return}(async()=>{console.log("\u{1F535} [CrudifyProvider] initializeCrudify() CALLED"),t(!0),u(null),h(!1);try{console.log("\u{1F50D} [CrudifyProvider] Calling crudify.config with env:",n.env||"prod"),K.config(n.env||"prod"),console.log("\u{1F50D} [CrudifyProvider] Calling crudify.init with publicApiKey:",n.publicApiKey);let d=await K.init(n.publicApiKey,"none");if(console.log("\u2705 [CrudifyProvider] crudify.init() completed, result:",d),c(d),console.log("\u2705 [CrudifyProvider] Admin credentials stored in state:",d),typeof K.transaction=="function"&&typeof K.login=="function")h(!0),T(o),console.log("\u2705 [CrudifyProvider] Crudify initialized successfully"),d.apiEndpointAdmin&&d.apiKeyEndpointAdmin&&j.notifyCredentialsReady({apiUrl:d.apiEndpointAdmin,apiKey:d.apiKeyEndpointAdmin});else throw new Error("Crudify methods not properly initialized")}catch(d){let A=d instanceof Error?d.message:"Failed to initialize Crudify";console.error("\u274C [CrudifyProvider] Initialization error:",d),u(A),h(!1)}finally{t(!1)}})()},[n.publicApiKey,n.env,m,p]);let s={crudify:p?K:null,isLoading:e,error:r,isInitialized:p,adminCredentials:S};return ue(J.Provider,{value:s,children:i})},q=()=>{let n=ce(J);if(n===void 0)throw new Error("useCrudify must be used within a CrudifyProvider");return n};import U from"crypto-js";var l=class l{static setStorageType(i){l.storageType=i}static generateEncryptionKey(){let i=[navigator.userAgent,navigator.language,navigator.platform,screen.width,screen.height,Date.now().toString(),Math.random().toString(36)].join("|");return U.SHA256(i).toString()}static getEncryptionKey(){if(l.encryptionKey)return l.encryptionKey;let i=window.localStorage;if(!i)return l.encryptionKey=l.generateEncryptionKey(),l.encryptionKey;try{let e=i.getItem(l.ENCRYPTION_KEY_STORAGE);return(!e||e.length<32)&&(e=l.generateEncryptionKey(),i.setItem(l.ENCRYPTION_KEY_STORAGE,e)),l.encryptionKey=e,e}catch{return console.warn("Crudify: Cannot persist encryption key, using temporary key"),l.encryptionKey=l.generateEncryptionKey(),l.encryptionKey}}static isStorageAvailable(i){try{let e=window[i],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(i){try{let e=l.getEncryptionKey();return U.AES.encrypt(i,e).toString()}catch(e){return console.error("Crudify: Encryption failed",e),i}}static decrypt(i){try{let e=l.getEncryptionKey();return U.AES.decrypt(i,e).toString(U.enc.Utf8)||i}catch(e){return console.error("Crudify: Decryption failed",e),i}}static saveTokens(i){let e=l.getStorage();if(e)try{let t={accessToken:i.accessToken,refreshToken:i.refreshToken,expiresAt:i.expiresAt,refreshExpiresAt:i.refreshExpiresAt,savedAt:Date.now()},r=l.encrypt(JSON.stringify(t));e.setItem(l.TOKEN_KEY,r),console.debug("Crudify: Tokens saved successfully")}catch(t){console.error("Crudify: Failed to save tokens",t)}}static getTokens(){let i=l.getStorage();if(!i)return null;try{let e=i.getItem(l.TOKEN_KEY);if(!e)return null;let t=l.decrypt(e),r=JSON.parse(t);return!r.accessToken||!r.refreshToken||!r.expiresAt||!r.refreshExpiresAt?(console.warn("Crudify: Incomplete token data found, clearing storage"),l.clearTokens(),null):Date.now()>=r.refreshExpiresAt?(console.info("Crudify: Refresh token expired, clearing storage"),l.clearTokens(),null):{accessToken:r.accessToken,refreshToken:r.refreshToken,expiresAt:r.expiresAt,refreshExpiresAt:r.refreshExpiresAt}}catch(e){return console.error("Crudify: Failed to retrieve tokens",e),l.clearTokens(),null}}static clearTokens(){let i=l.getStorage();if(i)try{i.removeItem(l.TOKEN_KEY),console.debug("Crudify: Tokens cleared from storage")}catch(e){console.error("Crudify: Failed to clear tokens",e)}}static rotateEncryptionKey(){try{l.clearTokens(),l.encryptionKey=null;let i=window.localStorage;i&&i.removeItem(l.ENCRYPTION_KEY_STORAGE),console.info("Crudify: Encryption key rotated successfully")}catch(i){console.error("Crudify: Failed to rotate encryption key",i)}}static hasValidTokens(){return l.getTokens()!==null}static getExpirationInfo(){let i=l.getTokens();if(!i)return null;let e=Date.now();return{accessExpired:e>=i.expiresAt,refreshExpired:e>=i.refreshExpiresAt,accessExpiresIn:Math.max(0,i.expiresAt-e),refreshExpiresIn:Math.max(0,i.refreshExpiresAt-e)}}static updateAccessToken(i,e){let t=l.getTokens();if(!t){console.warn("Crudify: Cannot update access token, no existing tokens found");return}l.saveTokens({...t,accessToken:i,expiresAt:e})}static subscribeToChanges(i){let e=t=>{if(t.key===l.TOKEN_KEY){if(t.newValue===null){console.debug("Crudify: Tokens removed in another tab"),i(null);return}if(t.newValue){console.debug("Crudify: Tokens updated in another tab");let r=l.getTokens();i(r)}}};return window.addEventListener("storage",e),()=>{window.removeEventListener("storage",e)}}};l.TOKEN_KEY="crudify_tokens",l.ENCRYPTION_KEY_STORAGE="crudify_enc_key",l.encryptionKey=null,l.storageType="localStorage";var f=l;import v from"@nocios/crudify-browser";var z=class n{constructor(){this.config={};this.initialized=!1;this.lastActivityTime=0;this.isRefreshingLocally=!1;this.refreshPromise=null}static getInstance(){return n.instance||(n.instance=new n),n.instance}async initialize(i={}){if(console.log("\u{1F535} [SessionManager] initialize() CALLED"),console.log("\u{1F50D} [SessionManager] Received config:",i),this.initialized){console.warn("SessionManager: Already initialized");return}if(this.config={storageType:"localStorage",autoRestore:!0,enableLogging:!1,...i},f.setStorageType(this.config.storageType||"localStorage"),this.config.enableLogging,v.setTokenInvalidationCallback(()=>{this.log("\u{1F514} Tokens invalidated by crudify-core"),k.emit("SESSION_EXPIRED",{message:"Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente.",source:"crudify-core.clearTokensAndRefreshState"})}),console.log("\u{1F50D} [SessionManager] config.apiEndpointAdmin:",this.config.apiEndpointAdmin),console.log("\u{1F50D} [SessionManager] config.apiKeyEndpointAdmin:",this.config.apiKeyEndpointAdmin),this.config.apiEndpointAdmin&&this.config.apiKeyEndpointAdmin){console.log("\u2705 [SessionManager] Admin credentials provided, storing...");let e=f.getTokens();e?(f.saveTokens({...e,apiEndpointAdmin:this.config.apiEndpointAdmin,apiKeyEndpointAdmin:this.config.apiKeyEndpointAdmin}),console.log("\u2705 [SessionManager] Admin API credentials stored from init (with existing tokens)")):(f.saveTokens({accessToken:"",refreshToken:"",expiresAt:0,refreshExpiresAt:0,apiEndpointAdmin:this.config.apiEndpointAdmin,apiKeyEndpointAdmin:this.config.apiKeyEndpointAdmin}),console.log("\u2705 [SessionManager] Admin API credentials stored (no tokens yet)"));let t=f.getTokens();console.log("\u{1F50D} [SessionManager] After saving, TokenStorage has:",{apiEndpointAdmin:t?.apiEndpointAdmin,apiKeyEndpointAdmin:t?.apiKeyEndpointAdmin})}else console.warn("\u26A0\uFE0F [SessionManager] Admin API credentials NOT provided to SessionManager.initialize()");this.config.autoRestore&&await this.restoreSession(),this.initialized=!0,console.log("\u2705 [SessionManager] Initialized successfully")}async login(i,e){try{console.log("\u{1F535} [SessionManager] login() CALLED");let t=await v.login(i,e);if(!t.success)return console.log("\u274C [SessionManager] Login failed:",t.errors),{success:!1,error:this.formatError(t.errors),rawResponse:t};let r=f.getTokens();console.log("\u{1F50D} [SessionManager] Login - existingTokens:",r),console.log("\u{1F50D} [SessionManager] Login - this.config.apiEndpointAdmin:",this.config.apiEndpointAdmin),console.log("\u{1F50D} [SessionManager] Login - this.config.apiKeyEndpointAdmin:",this.config.apiKeyEndpointAdmin);let u={accessToken:t.data.token,refreshToken:t.data.refreshToken,expiresAt:t.data.expiresAt,refreshExpiresAt:t.data.refreshExpiresAt,apiEndpointAdmin:r?.apiEndpointAdmin||this.config.apiEndpointAdmin,apiKeyEndpointAdmin:r?.apiKeyEndpointAdmin||this.config.apiKeyEndpointAdmin};console.log("\u{1F50D} [SessionManager] Login - tokens to save:",u),f.saveTokens(u);let p=f.getTokens();return console.log("\u{1F50D} [SessionManager] After login save, TokenStorage has:",{apiEndpointAdmin:p?.apiEndpointAdmin,apiKeyEndpointAdmin:p?.apiKeyEndpointAdmin}),this.lastActivityTime=Date.now(),console.log("\u2705 [SessionManager] Login successful, tokens saved"),this.config.onLoginSuccess?.(u),{success:!0,tokens:u,data:t.data}}catch(t){return console.error("\u274C [SessionManager] Login error:",t),{success:!1,error:t instanceof Error?t.message:"Unknown error"}}}async logout(){try{this.log("Logging out..."),await v.logout(),f.clearTokens(),this.log("Logout successful"),this.config.onLogout?.()}catch(i){this.log("Logout error:",i),f.clearTokens()}}async restoreSession(){try{this.log("Attempting to restore session...");let i=f.getTokens();if(!i)return this.log("No valid tokens found in storage"),!1;if(Date.now()>=i.refreshExpiresAt)return this.log("Refresh token expired, clearing storage"),f.clearTokens(),!1;if(v.setTokens({accessToken:i.accessToken,refreshToken:i.refreshToken,expiresAt:i.expiresAt,refreshExpiresAt:i.refreshExpiresAt}),v.getTokenData().isValid===!1){if(this.log("Restored access token is invalid or expired"),Date.now()<i.refreshExpiresAt&&(this.log("Access token expired but refresh is valid, attempting refresh..."),await this.refreshTokens())){this.log("Session restored successfully via token refresh");let r=f.getTokens();return r&&this.config.onSessionRestored?.(r),!0}return f.clearTokens(),await v.logout(),!1}return this.log("Session restored successfully"),this.lastActivityTime=Date.now(),this.config.onSessionRestored?.(i),!0}catch(i){return this.log("Session restore error:",i),f.clearTokens(),await v.logout(),!1}}isAuthenticated(){return v.isLogin()||f.hasValidTokens()}getTokenInfo(){let i=v.getTokenData(),e=f.getExpirationInfo(),t=f.getTokens();return{isLoggedIn:this.isAuthenticated(),crudifyTokens:i,storageInfo:e,hasValidTokens:f.hasValidTokens(),apiEndpointAdmin:t?.apiEndpointAdmin,apiKeyEndpointAdmin:t?.apiKeyEndpointAdmin}}async refreshTokens(){if(this.isRefreshingLocally&&this.refreshPromise)return this.log("Refresh already in progress, waiting for existing promise..."),this.refreshPromise;this.isRefreshingLocally=!0,this.refreshPromise=this._performRefresh();try{return await this.refreshPromise}finally{this.isRefreshingLocally=!1,this.refreshPromise=null}}async _performRefresh(){try{this.log("Starting token refresh...");let i=await v.refreshAccessToken();if(!i.success)return this.log("Token refresh failed:",i.errors),f.clearTokens(),this.config.showNotification?.(this.getSessionExpiredMessage(),"warning"),this.config.onSessionExpired?.(),!1;let e={accessToken:i.data.token,refreshToken:i.data.refreshToken,expiresAt:i.data.expiresAt,refreshExpiresAt:i.data.refreshExpiresAt};return f.saveTokens(e),this.log("Tokens refreshed and saved successfully"),this.lastActivityTime=Date.now(),!0}catch(i){return this.log("Token refresh error:",i),f.clearTokens(),this.config.showNotification?.(this.getSessionExpiredMessage(),"warning"),this.config.onSessionExpired?.(),!1}}isRefreshing(){return this.isRefreshingLocally}setupResponseInterceptor(){v.setResponseInterceptor(async i=>{this.updateLastActivity();let e=this.detectAuthorizationError(i);if(e.isAuthError){if(this.log("\u{1F6A8} Authorization error detected:",{errorType:e.errorType,shouldLogout:e.shouldTriggerLogout}),e.isRefreshTokenInvalid||e.isTokenRefreshFailed)return this.log("Refresh token invalid, emitting TOKEN_REFRESH_FAILED event"),k.emit("TOKEN_REFRESH_FAILED",{message:e.userFriendlyMessage,error:e.errorDetails,source:"SessionManager.setupResponseInterceptor"}),i;e.shouldTriggerLogout&&(f.hasValidTokens()&&!e.isIrrecoverable?(this.log("Access token expired, emitting TOKEN_EXPIRED event"),k.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"),k.emit("SESSION_EXPIRED",{message:e.userFriendlyMessage,error:e.errorDetails,source:"SessionManager.setupResponseInterceptor"})))}return i}),this.log("Response interceptor configured (non-blocking mode)")}detectAuthorizationError(i){let e={isAuthError:!1,isRefreshTokenInvalid:!1,isTokenRefreshFailed:!1,isTokenExpired:!1,isUnauthorized:!1,isIrrecoverable:!1,shouldTriggerLogout:!1,errorType:"",errorDetails:null,userFriendlyMessage:""};if(i.errors&&Array.isArray(i.errors)){let t=i.errors.find(r=>r.errorType==="Unauthorized"||r.message?.includes("Unauthorized")||r.message?.includes("Not Authorized")||r.message?.includes("NOT_AUTHORIZED")||r.message?.includes("Token")||r.message?.includes("TOKEN")||r.message?.includes("Authentication")||r.message?.includes("UNAUTHENTICATED")||r.extensions?.code==="UNAUTHENTICATED"||r.extensions?.code==="FORBIDDEN");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&&i.errors&&typeof i.errors=="object"&&!Array.isArray(i.errors)){let r=Object.values(i.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")));r&&typeof r=="string"&&(e.isAuthError=!0,e.errorType="GraphQL Object",e.errorDetails=i.errors,e.shouldTriggerLogout=!0,r.includes("TOKEN_REFRESH_FAILED")?(e.isTokenRefreshFailed=!0,e.isRefreshTokenInvalid=!0,e.isIrrecoverable=!0,e.userFriendlyMessage="Tu sesi\xF3n ha caducado. Por favor, inicia sesi\xF3n nuevamente."):r.includes("TOKEN_HAS_EXPIRED")||r.includes("SESSION_EXPIRED")?(e.isTokenExpired=!0,e.userFriendlyMessage="Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente."):r.includes("INVALID_TOKEN")?(e.isTokenExpired=!0,e.isIrrecoverable=!0,e.userFriendlyMessage="Token inv\xE1lido. Por favor, inicia sesi\xF3n nuevamente."):e.userFriendlyMessage="Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente.")}if(!e.isAuthError&&i.data?.response?.status){let t=i.data.response.status.toUpperCase();(t==="UNAUTHORIZED"||t==="UNAUTHENTICATED")&&(e.isAuthError=!0,e.errorType="Status",e.errorDetails=i.data.response,e.isUnauthorized=!0,e.shouldTriggerLogout=!0,e.isIrrecoverable=!0,e.userFriendlyMessage="Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente.")}if(!e.isAuthError&&i.data?.response?.data)try{let t=typeof i.data.response.data=="string"?JSON.parse(i.data.response.data):i.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&&i.errorCode){let t=i.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 i=this.getTimeSinceLastActivity(),e=v.getTokenData();if(this.lastActivityTime===0)return"none";let t=900*1e3,r=300*1e3,u=300*1e3;return i>t?(this.log(`Inactivity timeout: ${Math.floor(i/6e4)} minutes since last activity`),"logout"):i<r&&e.expiresIn<u&&e.expiresIn>0?(this.log(`User active recently (${Math.floor(i/6e4)}min ago) and token expiring soon, should refresh`),"refresh"):"none"}clearSession(){f.clearTokens(),v.logout(),this.lastActivityTime=0,this.log("Session cleared completely")}getSessionExpiredMessage(){return this.config.translateFn?Y("SESSION_EXPIRED",{translateFn:this.config.translateFn,enableDebug:this.config.enableLogging}):"Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente."}log(i,...e){this.config.enableLogging&&console.log(`[SessionManager] ${i}`,...e)}formatError(i){return i?typeof i=="string"?i:typeof i=="object"?Object.values(i).flat().join(", "):"Authentication failed":"Unknown error"}};import{useState as fe,useEffect as F,useCallback as C}from"react";function Q(n={}){let[i,e]=fe({isAuthenticated:!1,isLoading:!0,isInitialized:!1,tokens:null,error:null}),t=z.getInstance(),r=C(async()=>{console.log("\u{1F535} [useSession] initialize() CALLED"),console.log("\u{1F50D} [useSession] options received:",{autoRestore:n.autoRestore,enableLogging:n.enableLogging,apiEndpointAdmin:n.apiEndpointAdmin,apiKeyEndpointAdmin:n.apiKeyEndpointAdmin});try{e(a=>({...a,isLoading:!0,error:null}));let c={autoRestore:n.autoRestore??!0,enableLogging:n.enableLogging??!1,showNotification:n.showNotification,translateFn:n.translateFn,apiEndpointAdmin:n.apiEndpointAdmin,apiKeyEndpointAdmin:n.apiKeyEndpointAdmin,onSessionExpired:()=>{e(a=>({...a,isAuthenticated:!1,tokens:null,error:"Session expired"})),n.onSessionExpired?.()},onSessionRestored:a=>{e(d=>({...d,isAuthenticated:!0,tokens:a,error:null})),n.onSessionRestored?.(a)},onLoginSuccess:a=>{e(d=>({...d,isAuthenticated:!0,tokens:a,error:null}))},onLogout:()=>{e(a=>({...a,isAuthenticated:!1,tokens:null,error:null}))}};console.log("\u{1F50D} [useSession] Calling sessionManager.initialize() with config:",c),await t.initialize(c),console.log("\u2705 [useSession] sessionManager.initialize() completed"),t.setupResponseInterceptor();let s=t.isAuthenticated(),o=t.getTokenInfo();console.log("\u{1F50D} [useSession] After initialize, isAuth:",s),console.log("\u{1F50D} [useSession] After initialize, tokenInfo:",o),e(a=>({...a,isAuthenticated:s,isInitialized:!0,isLoading:!1,tokens:o.crudifyTokens.accessToken?{accessToken:o.crudifyTokens.accessToken,refreshToken:o.crudifyTokens.refreshToken,expiresAt:o.crudifyTokens.expiresAt,refreshExpiresAt:o.crudifyTokens.refreshExpiresAt}:null}))}catch(c){let s=c instanceof Error?c.message:"Initialization failed";e(o=>({...o,isLoading:!1,isInitialized:!0,error:s}))}},[n.autoRestore,n.enableLogging,n.onSessionExpired,n.onSessionRestored]),u=C(async(c,s)=>{e(o=>({...o,isLoading:!0,error:null}));try{let o=await t.login(c,s);return o.success&&o.tokens?e(a=>({...a,isAuthenticated:!0,tokens:o.tokens,isLoading:!1,error:null})):e(a=>({...a,isAuthenticated:!1,tokens:null,isLoading:!1,error:null})),o}catch(o){let a=o instanceof Error?o.message:"Login failed",d=a.includes("INVALID_CREDENTIALS")||a.includes("Invalid email")||a.includes("Invalid password")||a.includes("credentials");return e(A=>({...A,isAuthenticated:!1,tokens:null,isLoading:!1,error:d?null:a})),{success:!1,error:a}}},[t]),p=C(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=C(async()=>{try{let c=await t.refreshTokens();if(c){let s=t.getTokenInfo();e(o=>({...o,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]),m=C(()=>{e(c=>({...c,error:null}))},[]),T=C(()=>t.getTokenInfo(),[t]);F(()=>{r()},[r]),F(()=>{if(!i.isAuthenticated||!i.tokens)return;let c=B.getInstance(),s=()=>{t.updateLastActivity(),n.enableLogging&&console.log("\u{1F4CD} User navigating - activity updated")},o=c.subscribe(s);window.addEventListener("popstate",s);let a=setInterval(async()=>{if(t.isRefreshing()){n.enableLogging&&console.log("\u23F8\uFE0F Refresh already in progress, skipping inactivity check");return}let d=t.checkInactivity();if(d==="logout")n.enableLogging&&console.log("\u23F1\uFE0F Inactivity timeout - logging out user"),await p();else if(d==="refresh")if(n.enableLogging&&console.log("\u{1F504} User active, token expiring soon - refreshing..."),e(y=>({...y,isLoading:!0})),await t.refreshTokens()){let y=t.getTokenInfo();e(I=>({...I,isLoading:!1,tokens:y.crudifyTokens.accessToken?{accessToken:y.crudifyTokens.accessToken,refreshToken:y.crudifyTokens.refreshToken,expiresAt:y.crudifyTokens.expiresAt,refreshExpiresAt:y.crudifyTokens.refreshExpiresAt}:null}))}else e(y=>({...y,isLoading:!1,isAuthenticated:!1,tokens:null}))},120*1e3);return()=>{clearInterval(a),window.removeEventListener("popstate",s),o()}},[i.isAuthenticated,i.tokens,t,n.enableLogging,p]),F(()=>{let c=k.subscribe(async s=>{if(n.enableLogging&&console.log(`\u{1F4E2} useSession: Received auth event: ${s.type}`),s.type==="TOKEN_EXPIRED"){if(t.isRefreshing()){n.enableLogging&&console.log("\u23F8\uFE0F Refresh already in progress, skipping TOKEN_EXPIRED handler");return}n.enableLogging&&console.log("\u{1F504} Token expired, attempting refresh..."),e(o=>({...o,isLoading:!0}));try{if(await t.refreshTokens()){n.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 n.enableLogging&&console.log("\u274C Token refresh failed, session expired"),k.emit("SESSION_EXPIRED",{message:"Failed to refresh token after detecting expiration",source:"useSession.TOKEN_EXPIRED handler"})}catch(o){n.enableLogging&&console.error("\u274C Error during token refresh:",o),k.emit("SESSION_EXPIRED",{message:o instanceof Error?o.message:"Unknown error during refresh",source:"useSession.TOKEN_EXPIRED handler (error)"})}}(s.type==="SESSION_EXPIRED"||s.type==="TOKEN_REFRESH_FAILED")&&(n.enableLogging&&console.log(`\u{1F534} Session expired (${s.type}), logging out...`),e(o=>({...o,isAuthenticated:!1,tokens:null,isLoading:!1,error:s.details?.message||"Session expired"})),n.onSessionExpired?.())});return()=>c()},[n.enableLogging,n.onSessionExpired,t]),F(()=>{let c=f.subscribeToChanges(s=>{s?(n.enableLogging&&console.log("\u{1F504} Tokens updated in another tab"),e(o=>({...o,tokens:s,isAuthenticated:!0}))):(n.enableLogging&&console.log("\u{1F504} Logout detected in another tab"),e(o=>({...o,isAuthenticated:!1,tokens:null})),k.emit("SESSION_EXPIRED",{message:"Sesi\xF3n cerrada en otra pesta\xF1a",source:"CrossTabSync"}))});return()=>c()},[n.enableLogging]);let S=C(()=>{t.updateLastActivity()},[t]);return{...i,login:u,logout:p,refreshTokens:h,clearError:m,getTokenInfo:T,updateActivity:S,isExpiringSoon:i.tokens?i.tokens.expiresAt-Date.now()<300*1e3:!1,expiresIn:i.tokens?Math.max(0,i.tokens.expiresAt-Date.now()):0,refreshExpiresIn:i.tokens?Math.max(0,i.tokens.refreshExpiresAt-Date.now()):0}}import{useState as ee,createContext as ge,useContext as pe,useCallback as H,useEffect as ye}from"react";import{Snackbar as he,Alert as Ee,Box as me,Portal as Te}from"@mui/material";import{v4 as ve}from"uuid";import Ae from"dompurify";import{jsx as R,jsxs as Se}from"react/jsx-runtime";var ie=ge(null),ke=n=>Ae.sanitize(n,{ALLOWED_TAGS:["b","i","em","strong","br","span"],ALLOWED_ATTR:["class"],FORBID_TAGS:["script","iframe","object","embed"],FORBID_ATTR:["onload","onerror","onclick","onmouseover","onfocus","onblur"],WHOLE_DOCUMENT:!1,RETURN_DOM:!1,RETURN_DOM_FRAGMENT:!1,RETURN_TRUSTED_TYPE:!1}),X=({children:n,maxNotifications:i=5,defaultAutoHideDuration:e=6e3,position:t={vertical:"top",horizontal:"right"},enabled:r=!1,allowHtml:u=!1})=>{let[p,h]=ee([]),m=H((s,o="info",a)=>{if(!r)return"";if(!s||typeof s!="string")return console.warn("\u26A0\uFE0F GlobalNotificationProvider: Invalid message provided"),"";s.length>1e3&&(console.warn("\u26A0\uFE0F GlobalNotificationProvider: Message too long, truncating"),s=s.substring(0,1e3)+"...");let d=ve(),A={id:d,message:s,severity:o,autoHideDuration:a?.autoHideDuration??e,persistent:a?.persistent??!1,allowHtml:a?.allowHtml??u};return h(y=>[...y.length>=i?y.slice(-(i-1)):y,A]),d},[i,e,r,u]),T=H(s=>{h(o=>o.filter(a=>a.id!==s))},[]),S=H(()=>{h([])},[]),c={showNotification:m,hideNotification:T,clearAllNotifications:S};return Se(ie.Provider,{value:c,children:[n,r&&R(Te,{children:R(me,{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:p.map(s=>R(be,{notification:s,onClose:()=>T(s.id)},s.id))})})]})},be=({notification:n,onClose:i})=>{let[e,t]=ee(!0),r=H((u,p)=>{p!=="clickaway"&&(t(!1),setTimeout(i,300))},[i]);return ye(()=>{if(!n.persistent&&n.autoHideDuration){let u=setTimeout(()=>{r()},n.autoHideDuration);return()=>clearTimeout(u)}},[n.autoHideDuration,n.persistent,r]),R(he,{open:e,onClose:r,sx:{position:"relative","& .MuiSnackbarContent-root":{minWidth:"auto"}},TransitionProps:{enter:!0,exit:!0},children:R(Ee,{variant:"filled",severity:n.severity,onClose:r,sx:{width:"100%",minWidth:"280px",maxWidth:"400px",wordBreak:"break-word"},children:n.allowHtml?R("span",{dangerouslySetInnerHTML:{__html:ke(n.message)}}):R("span",{children:n.message})})})},ne=()=>{let n=pe(ie);if(!n)throw new Error("useGlobalNotification debe ser usado dentro de un GlobalNotificationProvider");return n};import xe,{createContext as Ie,useContext as Ne,useMemo as te}from"react";import{Fragment as Re,jsx as E,jsxs as b}from"react/jsx-runtime";var re=Ie(void 0);function oe({children:n,options:i={},config:e,showNotifications:t=!1,notificationOptions:r={}}){let u;try{let{showNotification:o}=ne();u=o}catch{}let p={};try{console.log("\u{1F535} [SessionProvider/Inner] Attempting to get Crudify context...");let o=q();console.log("\u2705 [SessionProvider/Inner] Crudify context obtained:",{isInitialized:o.isInitialized,isLoading:o.isLoading,hasAdminCredentials:!!o.adminCredentials}),o.isInitialized&&o.adminCredentials?(p=o.adminCredentials,console.log("\u2705 [SessionProvider/Inner] Admin credentials obtained:",p)):o.isLoading?console.log("\u23F3 [SessionProvider/Inner] CrudifyProvider still loading, credentials will be available soon"):console.warn("\u26A0\uFE0F [SessionProvider/Inner] CrudifyProvider initialized but has no adminCredentials")}catch(o){console.warn("\u26A0\uFE0F [SessionProvider/Inner] Could not get Crudify context - this is OK if using external CrudifyProvider:",o)}let h=xe.useMemo(()=>{console.log("\u{1F50D} [SessionProvider] Creating enhancedOptions with adminCredentials:",p);let o={...i,showNotification:u,apiEndpointAdmin:p.apiEndpointAdmin,apiKeyEndpointAdmin:p.apiKeyEndpointAdmin,onSessionExpired:()=>{i.onSessionExpired?.()}};return console.log("\u2705 [SessionProvider] enhancedOptions created:",o),o},[i,u,p.apiEndpointAdmin,p.apiKeyEndpointAdmin]),m=Q(h),T=te(()=>{let o,a,d,A,y,I="unknown";if(e?.publicApiKey&&(o=e.publicApiKey,I="props"),e?.env&&(a=e.env),e?.appName&&(d=e.appName),e?.loginActions&&(A=e.loginActions),e?.logo&&(y=e.logo),!o){let P=L("publicApiKey"),N=L("environment"),x=L("appName"),g=L("loginActions"),D=L("logo");P&&(o=P,I="cookies"),N&&["dev","stg","prod"].includes(N)&&(a=N),x&&(d=decodeURIComponent(x)),g&&(A=decodeURIComponent(g).split(",").map(M=>M.trim()).filter(Boolean)),D&&(y=decodeURIComponent(D))}return{publicApiKey:o,env:a,appName:d,loginActions:A,logo:y}},[e]),S=te(()=>{if(!m.tokens?.accessToken||!m.isAuthenticated)return null;try{let o=$(m.tokens.accessToken);if(o&&o.sub&&o.email&&o.subscriber){let a={_id:o.sub,email:o.email,subscriberKey:o.subscriber};return Object.keys(o).forEach(d=>{["sub","email","subscriber"].includes(d)||(a[d]=o[d])}),a}}catch(o){console.error("Error decoding JWT token for sessionData:",o)}return null},[m.tokens?.accessToken,m.isAuthenticated]),c={...m,sessionData:S,config:T},s={enabled:t,maxNotifications:r.maxNotifications||5,defaultAutoHideDuration:r.defaultAutoHideDuration||6e3,position:r.position||{vertical:"top",horizontal:"right"}};return E(re.Provider,{value:c,children:n})}function mi(n){let i={enabled:n.showNotifications,maxNotifications:n.notificationOptions?.maxNotifications||5,defaultAutoHideDuration:n.notificationOptions?.defaultAutoHideDuration||6e3,position:n.notificationOptions?.position||{vertical:"top",horizontal:"right"},allowHtml:n.notificationOptions?.allowHtml||!1};return n.config?.publicApiKey?(console.log("\u2705 [SessionProvider] Auto-creating internal CrudifyProvider with config:",n.config),E(Z,{config:{publicApiKey:n.config.publicApiKey,env:n.config.env||"prod",appName:n.config.appName,loginActions:n.config.loginActions,logo:n.config.logo},children:E(X,{...i,children:E(oe,{...n})})})):(console.log("\u2705 [SessionProvider] Using external CrudifyProvider"),E(X,{...i,children:E(oe,{...n})}))}function Ce(){let n=Ne(re);if(n===void 0)throw new Error("useSessionContext must be used within a SessionProvider");return n}function Ti(){let n=Ce();return n.isInitialized?b("div",{style:{padding:"10px",margin:"10px",border:"1px solid #ccc",borderRadius:"4px",fontSize:"12px",fontFamily:"monospace"},children:[E("h4",{children:"Session Debug Info"}),b("div",{children:[E("strong",{children:"Authenticated:"})," ",n.isAuthenticated?"Yes":"No"]}),b("div",{children:[E("strong",{children:"Loading:"})," ",n.isLoading?"Yes":"No"]}),b("div",{children:[E("strong",{children:"Error:"})," ",n.error||"None"]}),n.tokens&&b(Re,{children:[b("div",{children:[E("strong",{children:"Access Token:"})," ",n.tokens.accessToken.substring(0,20),"..."]}),b("div",{children:[E("strong",{children:"Refresh Token:"})," ",n.tokens.refreshToken.substring(0,20),"..."]}),b("div",{children:[E("strong",{children:"Access Expires In:"})," ",Math.round(n.expiresIn/1e3/60)," minutes"]}),b("div",{children:[E("strong",{children:"Refresh Expires In:"})," ",Math.round(n.refreshExpiresIn/1e3/60/60)," hours"]}),b("div",{children:[E("strong",{children:"Expiring Soon:"})," ",n.isExpiringSoon?"Yes":"No"]})]})]}):E("div",{children:"Session not initialized"})}import{useState as _,useEffect as se,useCallback as ae,useRef as G}from"react";import Pe from"@nocios/crudify-browser";var xi=(n={})=>{let{autoFetch:i=!0,retryOnError:e=!1,maxRetries:t=3}=n,[r,u]=_(null),[p,h]=_(!1),[m,T]=_(null),[S,c]=_({}),s=G(null),o=G(!0),a=G(0),d=G(0),A=ae(()=>{u(null),T(null),h(!1),c({})},[]),y=ae(async()=>{let I=W();if(!I){o.current&&(T("No user email available"),h(!1));return}s.current&&s.current.abort();let P=new AbortController;s.current=P;let N=++a.current;try{o.current&&(h(!0),T(null));let x=await Pe.readItems("users",{filter:{email:I},pagination:{limit:1}});if(N===a.current&&o.current&&!P.signal.aborted)if(x.success&&x.data&&x.data.length>0){let g=x.data[0];u(g);let D={fullProfile:g,totalFields:Object.keys(g).length,displayData:{id:g.id,email:g.email,username:g.username,firstName:g.firstName,lastName:g.lastName,fullName:g.fullName||`${g.firstName||""} ${g.lastName||""}`.trim(),role:g.role,permissions:g.permissions||[],isActive:g.isActive,lastLogin:g.lastLogin,createdAt:g.createdAt,updatedAt:g.updatedAt,...Object.keys(g).filter(O=>!["id","email","username","firstName","lastName","fullName","role","permissions","isActive","lastLogin","createdAt","updatedAt"].includes(O)).reduce((O,M)=>({...O,[M]:g[M]}),{})}};c(D),T(null),d.current=0}else T("User profile not found"),u(null),c({})}catch(x){if(N===a.current&&o.current){let g=x;if(g.name==="AbortError")return;e&&d.current<t&&(g.message?.includes("Network Error")||g.message?.includes("Failed to fetch"))?(d.current++,setTimeout(()=>{o.current&&y()},1e3*d.current)):(T("Failed to load user profile"),u(null),c({}))}}finally{N===a.current&&o.current&&h(!1),s.current===P&&(s.current=null)}},[e,t]);return se(()=>{i&&y()},[i,y]),se(()=>(o.current=!0,()=>{o.current=!1,s.current&&(s.current.abort(),s.current=null)}),[]),{userProfile:r,loading:p,error:m,extendedData:S,refreshProfile:y,clearProfile:A}};export{j as a,Z as b,q as c,f as d,z as e,Q as f,X as g,ne as h,mi as i,Ce as j,Ti as k,xi as l};
|
|
@@ -0,0 +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 _react = require('react'); var _react2 = _interopRequireDefault(_react);var _crudifybrowser = require('@nocios/crudify-browser'); var _crudifybrowser2 = _interopRequireDefault(_crudifybrowser);var V=class n{constructor(){this.listeners=[];this.credentials=null;this.isReady=!1}static getInstance(){return n.instance||(n.instance=new n),n.instance}notifyCredentialsReady(i){this.credentials=i,this.isReady=!0,console.log("\u2705 [CredentialsEventBus] Credentials ready, notifying",this.listeners.length,"listeners"),this.listeners.forEach(e=>{try{e(i)}catch(t){console.error("\u274C [CredentialsEventBus] Error in listener:",t)}}),this.listeners=[]}waitForCredentials(){return this.isReady&&this.credentials?(console.log("\u2705 [CredentialsEventBus] Credentials already available"),Promise.resolve(this.credentials)):(console.log("\u23F3 [CredentialsEventBus] Waiting for credentials..."),new Promise(i=>{this.listeners.push(i)}))}reset(){this.credentials=null,this.isReady=!1,this.listeners=[],console.log("\u{1F504} [CredentialsEventBus] Reset")}areCredentialsReady(){return this.isReady&&this.credentials!==null}},j= exports.a =V.getInstance();var _jsxruntime = require('react/jsx-runtime');var J=_react.createContext.call(void 0, void 0),Z= exports.b =({config:n,children:i})=>{let[e,t]=_react.useState.call(void 0, !0),[r,u]=_react.useState.call(void 0, null),[p,h]=_react.useState.call(void 0, !1),[m,T]=_react.useState.call(void 0, ""),[S,c]=_react.useState.call(void 0, );console.log("\u{1F50D} CrudifyProvider - Received config:",n),_react.useEffect.call(void 0, ()=>{if(console.log("\u{1F50D} CrudifyProvider - useEffect - config.publicApiKey:",n.publicApiKey),console.log("\u{1F50D} CrudifyProvider - useEffect - full config:",n),!n.publicApiKey){console.log("\u274C CrudifyProvider - No publicApiKey provided, setting error"),u("No publicApiKey provided"),t(!1),h(!1);return}console.log("\u2705 CrudifyProvider - publicApiKey found, proceeding with initialization");let o=`${n.publicApiKey}-${n.env}`;if(o===m&&p){t(!1);return}(async()=>{console.log("\u{1F535} [CrudifyProvider] initializeCrudify() CALLED"),t(!0),u(null),h(!1);try{console.log("\u{1F50D} [CrudifyProvider] Calling crudify.config with env:",n.env||"prod"),_crudifybrowser2.default.config(n.env||"prod"),console.log("\u{1F50D} [CrudifyProvider] Calling crudify.init with publicApiKey:",n.publicApiKey);let d=await _crudifybrowser2.default.init(n.publicApiKey,"none");if(console.log("\u2705 [CrudifyProvider] crudify.init() completed, result:",d),c(d),console.log("\u2705 [CrudifyProvider] Admin credentials stored in state:",d),typeof _crudifybrowser2.default.transaction=="function"&&typeof _crudifybrowser2.default.login=="function")h(!0),T(o),console.log("\u2705 [CrudifyProvider] Crudify initialized successfully"),d.apiEndpointAdmin&&d.apiKeyEndpointAdmin&&j.notifyCredentialsReady({apiUrl:d.apiEndpointAdmin,apiKey:d.apiKeyEndpointAdmin});else throw new Error("Crudify methods not properly initialized")}catch(d){let A=d instanceof Error?d.message:"Failed to initialize Crudify";console.error("\u274C [CrudifyProvider] Initialization error:",d),u(A),h(!1)}finally{t(!1)}})()},[n.publicApiKey,n.env,m,p]);let s={crudify:p?_crudifybrowser2.default:null,isLoading:e,error:r,isInitialized:p,adminCredentials:S};return _jsxruntime.jsx.call(void 0, J.Provider,{value:s,children:i})},q= exports.c =()=>{let n=_react.useContext.call(void 0, J);if(n===void 0)throw new Error("useCrudify must be used within a CrudifyProvider");return n};var _cryptojs = require('crypto-js'); var _cryptojs2 = _interopRequireDefault(_cryptojs);var l=class l{static setStorageType(i){l.storageType=i}static generateEncryptionKey(){let i=[navigator.userAgent,navigator.language,navigator.platform,screen.width,screen.height,Date.now().toString(),Math.random().toString(36)].join("|");return _cryptojs2.default.SHA256(i).toString()}static getEncryptionKey(){if(l.encryptionKey)return l.encryptionKey;let i=window.localStorage;if(!i)return l.encryptionKey=l.generateEncryptionKey(),l.encryptionKey;try{let e=i.getItem(l.ENCRYPTION_KEY_STORAGE);return(!e||e.length<32)&&(e=l.generateEncryptionKey(),i.setItem(l.ENCRYPTION_KEY_STORAGE,e)),l.encryptionKey=e,e}catch (e2){return console.warn("Crudify: Cannot persist encryption key, using temporary key"),l.encryptionKey=l.generateEncryptionKey(),l.encryptionKey}}static isStorageAvailable(i){try{let e=window[i],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(i){try{let e=l.getEncryptionKey();return _cryptojs2.default.AES.encrypt(i,e).toString()}catch(e){return console.error("Crudify: Encryption failed",e),i}}static decrypt(i){try{let e=l.getEncryptionKey();return _cryptojs2.default.AES.decrypt(i,e).toString(_cryptojs2.default.enc.Utf8)||i}catch(e){return console.error("Crudify: Decryption failed",e),i}}static saveTokens(i){let e=l.getStorage();if(e)try{let t={accessToken:i.accessToken,refreshToken:i.refreshToken,expiresAt:i.expiresAt,refreshExpiresAt:i.refreshExpiresAt,savedAt:Date.now()},r=l.encrypt(JSON.stringify(t));e.setItem(l.TOKEN_KEY,r),console.debug("Crudify: Tokens saved successfully")}catch(t){console.error("Crudify: Failed to save tokens",t)}}static getTokens(){let i=l.getStorage();if(!i)return null;try{let e=i.getItem(l.TOKEN_KEY);if(!e)return null;let t=l.decrypt(e),r=JSON.parse(t);return!r.accessToken||!r.refreshToken||!r.expiresAt||!r.refreshExpiresAt?(console.warn("Crudify: Incomplete token data found, clearing storage"),l.clearTokens(),null):Date.now()>=r.refreshExpiresAt?(console.info("Crudify: Refresh token expired, clearing storage"),l.clearTokens(),null):{accessToken:r.accessToken,refreshToken:r.refreshToken,expiresAt:r.expiresAt,refreshExpiresAt:r.refreshExpiresAt}}catch(e){return console.error("Crudify: Failed to retrieve tokens",e),l.clearTokens(),null}}static clearTokens(){let i=l.getStorage();if(i)try{i.removeItem(l.TOKEN_KEY),console.debug("Crudify: Tokens cleared from storage")}catch(e){console.error("Crudify: Failed to clear tokens",e)}}static rotateEncryptionKey(){try{l.clearTokens(),l.encryptionKey=null;let i=window.localStorage;i&&i.removeItem(l.ENCRYPTION_KEY_STORAGE),console.info("Crudify: Encryption key rotated successfully")}catch(i){console.error("Crudify: Failed to rotate encryption key",i)}}static hasValidTokens(){return l.getTokens()!==null}static getExpirationInfo(){let i=l.getTokens();if(!i)return null;let e=Date.now();return{accessExpired:e>=i.expiresAt,refreshExpired:e>=i.refreshExpiresAt,accessExpiresIn:Math.max(0,i.expiresAt-e),refreshExpiresIn:Math.max(0,i.refreshExpiresAt-e)}}static updateAccessToken(i,e){let t=l.getTokens();if(!t){console.warn("Crudify: Cannot update access token, no existing tokens found");return}l.saveTokens({...t,accessToken:i,expiresAt:e})}static subscribeToChanges(i){let e=t=>{if(t.key===l.TOKEN_KEY){if(t.newValue===null){console.debug("Crudify: Tokens removed in another tab"),i(null);return}if(t.newValue){console.debug("Crudify: Tokens updated in another tab");let r=l.getTokens();i(r)}}};return window.addEventListener("storage",e),()=>{window.removeEventListener("storage",e)}}};l.TOKEN_KEY="crudify_tokens",l.ENCRYPTION_KEY_STORAGE="crudify_enc_key",l.encryptionKey=null,l.storageType="localStorage";var f=l;var z=class n{constructor(){this.config={};this.initialized=!1;this.lastActivityTime=0;this.isRefreshingLocally=!1;this.refreshPromise=null}static getInstance(){return n.instance||(n.instance=new n),n.instance}async initialize(i={}){if(console.log("\u{1F535} [SessionManager] initialize() CALLED"),console.log("\u{1F50D} [SessionManager] Received config:",i),this.initialized){console.warn("SessionManager: Already initialized");return}if(this.config={storageType:"localStorage",autoRestore:!0,enableLogging:!1,...i},f.setStorageType(this.config.storageType||"localStorage"),this.config.enableLogging,_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"})}),console.log("\u{1F50D} [SessionManager] config.apiEndpointAdmin:",this.config.apiEndpointAdmin),console.log("\u{1F50D} [SessionManager] config.apiKeyEndpointAdmin:",this.config.apiKeyEndpointAdmin),this.config.apiEndpointAdmin&&this.config.apiKeyEndpointAdmin){console.log("\u2705 [SessionManager] Admin credentials provided, storing...");let e=f.getTokens();e?(f.saveTokens({...e,apiEndpointAdmin:this.config.apiEndpointAdmin,apiKeyEndpointAdmin:this.config.apiKeyEndpointAdmin}),console.log("\u2705 [SessionManager] Admin API credentials stored from init (with existing tokens)")):(f.saveTokens({accessToken:"",refreshToken:"",expiresAt:0,refreshExpiresAt:0,apiEndpointAdmin:this.config.apiEndpointAdmin,apiKeyEndpointAdmin:this.config.apiKeyEndpointAdmin}),console.log("\u2705 [SessionManager] Admin API credentials stored (no tokens yet)"));let t=f.getTokens();console.log("\u{1F50D} [SessionManager] After saving, TokenStorage has:",{apiEndpointAdmin:_optionalChain([t, 'optionalAccess', _2 => _2.apiEndpointAdmin]),apiKeyEndpointAdmin:_optionalChain([t, 'optionalAccess', _3 => _3.apiKeyEndpointAdmin])})}else console.warn("\u26A0\uFE0F [SessionManager] Admin API credentials NOT provided to SessionManager.initialize()");this.config.autoRestore&&await this.restoreSession(),this.initialized=!0,console.log("\u2705 [SessionManager] Initialized successfully")}async login(i,e){try{console.log("\u{1F535} [SessionManager] login() CALLED");let t=await _crudifybrowser2.default.login(i,e);if(!t.success)return console.log("\u274C [SessionManager] Login failed:",t.errors),{success:!1,error:this.formatError(t.errors),rawResponse:t};let r=f.getTokens();console.log("\u{1F50D} [SessionManager] Login - existingTokens:",r),console.log("\u{1F50D} [SessionManager] Login - this.config.apiEndpointAdmin:",this.config.apiEndpointAdmin),console.log("\u{1F50D} [SessionManager] Login - this.config.apiKeyEndpointAdmin:",this.config.apiKeyEndpointAdmin);let u={accessToken:t.data.token,refreshToken:t.data.refreshToken,expiresAt:t.data.expiresAt,refreshExpiresAt:t.data.refreshExpiresAt,apiEndpointAdmin:_optionalChain([r, 'optionalAccess', _4 => _4.apiEndpointAdmin])||this.config.apiEndpointAdmin,apiKeyEndpointAdmin:_optionalChain([r, 'optionalAccess', _5 => _5.apiKeyEndpointAdmin])||this.config.apiKeyEndpointAdmin};console.log("\u{1F50D} [SessionManager] Login - tokens to save:",u),f.saveTokens(u);let p=f.getTokens();return console.log("\u{1F50D} [SessionManager] After login save, TokenStorage has:",{apiEndpointAdmin:_optionalChain([p, 'optionalAccess', _6 => _6.apiEndpointAdmin]),apiKeyEndpointAdmin:_optionalChain([p, 'optionalAccess', _7 => _7.apiKeyEndpointAdmin])}),this.lastActivityTime=Date.now(),console.log("\u2705 [SessionManager] Login successful, tokens saved"),_optionalChain([this, 'access', _8 => _8.config, 'access', _9 => _9.onLoginSuccess, 'optionalCall', _10 => _10(u)]),{success:!0,tokens:u,data:t.data}}catch(t){return console.error("\u274C [SessionManager] Login error:",t),{success:!1,error:t instanceof Error?t.message:"Unknown error"}}}async logout(){try{this.log("Logging out..."),await _crudifybrowser2.default.logout(),f.clearTokens(),this.log("Logout successful"),_optionalChain([this, 'access', _11 => _11.config, 'access', _12 => _12.onLogout, 'optionalCall', _13 => _13()])}catch(i){this.log("Logout error:",i),f.clearTokens()}}async restoreSession(){try{this.log("Attempting to restore session...");let i=f.getTokens();if(!i)return this.log("No valid tokens found in storage"),!1;if(Date.now()>=i.refreshExpiresAt)return this.log("Refresh token expired, clearing storage"),f.clearTokens(),!1;if(_crudifybrowser2.default.setTokens({accessToken:i.accessToken,refreshToken:i.refreshToken,expiresAt:i.expiresAt,refreshExpiresAt:i.refreshExpiresAt}),_crudifybrowser2.default.getTokenData().isValid===!1){if(this.log("Restored access token is invalid or expired"),Date.now()<i.refreshExpiresAt&&(this.log("Access token expired but refresh is valid, attempting refresh..."),await this.refreshTokens())){this.log("Session restored successfully via token refresh");let r=f.getTokens();return r&&_optionalChain([this, 'access', _14 => _14.config, 'access', _15 => _15.onSessionRestored, 'optionalCall', _16 => _16(r)]),!0}return f.clearTokens(),await _crudifybrowser2.default.logout(),!1}return this.log("Session restored successfully"),this.lastActivityTime=Date.now(),_optionalChain([this, 'access', _17 => _17.config, 'access', _18 => _18.onSessionRestored, 'optionalCall', _19 => _19(i)]),!0}catch(i){return this.log("Session restore error:",i),f.clearTokens(),await _crudifybrowser2.default.logout(),!1}}isAuthenticated(){return _crudifybrowser2.default.isLogin()||f.hasValidTokens()}getTokenInfo(){let i=_crudifybrowser2.default.getTokenData(),e=f.getExpirationInfo(),t=f.getTokens();return{isLoggedIn:this.isAuthenticated(),crudifyTokens:i,storageInfo:e,hasValidTokens:f.hasValidTokens(),apiEndpointAdmin:_optionalChain([t, 'optionalAccess', _20 => _20.apiEndpointAdmin]),apiKeyEndpointAdmin:_optionalChain([t, 'optionalAccess', _21 => _21.apiKeyEndpointAdmin])}}async refreshTokens(){if(this.isRefreshingLocally&&this.refreshPromise)return this.log("Refresh already in progress, waiting for existing promise..."),this.refreshPromise;this.isRefreshingLocally=!0,this.refreshPromise=this._performRefresh();try{return await this.refreshPromise}finally{this.isRefreshingLocally=!1,this.refreshPromise=null}}async _performRefresh(){try{this.log("Starting token refresh...");let i=await _crudifybrowser2.default.refreshAccessToken();if(!i.success)return this.log("Token refresh failed:",i.errors),f.clearTokens(),_optionalChain([this, 'access', _22 => _22.config, 'access', _23 => _23.showNotification, 'optionalCall', _24 => _24(this.getSessionExpiredMessage(),"warning")]),_optionalChain([this, 'access', _25 => _25.config, 'access', _26 => _26.onSessionExpired, 'optionalCall', _27 => _27()]),!1;let e={accessToken:i.data.token,refreshToken:i.data.refreshToken,expiresAt:i.data.expiresAt,refreshExpiresAt:i.data.refreshExpiresAt};return f.saveTokens(e),this.log("Tokens refreshed and saved successfully"),this.lastActivityTime=Date.now(),!0}catch(i){return this.log("Token refresh error:",i),f.clearTokens(),_optionalChain([this, 'access', _28 => _28.config, 'access', _29 => _29.showNotification, 'optionalCall', _30 => _30(this.getSessionExpiredMessage(),"warning")]),_optionalChain([this, 'access', _31 => _31.config, 'access', _32 => _32.onSessionExpired, 'optionalCall', _33 => _33()]),!1}}isRefreshing(){return this.isRefreshingLocally}setupResponseInterceptor(){_crudifybrowser2.default.setResponseInterceptor(async i=>{this.updateLastActivity();let e=this.detectAuthorizationError(i);if(e.isAuthError){if(this.log("\u{1F6A8} Authorization error detected:",{errorType:e.errorType,shouldLogout:e.shouldTriggerLogout}),e.isRefreshTokenInvalid||e.isTokenRefreshFailed)return this.log("Refresh token invalid, emitting TOKEN_REFRESH_FAILED event"),_chunkAT74WV5Wjs.f.emit("TOKEN_REFRESH_FAILED",{message:e.userFriendlyMessage,error:e.errorDetails,source:"SessionManager.setupResponseInterceptor"}),i;e.shouldTriggerLogout&&(f.hasValidTokens()&&!e.isIrrecoverable?(this.log("Access token expired, emitting TOKEN_EXPIRED event"),_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 i}),this.log("Response interceptor configured (non-blocking mode)")}detectAuthorizationError(i){let e={isAuthError:!1,isRefreshTokenInvalid:!1,isTokenRefreshFailed:!1,isTokenExpired:!1,isUnauthorized:!1,isIrrecoverable:!1,shouldTriggerLogout:!1,errorType:"",errorDetails:null,userFriendlyMessage:""};if(i.errors&&Array.isArray(i.errors)){let t=i.errors.find(r=>r.errorType==="Unauthorized"||_optionalChain([r, 'access', _34 => _34.message, 'optionalAccess', _35 => _35.includes, 'call', _36 => _36("Unauthorized")])||_optionalChain([r, 'access', _37 => _37.message, 'optionalAccess', _38 => _38.includes, 'call', _39 => _39("Not Authorized")])||_optionalChain([r, 'access', _40 => _40.message, 'optionalAccess', _41 => _41.includes, 'call', _42 => _42("NOT_AUTHORIZED")])||_optionalChain([r, 'access', _43 => _43.message, 'optionalAccess', _44 => _44.includes, 'call', _45 => _45("Token")])||_optionalChain([r, 'access', _46 => _46.message, 'optionalAccess', _47 => _47.includes, 'call', _48 => _48("TOKEN")])||_optionalChain([r, 'access', _49 => _49.message, 'optionalAccess', _50 => _50.includes, 'call', _51 => _51("Authentication")])||_optionalChain([r, 'access', _52 => _52.message, 'optionalAccess', _53 => _53.includes, 'call', _54 => _54("UNAUTHENTICATED")])||_optionalChain([r, 'access', _55 => _55.extensions, 'optionalAccess', _56 => _56.code])==="UNAUTHENTICATED"||_optionalChain([r, 'access', _57 => _57.extensions, 'optionalAccess', _58 => _58.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', _59 => _59.message, 'optionalAccess', _60 => _60.includes, 'call', _61 => _61("TOKEN")])||_optionalChain([t, 'access', _62 => _62.message, 'optionalAccess', _63 => _63.includes, 'call', _64 => _64("Token")]))&&(e.isTokenExpired=!0),_optionalChain([t, 'access', _65 => _65.extensions, 'optionalAccess', _66 => _66.code])==="UNAUTHENTICATED"&&(e.isUnauthorized=!0))}if(!e.isAuthError&&i.errors&&typeof i.errors=="object"&&!Array.isArray(i.errors)){let r=Object.values(i.errors).flat().find(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")));r&&typeof r=="string"&&(e.isAuthError=!0,e.errorType="GraphQL Object",e.errorDetails=i.errors,e.shouldTriggerLogout=!0,r.includes("TOKEN_REFRESH_FAILED")?(e.isTokenRefreshFailed=!0,e.isRefreshTokenInvalid=!0,e.isIrrecoverable=!0,e.userFriendlyMessage="Tu sesi\xF3n ha caducado. Por favor, inicia sesi\xF3n nuevamente."):r.includes("TOKEN_HAS_EXPIRED")||r.includes("SESSION_EXPIRED")?(e.isTokenExpired=!0,e.userFriendlyMessage="Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente."):r.includes("INVALID_TOKEN")?(e.isTokenExpired=!0,e.isIrrecoverable=!0,e.userFriendlyMessage="Token inv\xE1lido. Por favor, inicia sesi\xF3n nuevamente."):e.userFriendlyMessage="Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente.")}if(!e.isAuthError&&_optionalChain([i, 'access', _67 => _67.data, 'optionalAccess', _68 => _68.response, 'optionalAccess', _69 => _69.status])){let t=i.data.response.status.toUpperCase();(t==="UNAUTHORIZED"||t==="UNAUTHENTICATED")&&(e.isAuthError=!0,e.errorType="Status",e.errorDetails=i.data.response,e.isUnauthorized=!0,e.shouldTriggerLogout=!0,e.isIrrecoverable=!0,e.userFriendlyMessage="Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente.")}if(!e.isAuthError&&_optionalChain([i, 'access', _70 => _70.data, 'optionalAccess', _71 => _71.response, 'optionalAccess', _72 => _72.data]))try{let t=typeof i.data.response.data=="string"?JSON.parse(i.data.response.data):i.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&&i.errorCode){let t=i.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 i=this.getTimeSinceLastActivity(),e=_crudifybrowser2.default.getTokenData();if(this.lastActivityTime===0)return"none";let t=900*1e3,r=300*1e3,u=300*1e3;return i>t?(this.log(`Inactivity timeout: ${Math.floor(i/6e4)} minutes since last activity`),"logout"):i<r&&e.expiresIn<u&&e.expiresIn>0?(this.log(`User active recently (${Math.floor(i/6e4)}min ago) and token expiring soon, should refresh`),"refresh"):"none"}clearSession(){f.clearTokens(),_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(i,...e){this.config.enableLogging&&console.log(`[SessionManager] ${i}`,...e)}formatError(i){return i?typeof i=="string"?i:typeof i=="object"?Object.values(i).flat().join(", "):"Authentication failed":"Unknown error"}};function Q(n={}){let[i,e]=_react.useState.call(void 0, {isAuthenticated:!1,isLoading:!0,isInitialized:!1,tokens:null,error:null}),t=z.getInstance(),r=_react.useCallback.call(void 0, async()=>{console.log("\u{1F535} [useSession] initialize() CALLED"),console.log("\u{1F50D} [useSession] options received:",{autoRestore:n.autoRestore,enableLogging:n.enableLogging,apiEndpointAdmin:n.apiEndpointAdmin,apiKeyEndpointAdmin:n.apiKeyEndpointAdmin});try{e(a=>({...a,isLoading:!0,error:null}));let c={autoRestore:_nullishCoalesce(n.autoRestore, () => (!0)),enableLogging:_nullishCoalesce(n.enableLogging, () => (!1)),showNotification:n.showNotification,translateFn:n.translateFn,apiEndpointAdmin:n.apiEndpointAdmin,apiKeyEndpointAdmin:n.apiKeyEndpointAdmin,onSessionExpired:()=>{e(a=>({...a,isAuthenticated:!1,tokens:null,error:"Session expired"})),_optionalChain([n, 'access', _73 => _73.onSessionExpired, 'optionalCall', _74 => _74()])},onSessionRestored:a=>{e(d=>({...d,isAuthenticated:!0,tokens:a,error:null})),_optionalChain([n, 'access', _75 => _75.onSessionRestored, 'optionalCall', _76 => _76(a)])},onLoginSuccess:a=>{e(d=>({...d,isAuthenticated:!0,tokens:a,error:null}))},onLogout:()=>{e(a=>({...a,isAuthenticated:!1,tokens:null,error:null}))}};console.log("\u{1F50D} [useSession] Calling sessionManager.initialize() with config:",c),await t.initialize(c),console.log("\u2705 [useSession] sessionManager.initialize() completed"),t.setupResponseInterceptor();let s=t.isAuthenticated(),o=t.getTokenInfo();console.log("\u{1F50D} [useSession] After initialize, isAuth:",s),console.log("\u{1F50D} [useSession] After initialize, tokenInfo:",o),e(a=>({...a,isAuthenticated:s,isInitialized:!0,isLoading:!1,tokens:o.crudifyTokens.accessToken?{accessToken:o.crudifyTokens.accessToken,refreshToken:o.crudifyTokens.refreshToken,expiresAt:o.crudifyTokens.expiresAt,refreshExpiresAt:o.crudifyTokens.refreshExpiresAt}:null}))}catch(c){let s=c instanceof Error?c.message:"Initialization failed";e(o=>({...o,isLoading:!1,isInitialized:!0,error:s}))}},[n.autoRestore,n.enableLogging,n.onSessionExpired,n.onSessionRestored]),u=_react.useCallback.call(void 0, async(c,s)=>{e(o=>({...o,isLoading:!0,error:null}));try{let o=await t.login(c,s);return o.success&&o.tokens?e(a=>({...a,isAuthenticated:!0,tokens:o.tokens,isLoading:!1,error:null})):e(a=>({...a,isAuthenticated:!1,tokens:null,isLoading:!1,error:null})),o}catch(o){let a=o instanceof Error?o.message:"Login failed",d=a.includes("INVALID_CREDENTIALS")||a.includes("Invalid email")||a.includes("Invalid password")||a.includes("credentials");return e(A=>({...A,isAuthenticated:!1,tokens:null,isLoading:!1,error:d?null:a})),{success:!1,error:a}}},[t]),p=_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(o=>({...o,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]),m=_react.useCallback.call(void 0, ()=>{e(c=>({...c,error:null}))},[]),T=_react.useCallback.call(void 0, ()=>t.getTokenInfo(),[t]);_react.useEffect.call(void 0, ()=>{r()},[r]),_react.useEffect.call(void 0, ()=>{if(!i.isAuthenticated||!i.tokens)return;let c=_chunkAT74WV5Wjs.g.getInstance(),s=()=>{t.updateLastActivity(),n.enableLogging&&console.log("\u{1F4CD} User navigating - activity updated")},o=c.subscribe(s);window.addEventListener("popstate",s);let a=setInterval(async()=>{if(t.isRefreshing()){n.enableLogging&&console.log("\u23F8\uFE0F Refresh already in progress, skipping inactivity check");return}let d=t.checkInactivity();if(d==="logout")n.enableLogging&&console.log("\u23F1\uFE0F Inactivity timeout - logging out user"),await p();else if(d==="refresh")if(n.enableLogging&&console.log("\u{1F504} User active, token expiring soon - refreshing..."),e(y=>({...y,isLoading:!0})),await t.refreshTokens()){let y=t.getTokenInfo();e(I=>({...I,isLoading:!1,tokens:y.crudifyTokens.accessToken?{accessToken:y.crudifyTokens.accessToken,refreshToken:y.crudifyTokens.refreshToken,expiresAt:y.crudifyTokens.expiresAt,refreshExpiresAt:y.crudifyTokens.refreshExpiresAt}:null}))}else e(y=>({...y,isLoading:!1,isAuthenticated:!1,tokens:null}))},120*1e3);return()=>{clearInterval(a),window.removeEventListener("popstate",s),o()}},[i.isAuthenticated,i.tokens,t,n.enableLogging,p]),_react.useEffect.call(void 0, ()=>{let c=_chunkAT74WV5Wjs.f.subscribe(async s=>{if(n.enableLogging&&console.log(`\u{1F4E2} useSession: Received auth event: ${s.type}`),s.type==="TOKEN_EXPIRED"){if(t.isRefreshing()){n.enableLogging&&console.log("\u23F8\uFE0F Refresh already in progress, skipping TOKEN_EXPIRED handler");return}n.enableLogging&&console.log("\u{1F504} Token expired, attempting refresh..."),e(o=>({...o,isLoading:!0}));try{if(await t.refreshTokens()){n.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 n.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(o){n.enableLogging&&console.error("\u274C Error during token refresh:",o),_chunkAT74WV5Wjs.f.emit("SESSION_EXPIRED",{message:o instanceof Error?o.message:"Unknown error during refresh",source:"useSession.TOKEN_EXPIRED handler (error)"})}}(s.type==="SESSION_EXPIRED"||s.type==="TOKEN_REFRESH_FAILED")&&(n.enableLogging&&console.log(`\u{1F534} Session expired (${s.type}), logging out...`),e(o=>({...o,isAuthenticated:!1,tokens:null,isLoading:!1,error:_optionalChain([s, 'access', _77 => _77.details, 'optionalAccess', _78 => _78.message])||"Session expired"})),_optionalChain([n, 'access', _79 => _79.onSessionExpired, 'optionalCall', _80 => _80()]))});return()=>c()},[n.enableLogging,n.onSessionExpired,t]),_react.useEffect.call(void 0, ()=>{let c=f.subscribeToChanges(s=>{s?(n.enableLogging&&console.log("\u{1F504} Tokens updated in another tab"),e(o=>({...o,tokens:s,isAuthenticated:!0}))):(n.enableLogging&&console.log("\u{1F504} Logout detected in another tab"),e(o=>({...o,isAuthenticated:!1,tokens:null})),_chunkAT74WV5Wjs.f.emit("SESSION_EXPIRED",{message:"Sesi\xF3n cerrada en otra pesta\xF1a",source:"CrossTabSync"}))});return()=>c()},[n.enableLogging]);let S=_react.useCallback.call(void 0, ()=>{t.updateLastActivity()},[t]);return{...i,login:u,logout:p,refreshTokens:h,clearError:m,getTokenInfo:T,updateActivity:S,isExpiringSoon:i.tokens?i.tokens.expiresAt-Date.now()<300*1e3:!1,expiresIn:i.tokens?Math.max(0,i.tokens.expiresAt-Date.now()):0,refreshExpiresIn:i.tokens?Math.max(0,i.tokens.refreshExpiresAt-Date.now()):0}}var _material = require('@mui/material');var _uuid = require('uuid');var _dompurify = require('dompurify'); var _dompurify2 = _interopRequireDefault(_dompurify);var ie=_react.createContext.call(void 0, null),ke=n=>_dompurify2.default.sanitize(n,{ALLOWED_TAGS:["b","i","em","strong","br","span"],ALLOWED_ATTR:["class"],FORBID_TAGS:["script","iframe","object","embed"],FORBID_ATTR:["onload","onerror","onclick","onmouseover","onfocus","onblur"],WHOLE_DOCUMENT:!1,RETURN_DOM:!1,RETURN_DOM_FRAGMENT:!1,RETURN_TRUSTED_TYPE:!1}),X= exports.g =({children:n,maxNotifications:i=5,defaultAutoHideDuration:e=6e3,position:t={vertical:"top",horizontal:"right"},enabled:r=!1,allowHtml:u=!1})=>{let[p,h]=_react.useState.call(void 0, []),m=_react.useCallback.call(void 0, (s,o="info",a)=>{if(!r)return"";if(!s||typeof s!="string")return console.warn("\u26A0\uFE0F GlobalNotificationProvider: Invalid message provided"),"";s.length>1e3&&(console.warn("\u26A0\uFE0F GlobalNotificationProvider: Message too long, truncating"),s=s.substring(0,1e3)+"...");let d=_uuid.v4.call(void 0, ),A={id:d,message:s,severity:o,autoHideDuration:_nullishCoalesce(_optionalChain([a, 'optionalAccess', _81 => _81.autoHideDuration]), () => (e)),persistent:_nullishCoalesce(_optionalChain([a, 'optionalAccess', _82 => _82.persistent]), () => (!1)),allowHtml:_nullishCoalesce(_optionalChain([a, 'optionalAccess', _83 => _83.allowHtml]), () => (u))};return h(y=>[...y.length>=i?y.slice(-(i-1)):y,A]),d},[i,e,r,u]),T=_react.useCallback.call(void 0, s=>{h(o=>o.filter(a=>a.id!==s))},[]),S=_react.useCallback.call(void 0, ()=>{h([])},[]),c={showNotification:m,hideNotification:T,clearAllNotifications:S};return _jsxruntime.jsxs.call(void 0, ie.Provider,{value:c,children:[n,r&&_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:p.map(s=>_jsxruntime.jsx.call(void 0, be,{notification:s,onClose:()=>T(s.id)},s.id))})})]})},be=({notification:n,onClose:i})=>{let[e,t]=_react.useState.call(void 0, !0),r=_react.useCallback.call(void 0, (u,p)=>{p!=="clickaway"&&(t(!1),setTimeout(i,300))},[i]);return _react.useEffect.call(void 0, ()=>{if(!n.persistent&&n.autoHideDuration){let u=setTimeout(()=>{r()},n.autoHideDuration);return()=>clearTimeout(u)}},[n.autoHideDuration,n.persistent,r]),_jsxruntime.jsx.call(void 0, _material.Snackbar,{open:e,onClose:r,sx:{position:"relative","& .MuiSnackbarContent-root":{minWidth:"auto"}},TransitionProps:{enter:!0,exit:!0},children:_jsxruntime.jsx.call(void 0, _material.Alert,{variant:"filled",severity:n.severity,onClose:r,sx:{width:"100%",minWidth:"280px",maxWidth:"400px",wordBreak:"break-word"},children:n.allowHtml?_jsxruntime.jsx.call(void 0, "span",{dangerouslySetInnerHTML:{__html:ke(n.message)}}):_jsxruntime.jsx.call(void 0, "span",{children:n.message})})})},ne= exports.h =()=>{let n=_react.useContext.call(void 0, ie);if(!n)throw new Error("useGlobalNotification debe ser usado dentro de un GlobalNotificationProvider");return n};var re=_react.createContext.call(void 0, void 0);function oe({children:n,options:i={},config:e,showNotifications:t=!1,notificationOptions:r={}}){let u;try{let{showNotification:o}=ne();u=o}catch (e5){}let p={};try{console.log("\u{1F535} [SessionProvider/Inner] Attempting to get Crudify context...");let o=q();console.log("\u2705 [SessionProvider/Inner] Crudify context obtained:",{isInitialized:o.isInitialized,isLoading:o.isLoading,hasAdminCredentials:!!o.adminCredentials}),o.isInitialized&&o.adminCredentials?(p=o.adminCredentials,console.log("\u2705 [SessionProvider/Inner] Admin credentials obtained:",p)):o.isLoading?console.log("\u23F3 [SessionProvider/Inner] CrudifyProvider still loading, credentials will be available soon"):console.warn("\u26A0\uFE0F [SessionProvider/Inner] CrudifyProvider initialized but has no adminCredentials")}catch(o){console.warn("\u26A0\uFE0F [SessionProvider/Inner] Could not get Crudify context - this is OK if using external CrudifyProvider:",o)}let h=_react2.default.useMemo(()=>{console.log("\u{1F50D} [SessionProvider] Creating enhancedOptions with adminCredentials:",p);let o={...i,showNotification:u,apiEndpointAdmin:p.apiEndpointAdmin,apiKeyEndpointAdmin:p.apiKeyEndpointAdmin,onSessionExpired:()=>{_optionalChain([i, 'access', _84 => _84.onSessionExpired, 'optionalCall', _85 => _85()])}};return console.log("\u2705 [SessionProvider] enhancedOptions created:",o),o},[i,u,p.apiEndpointAdmin,p.apiKeyEndpointAdmin]),m=Q(h),T=_react.useMemo.call(void 0, ()=>{let o,a,d,A,y,I="unknown";if(_optionalChain([e, 'optionalAccess', _86 => _86.publicApiKey])&&(o=e.publicApiKey,I="props"),_optionalChain([e, 'optionalAccess', _87 => _87.env])&&(a=e.env),_optionalChain([e, 'optionalAccess', _88 => _88.appName])&&(d=e.appName),_optionalChain([e, 'optionalAccess', _89 => _89.loginActions])&&(A=e.loginActions),_optionalChain([e, 'optionalAccess', _90 => _90.logo])&&(y=e.logo),!o){let P=_chunkAT74WV5Wjs.a.call(void 0, "publicApiKey"),N=_chunkAT74WV5Wjs.a.call(void 0, "environment"),x=_chunkAT74WV5Wjs.a.call(void 0, "appName"),g=_chunkAT74WV5Wjs.a.call(void 0, "loginActions"),D=_chunkAT74WV5Wjs.a.call(void 0, "logo");P&&(o=P,I="cookies"),N&&["dev","stg","prod"].includes(N)&&(a=N),x&&(d=decodeURIComponent(x)),g&&(A=decodeURIComponent(g).split(",").map(M=>M.trim()).filter(Boolean)),D&&(y=decodeURIComponent(D))}return{publicApiKey:o,env:a,appName:d,loginActions:A,logo:y}},[e]),S=_react.useMemo.call(void 0, ()=>{if(!_optionalChain([m, 'access', _91 => _91.tokens, 'optionalAccess', _92 => _92.accessToken])||!m.isAuthenticated)return null;try{let o=_chunkAT74WV5Wjs.h.call(void 0, m.tokens.accessToken);if(o&&o.sub&&o.email&&o.subscriber){let a={_id:o.sub,email:o.email,subscriberKey:o.subscriber};return Object.keys(o).forEach(d=>{["sub","email","subscriber"].includes(d)||(a[d]=o[d])}),a}}catch(o){console.error("Error decoding JWT token for sessionData:",o)}return null},[_optionalChain([m, 'access', _93 => _93.tokens, 'optionalAccess', _94 => _94.accessToken]),m.isAuthenticated]),c={...m,sessionData:S,config:T},s={enabled:t,maxNotifications:r.maxNotifications||5,defaultAutoHideDuration:r.defaultAutoHideDuration||6e3,position:r.position||{vertical:"top",horizontal:"right"}};return _jsxruntime.jsx.call(void 0, re.Provider,{value:c,children:n})}function mi(n){let i={enabled:n.showNotifications,maxNotifications:_optionalChain([n, 'access', _95 => _95.notificationOptions, 'optionalAccess', _96 => _96.maxNotifications])||5,defaultAutoHideDuration:_optionalChain([n, 'access', _97 => _97.notificationOptions, 'optionalAccess', _98 => _98.defaultAutoHideDuration])||6e3,position:_optionalChain([n, 'access', _99 => _99.notificationOptions, 'optionalAccess', _100 => _100.position])||{vertical:"top",horizontal:"right"},allowHtml:_optionalChain([n, 'access', _101 => _101.notificationOptions, 'optionalAccess', _102 => _102.allowHtml])||!1};return _optionalChain([n, 'access', _103 => _103.config, 'optionalAccess', _104 => _104.publicApiKey])?(console.log("\u2705 [SessionProvider] Auto-creating internal CrudifyProvider with config:",n.config),_jsxruntime.jsx.call(void 0, Z,{config:{publicApiKey:n.config.publicApiKey,env:n.config.env||"prod",appName:n.config.appName,loginActions:n.config.loginActions,logo:n.config.logo},children:_jsxruntime.jsx.call(void 0, X,{...i,children:_jsxruntime.jsx.call(void 0, oe,{...n})})})):(console.log("\u2705 [SessionProvider] Using external CrudifyProvider"),_jsxruntime.jsx.call(void 0, X,{...i,children:_jsxruntime.jsx.call(void 0, oe,{...n})}))}function Ce(){let n=_react.useContext.call(void 0, re);if(n===void 0)throw new Error("useSessionContext must be used within a SessionProvider");return n}function Ti(){let n=Ce();return n.isInitialized?_jsxruntime.jsxs.call(void 0, "div",{style:{padding:"10px",margin:"10px",border:"1px solid #ccc",borderRadius:"4px",fontSize:"12px",fontFamily:"monospace"},children:[_jsxruntime.jsx.call(void 0, "h4",{children:"Session Debug Info"}),_jsxruntime.jsxs.call(void 0, "div",{children:[_jsxruntime.jsx.call(void 0, "strong",{children:"Authenticated:"})," ",n.isAuthenticated?"Yes":"No"]}),_jsxruntime.jsxs.call(void 0, "div",{children:[_jsxruntime.jsx.call(void 0, "strong",{children:"Loading:"})," ",n.isLoading?"Yes":"No"]}),_jsxruntime.jsxs.call(void 0, "div",{children:[_jsxruntime.jsx.call(void 0, "strong",{children:"Error:"})," ",n.error||"None"]}),n.tokens&&_jsxruntime.jsxs.call(void 0, _jsxruntime.Fragment,{children:[_jsxruntime.jsxs.call(void 0, "div",{children:[_jsxruntime.jsx.call(void 0, "strong",{children:"Access Token:"})," ",n.tokens.accessToken.substring(0,20),"..."]}),_jsxruntime.jsxs.call(void 0, "div",{children:[_jsxruntime.jsx.call(void 0, "strong",{children:"Refresh Token:"})," ",n.tokens.refreshToken.substring(0,20),"..."]}),_jsxruntime.jsxs.call(void 0, "div",{children:[_jsxruntime.jsx.call(void 0, "strong",{children:"Access Expires In:"})," ",Math.round(n.expiresIn/1e3/60)," minutes"]}),_jsxruntime.jsxs.call(void 0, "div",{children:[_jsxruntime.jsx.call(void 0, "strong",{children:"Refresh Expires In:"})," ",Math.round(n.refreshExpiresIn/1e3/60/60)," hours"]}),_jsxruntime.jsxs.call(void 0, "div",{children:[_jsxruntime.jsx.call(void 0, "strong",{children:"Expiring Soon:"})," ",n.isExpiringSoon?"Yes":"No"]})]})]}):_jsxruntime.jsx.call(void 0, "div",{children:"Session not initialized"})}var xi=(n={})=>{let{autoFetch:i=!0,retryOnError:e=!1,maxRetries:t=3}=n,[r,u]=_react.useState.call(void 0, null),[p,h]=_react.useState.call(void 0, !1),[m,T]=_react.useState.call(void 0, null),[S,c]=_react.useState.call(void 0, {}),s=_react.useRef.call(void 0, null),o=_react.useRef.call(void 0, !0),a=_react.useRef.call(void 0, 0),d=_react.useRef.call(void 0, 0),A=_react.useCallback.call(void 0, ()=>{u(null),T(null),h(!1),c({})},[]),y=_react.useCallback.call(void 0, async()=>{let I=_chunkAT74WV5Wjs.i.call(void 0, );if(!I){o.current&&(T("No user email available"),h(!1));return}s.current&&s.current.abort();let P=new AbortController;s.current=P;let N=++a.current;try{o.current&&(h(!0),T(null));let x=await _crudifybrowser2.default.readItems("users",{filter:{email:I},pagination:{limit:1}});if(N===a.current&&o.current&&!P.signal.aborted)if(x.success&&x.data&&x.data.length>0){let g=x.data[0];u(g);let D={fullProfile:g,totalFields:Object.keys(g).length,displayData:{id:g.id,email:g.email,username:g.username,firstName:g.firstName,lastName:g.lastName,fullName:g.fullName||`${g.firstName||""} ${g.lastName||""}`.trim(),role:g.role,permissions:g.permissions||[],isActive:g.isActive,lastLogin:g.lastLogin,createdAt:g.createdAt,updatedAt:g.updatedAt,...Object.keys(g).filter(O=>!["id","email","username","firstName","lastName","fullName","role","permissions","isActive","lastLogin","createdAt","updatedAt"].includes(O)).reduce((O,M)=>({...O,[M]:g[M]}),{})}};c(D),T(null),d.current=0}else T("User profile not found"),u(null),c({})}catch(x){if(N===a.current&&o.current){let g=x;if(g.name==="AbortError")return;e&&d.current<t&&(_optionalChain([g, 'access', _105 => _105.message, 'optionalAccess', _106 => _106.includes, 'call', _107 => _107("Network Error")])||_optionalChain([g, 'access', _108 => _108.message, 'optionalAccess', _109 => _109.includes, 'call', _110 => _110("Failed to fetch")]))?(d.current++,setTimeout(()=>{o.current&&y()},1e3*d.current)):(T("Failed to load user profile"),u(null),c({}))}}finally{N===a.current&&o.current&&h(!1),s.current===P&&(s.current=null)}},[e,t]);return _react.useEffect.call(void 0, ()=>{i&&y()},[i,y]),_react.useEffect.call(void 0, ()=>(o.current=!0,()=>{o.current=!1,s.current&&(s.current.abort(),s.current=null)}),[]),{userProfile:r,loading:p,error:m,extendedData:S,refreshProfile:y,clearProfile:A}};exports.a = j; exports.b = Z; exports.c = q; exports.d = f; exports.e = z; exports.f = Q; exports.g = X; exports.h = ne; exports.i = mi; exports.j = Ce; exports.k = Ti; exports.l = xi;
|
|
@@ -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 _chunkMIRR6QT5js = require('./chunk-MIRR6QT5.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}=_chunkMIRR6QT5js.i.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}=_chunkMIRR6QT5js.i.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}=_chunkMIRR6QT5js.i.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}=_chunkMIRR6QT5js.g.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 _chunkBP6LQCYDjs = require('./chunk-BP6LQCYD.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}=_chunkBP6LQCYDjs.j.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}=_chunkBP6LQCYDjs.j.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}=_chunkBP6LQCYDjs.j.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}=_chunkBP6LQCYDjs.h.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 +1 @@
|
|
|
1
|
-
import{g as $,i as D}from"./chunk-727DU3JS.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{h as $,j as D}from"./chunk-5KDBFWCO.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};
|