@nocios/crudify-ui 5.0.2 → 5.0.6

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.
@@ -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 _chunkMFYHD6S5js = require('./chunk-MFYHD6S5.js');var Ne="crudify_storage_version",Re=2,a=class a{static setStorageType(i){a.storageType=i}static async initialize(){if(!(a.encryptionKey&&a.salt))return a.initPromise||(a.initPromise=(async()=>{try{a.checkStorageVersion(),a.salt=a.getOrCreateSalt(),a.fingerprint=await a.generateFingerprint(),a.encryptionKey=await _chunkMFYHD6S5js.g.call(void 0, a.fingerprint,a.salt)}catch(i){throw _chunkMFYHD6S5js.a.error("Crudify: Failed to initialize encryption",i instanceof Error?i:{message:String(i)}),i}})()),a.initPromise}static checkStorageVersion(){try{if(parseInt(localStorage.getItem(Ne)||"1",10)<Re){let e=a.getStorage();e&&e.removeItem(a.TOKEN_KEY),localStorage.removeItem(a.ENCRYPTION_KEY_STORAGE),localStorage.removeItem(a.SALT_KEY),localStorage.setItem(Ne,Re.toString()),_chunkMFYHD6S5js.a.info("Crudify: Storage upgraded to v2, tokens cleared for security")}}catch (e2){}}static getOrCreateSalt(){try{let e=localStorage.getItem(a.SALT_KEY);if(e){let t=atob(e),n=new Uint8Array(t.length);for(let o=0;o<t.length;o++)n[o]=t.charCodeAt(o);return n}}catch (e3){}let i=_chunkMFYHD6S5js.j.call(void 0, );try{let e="";for(let t=0;t<i.length;t++)e+=String.fromCharCode(i[t]);localStorage.setItem(a.SALT_KEY,btoa(e))}catch (e4){_chunkMFYHD6S5js.a.warn("Crudify: Cannot persist salt, encryption may not persist across sessions")}return i}static async generateFingerprint(){let i=new Uint8Array(16);crypto.getRandomValues(i);let e=Array.from(i,o=>o.toString(16).padStart(2,"0")).join(""),t=[navigator.userAgent,navigator.language,navigator.platform,screen.width,screen.height,e].join("|");try{let o=localStorage.getItem(a.ENCRYPTION_KEY_STORAGE);if(o&&o.length>=32)return o}catch (e5){}let n=await _chunkMFYHD6S5js.f.call(void 0, t);try{localStorage.setItem(a.ENCRYPTION_KEY_STORAGE,n)}catch (e6){_chunkMFYHD6S5js.a.warn("Crudify: Cannot persist encryption key hash")}return n}static isStorageAvailable(i){try{let e=window[i],t="__storage_test__";return e.setItem(t,"test"),e.removeItem(t),!0}catch (e7){return!1}}static getStorage(){return a.storageType==="none"?null:a.isStorageAvailable(a.storageType)?window[a.storageType]:(_chunkMFYHD6S5js.a.warn(`Crudify: ${a.storageType} not available, tokens won't persist`),null)}static async encryptData(i){if(await a.initialize(),!a.encryptionKey||!a.salt)throw new Error("Encryption not initialized");return _chunkMFYHD6S5js.h.call(void 0, i,a.encryptionKey,a.salt)}static async decryptData(i){if(await a.initialize(),!a.fingerprint)throw new Error("Encryption not initialized");return _chunkMFYHD6S5js.k.call(void 0, i)?_chunkMFYHD6S5js.i.call(void 0, i,a.fingerprint):(_chunkMFYHD6S5js.a.warn("Crudify: Legacy encrypted data detected, cannot decrypt"),null)}static async saveTokens(i){let e=a.getStorage();if(e)try{let t={accessToken:i.accessToken,refreshToken:i.refreshToken,expiresAt:i.expiresAt,refreshExpiresAt:i.refreshExpiresAt,savedAt:Date.now()},n=await a.encryptData(JSON.stringify(t));e.setItem(a.TOKEN_KEY,n),_chunkMFYHD6S5js.a.debug("Crudify: Tokens saved successfully")}catch(t){_chunkMFYHD6S5js.a.error("Crudify: Failed to save tokens",t instanceof Error?t:{message:String(t)})}}static async getTokens(){let i=a.getStorage();if(!i)return null;try{let e=i.getItem(a.TOKEN_KEY);if(!e)return null;let t=await a.decryptData(e);if(!t)return _chunkMFYHD6S5js.a.warn("Crudify: Failed to decrypt tokens, clearing storage"),await a.clearTokens(),null;let n=JSON.parse(t);return!n.accessToken||!n.refreshToken||!n.expiresAt||!n.refreshExpiresAt?(_chunkMFYHD6S5js.a.warn("Crudify: Incomplete token data found, clearing storage"),await a.clearTokens(),null):Date.now()>=n.refreshExpiresAt?(_chunkMFYHD6S5js.a.info("Crudify: Refresh token expired, clearing storage"),await a.clearTokens(),null):{accessToken:n.accessToken,refreshToken:n.refreshToken,expiresAt:n.expiresAt,refreshExpiresAt:n.refreshExpiresAt}}catch(e){return _chunkMFYHD6S5js.a.error("Crudify: Failed to retrieve tokens",e instanceof Error?e:{message:String(e)}),await a.clearTokens(),null}}static async clearTokens(){let i=a.getStorage();if(i)try{i.removeItem(a.TOKEN_KEY),_chunkMFYHD6S5js.a.debug("Crudify: Tokens cleared from storage")}catch(e){_chunkMFYHD6S5js.a.error("Crudify: Failed to clear tokens",e instanceof Error?e:{message:String(e)})}}static async rotateEncryptionKey(){try{await a.clearTokens(),a.encryptionKey=null,a.salt=null,a.fingerprint=null,a.initPromise=null;try{localStorage.removeItem(a.ENCRYPTION_KEY_STORAGE),localStorage.removeItem(a.SALT_KEY)}catch (e8){}_chunkMFYHD6S5js.a.info("Crudify: Encryption key rotated successfully")}catch(i){_chunkMFYHD6S5js.a.error("Crudify: Failed to rotate encryption key",i instanceof Error?i:{message:String(i)})}}static async hasValidTokens(){return await a.getTokens()!==null}static async getExpirationInfo(){let i=await a.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 async updateAccessToken(i,e){let t=await a.getTokens();if(!t){_chunkMFYHD6S5js.a.warn("Crudify: Cannot update access token, no existing tokens found");return}await a.saveTokens({...t,accessToken:i,expiresAt:e})}static createSyncEvent(i,e,t){return{type:i,tokens:e,hadPreviousTokens:t}}static subscribeToChanges(i){let e=async t=>{if(t.key!==a.TOKEN_KEY)return;let n=t.oldValue!==null&&t.oldValue!=="";if(t.newValue===null){_chunkMFYHD6S5js.a.debug("Crudify: Tokens removed in another tab"),i(null,a.SYNC_EVENTS.TOKENS_CLEARED,n);return}if(t.newValue){_chunkMFYHD6S5js.a.debug("Crudify: Tokens updated in another tab");let o=await a.getTokens();i(o,a.SYNC_EVENTS.TOKENS_UPDATED,n)}};return window.addEventListener("storage",e),()=>{window.removeEventListener("storage",e)}}};a.TOKEN_KEY="crudify_tokens",a.ENCRYPTION_KEY_STORAGE="crudify_enc_key",a.SALT_KEY="crudify_enc_salt",a.encryptionKey=null,a.salt=null,a.fingerprint=null,a.storageType="localStorage",a.initPromise=null,a.SYNC_EVENTS={TOKENS_CLEARED:"TOKENS_CLEARED",TOKENS_UPDATED:"TOKENS_UPDATED"};var b=a;var _crudifybrowser = require('@nocios/crudify-browser'); var _crudifybrowser2 = _interopRequireDefault(_crudifybrowser);var ee=class r{constructor(){this.config={};this.initialized=!1;this.crudifyInitialized=!1;this.lastActivityTime=0;this.isRefreshingLocally=!1;this.refreshPromise=null}static getInstance(){return r.instance||(r.instance=new r),r.instance}async initialize(i={}){if(!this.initialized){if(this.config={storageType:"localStorage",autoRestore:!0,enableLogging:!1,env:"stg",...i},b.setStorageType(this.config.storageType||"localStorage"),this.config.publicApiKey&&!this.crudifyInitialized&&await this.ensureCrudifyInitialized(),_crudifybrowser2.default.setTokenInvalidationCallback(()=>{this.log("Tokens invalidated by crudify-core"),_chunkMFYHD6S5js.e.emit("SESSION_EXPIRED",{message:"Your session has expired. Please log in again.",source:"crudify-core.clearTokensAndRefreshState"})}),this.config.apiEndpointAdmin&&this.config.apiKeyEndpointAdmin){let e=await b.getTokens();e?await b.saveTokens({...e,apiEndpointAdmin:this.config.apiEndpointAdmin,apiKeyEndpointAdmin:this.config.apiKeyEndpointAdmin}):await b.saveTokens({accessToken:"",refreshToken:"",expiresAt:0,refreshExpiresAt:0,apiEndpointAdmin:this.config.apiEndpointAdmin,apiKeyEndpointAdmin:this.config.apiKeyEndpointAdmin})}this.config.autoRestore&&await this.restoreSession(),this.initialized=!0}}async login(i,e){try{let t=await _crudifybrowser2.default.login(i,e);if(!t.success)return{success:!1,error:this.formatError(t.errors),rawResponse:t};let n=await b.getTokens(),o=t.data,m={accessToken:o.token,refreshToken:o.refreshToken,expiresAt:o.expiresAt,refreshExpiresAt:o.refreshExpiresAt,apiEndpointAdmin:_optionalChain([n, 'optionalAccess', _2 => _2.apiEndpointAdmin])||this.config.apiEndpointAdmin,apiKeyEndpointAdmin:_optionalChain([n, 'optionalAccess', _3 => _3.apiKeyEndpointAdmin])||this.config.apiKeyEndpointAdmin};return await b.saveTokens(m),this.lastActivityTime=Date.now(),_optionalChain([this, 'access', _4 => _4.config, 'access', _5 => _5.onLoginSuccess, 'optionalCall', _6 => _6(m)]),{success:!0,tokens:m,data:o}}catch(t){return _chunkMFYHD6S5js.a.error("[SessionManager] Login error",t instanceof Error?t:{message:String(t)}),{success:!1,error:t instanceof Error?t.message:"Unknown error"}}}async logout(){try{this.log("Logging out..."),_chunkMFYHD6S5js.e.emit("LOGOUT",{message:"User logged out",source:"SessionManager.logout"}),await _crudifybrowser2.default.logout(),await b.clearTokens(),this.log("Logout successful"),_optionalChain([this, 'access', _7 => _7.config, 'access', _8 => _8.onLogout, 'optionalCall', _9 => _9()])}catch(i){this.log("Logout error",{error:i instanceof Error?i.message:String(i)}),await b.clearTokens()}}async restoreSession(){try{this.log("Attempting to restore session...");let i=await b.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"),await b.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 n=await b.getTokens();return n&&_optionalChain([this, 'access', _10 => _10.config, 'access', _11 => _11.onSessionRestored, 'optionalCall', _12 => _12(n)]),!0}return await b.clearTokens(),await _crudifybrowser2.default.logout(),!1}return this.log("Session restored successfully"),this.lastActivityTime=Date.now(),_optionalChain([this, 'access', _13 => _13.config, 'access', _14 => _14.onSessionRestored, 'optionalCall', _15 => _15(i)]),!0}catch(i){return this.log("Session restore error",{error:i instanceof Error?i.message:String(i)}),await b.clearTokens(),await _crudifybrowser2.default.logout(),!1}}async isAuthenticated(){return _crudifybrowser2.default.isLogin()||await b.hasValidTokens()}async getTokenInfo(){let i=_crudifybrowser2.default.getTokenData(),e=await b.getExpirationInfo(),t=await b.getTokens();return{isLoggedIn:await this.isAuthenticated(),crudifyTokens:i,storageInfo:e,hasValidTokens:await b.hasValidTokens(),apiEndpointAdmin:_optionalChain([t, 'optionalAccess', _16 => _16.apiEndpointAdmin]),apiKeyEndpointAdmin:_optionalChain([t, 'optionalAccess', _17 => _17.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",{errors:i.errors}),await b.clearTokens(),_optionalChain([this, 'access', _18 => _18.config, 'access', _19 => _19.showNotification, 'optionalCall', _20 => _20(this.getSessionExpiredMessage(),"warning")]),_optionalChain([this, 'access', _21 => _21.config, 'access', _22 => _22.onSessionExpired, 'optionalCall', _23 => _23()]),!1;let e=i.data,t={accessToken:e.token,refreshToken:e.refreshToken,expiresAt:e.expiresAt,refreshExpiresAt:e.refreshExpiresAt};return await b.saveTokens(t),this.log("Tokens refreshed and saved successfully"),this.lastActivityTime=Date.now(),!0}catch(i){return this.log("Token refresh error",{error:i instanceof Error?i.message:String(i)}),await b.clearTokens(),_optionalChain([this, 'access', _24 => _24.config, 'access', _25 => _25.showNotification, 'optionalCall', _26 => _26(this.getSessionExpiredMessage(),"warning")]),_optionalChain([this, 'access', _27 => _27.config, 'access', _28 => _28.onSessionExpired, 'optionalCall', _29 => _29()]),!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"),_chunkMFYHD6S5js.e.emit("TOKEN_REFRESH_FAILED",{message:e.userFriendlyMessage,error:e.errorDetails,source:"SessionManager.setupResponseInterceptor"}),i;e.shouldTriggerLogout&&(await b.hasValidTokens()&&!e.isIrrecoverable?(this.log("Access token expired, emitting TOKEN_EXPIRED event"),_chunkMFYHD6S5js.e.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"),_chunkMFYHD6S5js.e.emit("SESSION_EXPIRED",{message:e.userFriendlyMessage,error:e.errorDetails,source:"SessionManager.setupResponseInterceptor"})))}return i}),this.log("Response interceptor configured (non-blocking mode)")}async ensureCrudifyInitialized(){if(!this.crudifyInitialized)try{this.log("Initializing crudify SDK...");let i=_crudifybrowser2.default.getTokenData();if(i&&i.endpoint){this.log("Crudify already initialized by another service"),this.crudifyInitialized=!0;return}let e=this.config.env||"stg";_crudifybrowser2.default.config(e);let t=this.config.publicApiKey,n=this.config.enableLogging?"debug":"none",o=await _crudifybrowser2.default.init(t,n);if(o&&o.success===!1&&o.errors)throw new Error(`Failed to initialize crudify: ${JSON.stringify(o.errors)}`);this.crudifyInitialized=!0,this.log("Crudify SDK initialized successfully")}catch(i){throw _chunkMFYHD6S5js.a.error("[SessionManager] Failed to initialize crudify",i instanceof Error?i:{message:String(i)}),i}}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(n=>n.errorType==="Unauthorized"||_optionalChain([n, 'access', _30 => _30.message, 'optionalAccess', _31 => _31.includes, 'call', _32 => _32("Unauthorized")])||_optionalChain([n, 'access', _33 => _33.message, 'optionalAccess', _34 => _34.includes, 'call', _35 => _35("Not Authorized")])||_optionalChain([n, 'access', _36 => _36.message, 'optionalAccess', _37 => _37.includes, 'call', _38 => _38("NOT_AUTHORIZED")])||_optionalChain([n, 'access', _39 => _39.message, 'optionalAccess', _40 => _40.includes, 'call', _41 => _41("Token")])||_optionalChain([n, 'access', _42 => _42.message, 'optionalAccess', _43 => _43.includes, 'call', _44 => _44("TOKEN")])||_optionalChain([n, 'access', _45 => _45.message, 'optionalAccess', _46 => _46.includes, 'call', _47 => _47("Authentication")])||_optionalChain([n, 'access', _48 => _48.message, 'optionalAccess', _49 => _49.includes, 'call', _50 => _50("UNAUTHENTICATED")])||_optionalChain([n, 'access', _51 => _51.extensions, 'optionalAccess', _52 => _52.code])==="UNAUTHENTICATED"||_optionalChain([n, 'access', _53 => _53.extensions, 'optionalAccess', _54 => _54.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', _55 => _55.message, 'optionalAccess', _56 => _56.includes, 'call', _57 => _57("TOKEN")])||_optionalChain([t, 'access', _58 => _58.message, 'optionalAccess', _59 => _59.includes, 'call', _60 => _60("Token")]))&&(e.isTokenExpired=!0),_optionalChain([t, 'access', _61 => _61.extensions, 'optionalAccess', _62 => _62.code])==="UNAUTHENTICATED"&&(e.isUnauthorized=!0))}if(!e.isAuthError&&i.errors&&typeof i.errors=="object"&&!Array.isArray(i.errors)){let n=Object.values(i.errors).flat().find(o=>typeof o=="string"&&(o.includes("NOT_AUTHORIZED")||o.includes("TOKEN_REFRESH_FAILED")||o.includes("TOKEN_HAS_EXPIRED")||o.includes("PLEASE_LOGIN")||o.includes("Unauthorized")||o.includes("UNAUTHENTICATED")||o.includes("SESSION_EXPIRED")||o.includes("INVALID_TOKEN")));n&&typeof n=="string"&&(e.isAuthError=!0,e.errorType="GraphQL Object",e.errorDetails=i.errors,e.shouldTriggerLogout=!0,n.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."):n.includes("TOKEN_HAS_EXPIRED")||n.includes("SESSION_EXPIRED")?(e.isTokenExpired=!0,e.userFriendlyMessage="Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente."):n.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', _63 => _63.data, 'optionalAccess', _64 => _64.response, 'optionalAccess', _65 => _65.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', _66 => _66.data, 'optionalAccess', _67 => _67.response, 'optionalAccess', _68 => _68.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 (e9){}if(!e.isAuthError&&i.errorCode){let t=String(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();if(this.lastActivityTime===0)return"none";let e=1800*1e3;return i>e?(this.log(`Inactivity timeout: ${Math.floor(i/6e4)} minutes since last activity`),"logout"):"none"}async clearSession(){await b.clearTokens(),await _crudifybrowser2.default.logout(),this.lastActivityTime=0,this.log("Session cleared completely")}getSessionExpiredMessage(){return this.config.translateFn?_chunkMFYHD6S5js.l.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&&_chunkMFYHD6S5js.a.debug(`[SessionManager] ${i}`,e)}formatError(i){return i?typeof i=="string"?i:typeof i=="object"?Object.values(i).flat().map(String).join(", "):"Authentication failed":"Unknown error"}};var _react = require('react'); var _react2 = _interopRequireDefault(_react);function Ce(r={}){let[i,e]=_react.useState.call(void 0, {isAuthenticated:!1,isLoading:!0,isInitialized:!1,tokens:null,error:null}),t=ee.getInstance(),n=_react.useCallback.call(void 0, async()=>{try{e(s=>({...s,isLoading:!0,error:null}));let u={autoRestore:_nullishCoalesce(r.autoRestore, () => (!0)),enableLogging:_nullishCoalesce(r.enableLogging, () => (!1)),showNotification:r.showNotification,translateFn:r.translateFn,apiEndpointAdmin:r.apiEndpointAdmin,apiKeyEndpointAdmin:r.apiKeyEndpointAdmin,publicApiKey:r.publicApiKey,env:r.env||"stg",onSessionExpired:()=>{e(s=>({...s,isAuthenticated:!1,tokens:null,error:"Session expired"})),_optionalChain([r, 'access', _69 => _69.onSessionExpired, 'optionalCall', _70 => _70()])},onSessionRestored:s=>{e(E=>({...E,isAuthenticated:!0,tokens:s,error:null})),_optionalChain([r, 'access', _71 => _71.onSessionRestored, 'optionalCall', _72 => _72(s)])},onLoginSuccess:s=>{e(E=>({...E,isAuthenticated:!0,tokens:s,error:null}))},onLogout:()=>{e(s=>({...s,isAuthenticated:!1,tokens:null,error:null}))}};await t.initialize(u),t.setupResponseInterceptor();let l=await t.isAuthenticated(),f=await t.getTokenInfo();e(s=>({...s,isAuthenticated:l,isInitialized:!0,isLoading:!1,tokens:f.crudifyTokens.accessToken?{accessToken:f.crudifyTokens.accessToken,refreshToken:f.crudifyTokens.refreshToken,expiresAt:f.crudifyTokens.expiresAt,refreshExpiresAt:f.crudifyTokens.refreshExpiresAt}:null}))}catch(u){let l=u instanceof Error?u.message:"Initialization failed";_chunkMFYHD6S5js.a.error("[useSession] Initialize failed",u instanceof Error?u:{message:l}),e(f=>({...f,isLoading:!1,isInitialized:!0,error:l}))}},[r.autoRestore,r.enableLogging,r.onSessionExpired,r.onSessionRestored]),o=_react.useCallback.call(void 0, async(u,l)=>{e(f=>({...f,isLoading:!0,error:null}));try{let f=await t.login(u,l);return f.success&&f.tokens?e(s=>({...s,isAuthenticated:!0,tokens:f.tokens,isLoading:!1,error:null})):e(s=>({...s,isAuthenticated:!1,tokens:null,isLoading:!1,error:null})),f}catch(f){let s=f instanceof Error?f.message:"Login failed";_chunkMFYHD6S5js.a.error("[useSession] Login error",f instanceof Error?f:{message:s});let E=s.includes("INVALID_CREDENTIALS")||s.includes("Invalid email")||s.includes("Invalid password")||s.includes("credentials");return e(k=>({...k,isAuthenticated:!1,tokens:null,isLoading:!1,error:E?null:s})),{success:!1,error:s}}},[t]),m=_react.useCallback.call(void 0, async()=>{e(u=>({...u,isLoading:!0}));try{await t.logout(),e(u=>({...u,isAuthenticated:!1,tokens:null,isLoading:!1,error:null}))}catch(u){e(l=>({...l,isAuthenticated:!1,tokens:null,isLoading:!1,error:u instanceof Error?u.message:"Logout error"}))}},[t]),T=_react.useCallback.call(void 0, async()=>{try{let u=await t.refreshTokens();if(u){let l=await t.getTokenInfo();e(f=>({...f,tokens:l.crudifyTokens.accessToken?{accessToken:l.crudifyTokens.accessToken,refreshToken:l.crudifyTokens.refreshToken,expiresAt:l.crudifyTokens.expiresAt,refreshExpiresAt:l.crudifyTokens.refreshExpiresAt}:null,error:null}))}else e(l=>({...l,isAuthenticated:!1,tokens:null,error:"Token refresh failed"}));return u}catch(u){return e(l=>({...l,isAuthenticated:!1,tokens:null,error:u instanceof Error?u.message:"Token refresh failed"})),!1}},[t]),x=_react.useCallback.call(void 0, ()=>{e(u=>({...u,error:null}))},[]),A=_react.useCallback.call(void 0, async()=>t.getTokenInfo(),[t]);_react.useEffect.call(void 0, ()=>{n()},[n]),_react.useEffect.call(void 0, ()=>{if(!i.isAuthenticated||!i.tokens)return;let u=_chunkMFYHD6S5js.p.getInstance(),l=()=>{t.updateLastActivity()},f=u.subscribe(l);window.addEventListener("popstate",l);let s=async()=>{let R=(await t.getTokenInfo()).crudifyTokens.expiresIn||0;return R<300*1e3?30*1e3:R<1800*1e3?60*1e3:120*1e3},E,k=async()=>{let S=await s();E=setTimeout(async()=>{if(t.isRefreshing()){k();return}let R=await t.getTokenInfo(),w=R.crudifyTokens.expiresIn||0,C=((R.crudifyTokens.expiresAt||0)-(Date.now()-w))*.5;if(w>0&&w<=C)if(e(K=>({...K,isLoading:!0})),await t.refreshTokens()){let K=await t.getTokenInfo();e(ce=>({...ce,isLoading:!1,tokens:K.crudifyTokens.accessToken?{accessToken:K.crudifyTokens.accessToken,refreshToken:K.crudifyTokens.refreshToken,expiresAt:K.crudifyTokens.expiresAt,refreshExpiresAt:K.crudifyTokens.refreshExpiresAt}:null}))}else e(K=>({...K,isLoading:!1,isAuthenticated:!1,tokens:null}));let v=t.getTimeSinceLastActivity(),X=1800*1e3;v>X?await m():k()},S)};return k(),()=>{clearTimeout(E),window.removeEventListener("popstate",l),f()}},[i.isAuthenticated,i.tokens,t,r.enableLogging,m]),_react.useEffect.call(void 0, ()=>{let u=_chunkMFYHD6S5js.e.subscribe(async l=>{if(l.type==="TOKEN_EXPIRED"){if(t.isRefreshing())return;e(f=>({...f,isLoading:!0}));try{if(await t.refreshTokens()){let s=await t.getTokenInfo();e(E=>({...E,isLoading:!1,tokens:s.crudifyTokens.accessToken?{accessToken:s.crudifyTokens.accessToken,refreshToken:s.crudifyTokens.refreshToken,expiresAt:s.crudifyTokens.expiresAt,refreshExpiresAt:s.crudifyTokens.refreshExpiresAt}:null}))}else _chunkMFYHD6S5js.e.emit("SESSION_EXPIRED",{message:"Failed to refresh token after detecting expiration",source:"useSession.TOKEN_EXPIRED handler"})}catch(f){_chunkMFYHD6S5js.e.emit("SESSION_EXPIRED",{message:f instanceof Error?f.message:"Unknown error during refresh",source:"useSession.TOKEN_EXPIRED handler (error)"})}}(l.type==="SESSION_EXPIRED"||l.type==="TOKEN_REFRESH_FAILED")&&(e(f=>({...f,isAuthenticated:!1,tokens:null,isLoading:!1,error:_optionalChain([l, 'access', _73 => _73.details, 'optionalAccess', _74 => _74.message])||"Session expired"})),_optionalChain([r, 'access', _75 => _75.onSessionExpired, 'optionalCall', _76 => _76()]))});return()=>u()},[r.onSessionExpired,t]),_react.useEffect.call(void 0, ()=>{let u=b.subscribeToChanges((l,f,s)=>{f===b.SYNC_EVENTS.TOKENS_CLEARED?s&&i.isAuthenticated?(_chunkMFYHD6S5js.a.debug("[useSession] Cross-tab logout detected"),e(E=>({...E,isAuthenticated:!1,tokens:null})),_optionalChain([r, 'access', _77 => _77.onSessionExpired, 'optionalCall', _78 => _78()])):s&&e(E=>({...E,isAuthenticated:!1,tokens:null})):f===b.SYNC_EVENTS.TOKENS_UPDATED&&l&&(_chunkMFYHD6S5js.a.debug("[useSession] Cross-tab login/refresh detected"),e(E=>({...E,tokens:l,isAuthenticated:!0,error:null})))});return()=>u()},[i.isAuthenticated,r.onSessionExpired]);let F=_react.useCallback.call(void 0, ()=>{t.updateLastActivity()},[t]);return{...i,login:o,logout:m,refreshTokens:T,clearError:x,getTokenInfo:A,updateActivity:F,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 _jsxruntime = require('react/jsx-runtime');var Le=_react.createContext.call(void 0, null),Ai=r=>_dompurify2.default.sanitize(r,{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}),fe= exports.d =({children:r,maxNotifications:i=5,defaultAutoHideDuration:e=6e3,position:t={vertical:"top",horizontal:"right"},enabled:n=!1,allowHtml:o=!1})=>{let[m,T]=_react.useState.call(void 0, []),x=_react.useCallback.call(void 0, (l,f="info",s)=>{if(!n)return"";if(!l||typeof l!="string")return _chunkMFYHD6S5js.a.warn("GlobalNotificationProvider: Invalid message provided"),"";l.length>1e3&&(_chunkMFYHD6S5js.a.warn("GlobalNotificationProvider: Message too long, truncating"),l=l.substring(0,1e3)+"...");let E=_uuid.v4.call(void 0, ),k={id:E,message:l,severity:f,autoHideDuration:_nullishCoalesce(_optionalChain([s, 'optionalAccess', _79 => _79.autoHideDuration]), () => (e)),persistent:_nullishCoalesce(_optionalChain([s, 'optionalAccess', _80 => _80.persistent]), () => (!1)),allowHtml:_nullishCoalesce(_optionalChain([s, 'optionalAccess', _81 => _81.allowHtml]), () => (o))};return T(S=>[...S.length>=i?S.slice(-(i-1)):S,k]),E},[i,e,n,o]),A=_react.useCallback.call(void 0, l=>{T(f=>f.filter(s=>s.id!==l))},[]),F=_react.useCallback.call(void 0, ()=>{T([])},[]),u={showNotification:x,hideNotification:A,clearAllNotifications:F};return _jsxruntime.jsxs.call(void 0, Le.Provider,{value:u,children:[r,n&&_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:m.map(l=>_jsxruntime.jsx.call(void 0, Ii,{notification:l,onClose:()=>A(l.id)},l.id))})})]})},Ii=({notification:r,onClose:i})=>{let[e,t]=_react.useState.call(void 0, !0),n=_react.useCallback.call(void 0, (o,m)=>{m!=="clickaway"&&(t(!1),setTimeout(i,300))},[i]);return _react.useEffect.call(void 0, ()=>{if(!r.persistent&&r.autoHideDuration){let o=setTimeout(()=>{n()},r.autoHideDuration);return()=>clearTimeout(o)}},[r.autoHideDuration,r.persistent,n]),_jsxruntime.jsx.call(void 0, _material.Snackbar,{open:e,onClose:n,sx:{position:"relative","& .MuiSnackbarContent-root":{minWidth:"auto"}},TransitionProps:{enter:!0,exit:!0},children:_jsxruntime.jsx.call(void 0, _material.Alert,{variant:"filled",severity:r.severity,onClose:n,sx:{width:"100%",minWidth:"280px",maxWidth:"400px",wordBreak:"break-word"},children:r.allowHtml?_jsxruntime.jsx.call(void 0, "span",{dangerouslySetInnerHTML:{__html:Ai(r.message)}}):_jsxruntime.jsx.call(void 0, "span",{children:r.message})})})},Fe= exports.e =()=>{let r=_react.useContext.call(void 0, Le);if(!r)throw new Error("useGlobalNotification debe ser usado dentro de un GlobalNotificationProvider");return r};var ge=class r{constructor(){this.listeners=[];this.credentials=null;this.isReady=!1}static getInstance(){return r.instance||(r.instance=new r),r.instance}notifyCredentialsReady(i){this.credentials=i,this.isReady=!0,this.listeners.forEach(e=>{try{e(i)}catch(t){_chunkMFYHD6S5js.a.error("[CredentialsEventBus] Error in listener",t instanceof Error?t:{message:String(t)})}}),this.listeners=[]}waitForCredentials(){return this.isReady&&this.credentials?Promise.resolve(this.credentials):new Promise(i=>{this.listeners.push(i)})}reset(){this.credentials=null,this.isReady=!1,this.listeners=[]}areCredentialsReady(){return this.isReady&&this.credentials!==null}},re= exports.f =ge.getInstance();var ze=_react.createContext.call(void 0, void 0),Ke= exports.g =({config:r,children:i})=>{let[e,t]=_react.useState.call(void 0, !0),[n,o]=_react.useState.call(void 0, null),[m,T]=_react.useState.call(void 0, !1),[x,A]=_react.useState.call(void 0, ""),[F,u]=_react.useState.call(void 0, );_react.useEffect.call(void 0, ()=>{if(!r.publicApiKey){o("No publicApiKey provided"),t(!1),T(!1);return}let f=`${r.publicApiKey}-${r.env}`;if(f===x&&m){t(!1);return}(async()=>{t(!0),o(null),T(!1);try{_crudifybrowser2.default.config(r.env||"prod");let E=await _crudifybrowser2.default.init(r.publicApiKey,"none");if(u(E),typeof _crudifybrowser2.default.transaction=="function"&&typeof _crudifybrowser2.default.login=="function")T(!0),A(f),E.apiEndpointAdmin&&E.apiKeyEndpointAdmin&&re.notifyCredentialsReady({apiUrl:E.apiEndpointAdmin,apiKey:E.apiKeyEndpointAdmin});else throw new Error("Crudify methods not properly initialized")}catch(E){let k=E instanceof Error?E.message:"Failed to initialize Crudify";_chunkMFYHD6S5js.a.error("[CrudifyProvider] Initialization error",E instanceof Error?E:{message:String(E)}),o(k),T(!1)}finally{t(!1)}})()},[r.publicApiKey,r.env,x,m]);let l={crudify:m?_crudifybrowser2.default:null,isLoading:e,error:n,isInitialized:m,adminCredentials:F};return _jsxruntime.jsx.call(void 0, ze.Provider,{value:l,children:i})},Ue= exports.h =()=>{let r=_react.useContext.call(void 0, ze);if(r===void 0)throw new Error("useCrudify must be used within a CrudifyProvider");return r};var He=_react.createContext.call(void 0, void 0);function Oe({children:r,options:i={},config:e,showNotifications:t=!1,notificationOptions:n={}}){let o;try{let{showNotification:s}=Fe();o=s}catch (e10){}let m={};try{let s=Ue();s.isInitialized&&s.adminCredentials&&(m=s.adminCredentials)}catch (e11){}let T=_react.useMemo.call(void 0, ()=>{let s=_chunkMFYHD6S5js.c.call(void 0, {publicApiKey:_optionalChain([e, 'optionalAccess', _82 => _82.publicApiKey]),env:_optionalChain([e, 'optionalAccess', _83 => _83.env]),enableDebug:_optionalChain([i, 'optionalAccess', _84 => _84.enableLogging])});return{publicApiKey:s.publicApiKey,env:s.env||"prod"}},[e,_optionalChain([i, 'optionalAccess', _85 => _85.enableLogging])]),x=_react2.default.useMemo(()=>({...i,showNotification:o,apiEndpointAdmin:m.apiEndpointAdmin,apiKeyEndpointAdmin:m.apiKeyEndpointAdmin,publicApiKey:T.publicApiKey,env:T.env,onSessionExpired:()=>{_optionalChain([i, 'access', _86 => _86.onSessionExpired, 'optionalCall', _87 => _87()])}}),[i,o,m.apiEndpointAdmin,m.apiKeyEndpointAdmin,T]),A=Ce(x),F=_react.useMemo.call(void 0, ()=>{let s=_chunkMFYHD6S5js.c.call(void 0, {publicApiKey:_optionalChain([e, 'optionalAccess', _88 => _88.publicApiKey]),env:_optionalChain([e, 'optionalAccess', _89 => _89.env]),appName:_optionalChain([e, 'optionalAccess', _90 => _90.appName]),logo:_optionalChain([e, 'optionalAccess', _91 => _91.logo]),loginActions:_optionalChain([e, 'optionalAccess', _92 => _92.loginActions]),enableDebug:_optionalChain([i, 'optionalAccess', _93 => _93.enableLogging])});return{publicApiKey:s.publicApiKey,env:s.env,appName:s.appName,loginActions:s.loginActions,logo:s.logo}},[e,_optionalChain([i, 'optionalAccess', _94 => _94.enableLogging])]),u=_react.useMemo.call(void 0, ()=>{if(!_optionalChain([A, 'access', _95 => _95.tokens, 'optionalAccess', _96 => _96.accessToken])||!A.isAuthenticated)return null;try{let s=_chunkMFYHD6S5js.q.call(void 0, A.tokens.accessToken);if(s&&s.sub&&s.email&&s.subscriber){let E={_id:s.sub,email:s.email,subscriberKey:s.subscriber};return Object.keys(s).forEach(k=>{["sub","email","subscriber"].includes(k)||(E[k]=s[k])}),E}}catch(s){_chunkMFYHD6S5js.a.error("Error decoding JWT token for sessionData",s instanceof Error?s:{message:String(s)})}return null},[_optionalChain([A, 'access', _97 => _97.tokens, 'optionalAccess', _98 => _98.accessToken]),A.isAuthenticated]),l={...A,sessionData:u,config:F},f={enabled:t,maxNotifications:n.maxNotifications||5,defaultAutoHideDuration:n.defaultAutoHideDuration||6e3,position:n.position||{vertical:"top",horizontal:"right"}};return _jsxruntime.jsx.call(void 0, He.Provider,{value:l,children:r})}function Ft(r){let i={enabled:r.showNotifications,maxNotifications:_optionalChain([r, 'access', _99 => _99.notificationOptions, 'optionalAccess', _100 => _100.maxNotifications])||5,defaultAutoHideDuration:_optionalChain([r, 'access', _101 => _101.notificationOptions, 'optionalAccess', _102 => _102.defaultAutoHideDuration])||6e3,position:_optionalChain([r, 'access', _103 => _103.notificationOptions, 'optionalAccess', _104 => _104.position])||{vertical:"top",horizontal:"right"},allowHtml:_optionalChain([r, 'access', _105 => _105.notificationOptions, 'optionalAccess', _106 => _106.allowHtml])||!1};return _optionalChain([r, 'access', _107 => _107.config, 'optionalAccess', _108 => _108.publicApiKey])?_jsxruntime.jsx.call(void 0, Ke,{config:{publicApiKey:r.config.publicApiKey,env:r.config.env||"prod",appName:r.config.appName,loginActions:r.config.loginActions,logo:r.config.logo},children:_jsxruntime.jsx.call(void 0, fe,{...i,children:_jsxruntime.jsx.call(void 0, Oe,{...r})})}):_jsxruntime.jsx.call(void 0, fe,{...i,children:_jsxruntime.jsx.call(void 0, Oe,{...r})})}function Di(){let r=_react.useContext.call(void 0, He);if(r===void 0)throw new Error("useSessionContext must be used within a SessionProvider");return r}function zt(){let r=Di();return r.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:"})," ",r.isAuthenticated?"Yes":"No"]}),_jsxruntime.jsxs.call(void 0, "div",{children:[_jsxruntime.jsx.call(void 0, "strong",{children:"Loading:"})," ",r.isLoading?"Yes":"No"]}),_jsxruntime.jsxs.call(void 0, "div",{children:[_jsxruntime.jsx.call(void 0, "strong",{children:"Error:"})," ",r.error||"None"]}),r.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:"})," ",r.tokens.accessToken.substring(0,20),"..."]}),_jsxruntime.jsxs.call(void 0, "div",{children:[_jsxruntime.jsx.call(void 0, "strong",{children:"Refresh Token:"})," ",r.tokens.refreshToken.substring(0,20),"..."]}),_jsxruntime.jsxs.call(void 0, "div",{children:[_jsxruntime.jsx.call(void 0, "strong",{children:"Access Expires In:"})," ",Math.round(r.expiresIn/1e3/60)," minutes"]}),_jsxruntime.jsxs.call(void 0, "div",{children:[_jsxruntime.jsx.call(void 0, "strong",{children:"Refresh Expires In:"})," ",Math.round(r.refreshExpiresIn/1e3/60/60)," hours"]}),_jsxruntime.jsxs.call(void 0, "div",{children:[_jsxruntime.jsx.call(void 0, "strong",{children:"Expiring Soon:"})," ",r.isExpiringSoon?"Yes":"No"]})]})]}):_jsxruntime.jsx.call(void 0, "div",{children:"Session not initialized"})}var Gt=(r={})=>{let{autoFetch:i=!0,retryOnError:e=!1,maxRetries:t=3}=r,[n,o]=_react.useState.call(void 0, null),[m,T]=_react.useState.call(void 0, !1),[x,A]=_react.useState.call(void 0, null),[F,u]=_react.useState.call(void 0, {}),l=_react.useRef.call(void 0, null),f=_react.useRef.call(void 0, !0),s=_react.useRef.call(void 0, 0),E=_react.useRef.call(void 0, 0),k=_react.useCallback.call(void 0, ()=>{o(null),A(null),T(!1),u({})},[]),S=_react.useCallback.call(void 0, async()=>{let R=_chunkMFYHD6S5js.r.call(void 0, );if(!R){f.current&&(A("No user email available"),T(!1));return}l.current&&l.current.abort();let w=new AbortController;l.current=w;let z=++s.current;try{f.current&&(T(!0),A(null));let U=await _crudifybrowser2.default.readItems("users",{filter:{email:R},pagination:{limit:1}});if(z===s.current&&f.current&&!w.signal.aborted){let C=U.data;if(U.success&&C&&C.length>0){let v=C[0];o(v);let X={fullProfile:v,totalFields:Object.keys(v).length,displayData:{id:v.id,email:v.email,username:v.username,firstName:v.firstName,lastName:v.lastName,fullName:v.fullName||`${v.firstName||""} ${v.lastName||""}`.trim(),role:v.role,permissions:v.permissions||[],isActive:v.isActive,lastLogin:v.lastLogin,createdAt:v.createdAt,updatedAt:v.updatedAt,...Object.keys(v).filter(V=>!["id","email","username","firstName","lastName","fullName","role","permissions","isActive","lastLogin","createdAt","updatedAt"].includes(V)).reduce((V,K)=>({...V,[K]:v[K]}),{})}};u(X),A(null),E.current=0}else A("User profile not found"),o(null),u({})}}catch(U){if(z===s.current&&f.current){let C=U;if(C.name==="AbortError")return;e&&E.current<t&&(_optionalChain([C, 'access', _109 => _109.message, 'optionalAccess', _110 => _110.includes, 'call', _111 => _111("Network Error")])||_optionalChain([C, 'access', _112 => _112.message, 'optionalAccess', _113 => _113.includes, 'call', _114 => _114("Failed to fetch")]))?(E.current++,setTimeout(()=>{f.current&&S()},1e3*E.current)):(A("Failed to load user profile"),o(null),u({}))}}finally{z===s.current&&f.current&&T(!1),l.current===w&&(l.current=null)}},[e,t]);return _react.useEffect.call(void 0, ()=>{i&&S()},[i,S]),_react.useEffect.call(void 0, ()=>(f.current=!0,()=>{f.current=!1,l.current&&(l.current.abort(),l.current=null)}),[]),{userProfile:n,loading:m,error:x,extendedData:F,refreshProfile:S,clearProfile:k}};var $t=(r,i={})=>{let{autoFetch:e=!0,onSuccess:t,onError:n}=i,{prefix:o,padding:m=0,separator:T=""}=r,[x,A]=_react.useState.call(void 0, ""),[F,u]=_react.useState.call(void 0, !1),[l,f]=_react.useState.call(void 0, null),s=_react.useRef.call(void 0, !1),E=_react.useCallback.call(void 0, w=>{let z=String(w).padStart(m,"0");return`${o}${T}${z}`},[o,m,T]),k=_react.useCallback.call(void 0, async()=>{u(!0),f(null);try{let w=await _crudifybrowser2.default.getNextSequence(o),z=w.data;if(w.success&&_optionalChain([z, 'optionalAccess', _115 => _115.value])){let U=E(z.value);A(U),_optionalChain([t, 'optionalCall', _116 => _116(U)])}else{let U=_optionalChain([w, 'access', _117 => _117.errors, 'optionalAccess', _118 => _118._error, 'optionalAccess', _119 => _119[0]])||"Failed to generate code";f(U),_optionalChain([n, 'optionalCall', _120 => _120(U)])}}catch(w){let z=w instanceof Error?w.message:"Unknown error";f(z),_optionalChain([n, 'optionalCall', _121 => _121(z)])}finally{u(!1)}},[o,E,t,n]),S=_react.useCallback.call(void 0, async()=>{await k()},[k]),R=_react.useCallback.call(void 0, ()=>{f(null)},[]);return _react.useEffect.call(void 0, ()=>{e&&!x&&!s.current&&(s.current=!0,k())},[e,x,k]),{value:x,loading:F,error:l,regenerate:S,clearError:R}};var he=class r{constructor(){this.state={status:"UNINITIALIZED",priority:null,publicApiKey:null,env:null,error:null,initializedBy:null};this.initializationPromise=null;this.highPriorityInitializerPresent=!1;this.waitingForHighPriority=new Set;this.HIGH_PRIORITY_WAIT_TIMEOUT=100}static getInstance(){return r.instance||(r.instance=new r),r.instance}registerHighPriorityInitializer(){this.highPriorityInitializerPresent=!0}isHighPriorityInitializerPresent(){return this.highPriorityInitializerPresent}getState(){return{...this.state}}async initialize(i){let{priority:e,publicApiKey:t,env:n,enableLogging:o,requestedBy:m}=i;if(this.state.status==="INITIALIZED"){this.state.publicApiKey!==t&&_chunkMFYHD6S5js.a.warn(`[CrudifyInitialization] ${m} attempted to initialize with different key. Already initialized with key: ${_optionalChain([this, 'access', _122 => _122.state, 'access', _123 => _123.publicApiKey, 'optionalAccess', _124 => _124.slice, 'call', _125 => _125(0,10)])}... by ${this.state.initializedBy}`);return}if(this.initializationPromise)return o&&_chunkMFYHD6S5js.a.debug(`[CrudifyInitialization] ${m} waiting for ongoing initialization...`),this.initializationPromise;if(e==="LOW"&&this.highPriorityInitializerPresent&&this.state.status==="UNINITIALIZED"){if(o&&_chunkMFYHD6S5js.a.debug(`[CrudifyInitialization] ${m} (LOW priority) waiting for HIGH priority initializer...`),this.waitingForHighPriority.add(m),await this.waitForHighPriorityOrTimeout(o),this.waitingForHighPriority.delete(m),this.getState().status==="INITIALIZED"){o&&_chunkMFYHD6S5js.a.debug(`[CrudifyInitialization] ${m} found initialization completed by HIGH priority`);return}o&&_chunkMFYHD6S5js.a.warn(`[CrudifyInitialization] ${m} timeout waiting for HIGH priority, initializing with LOW priority`)}e==="HIGH"&&this.state.status==="INITIALIZING"&&this.state.priority==="LOW"&&(_chunkMFYHD6S5js.a.warn(`[CrudifyInitialization] HIGH priority request from ${m} interrupting LOW priority initialization by ${this.state.initializedBy}`),this.state.status="UNINITIALIZED",this.initializationPromise=null),o&&_chunkMFYHD6S5js.a.debug(`[CrudifyInitialization] ${m} starting initialization (${e} priority)...`),this.state.status="INITIALIZING",this.state.priority=e,this.state.initializedBy=m,this.initializationPromise=this.performInitialization(t,n,o);try{await this.initializationPromise,this.state.status="INITIALIZED",this.state.publicApiKey=t,this.state.env=n,this.state.error=null,o&&_chunkMFYHD6S5js.a.info(`[CrudifyInitialization] Successfully initialized by ${m} (${e} priority)`)}catch(T){throw this.state.status="ERROR",this.state.error=T instanceof Error?T:new Error(String(T)),this.initializationPromise=null,_chunkMFYHD6S5js.a.error(`[CrudifyInitialization] Initialization failed for ${m}`,T instanceof Error?T:{message:String(T)}),T}}async waitForHighPriorityOrTimeout(i){return new Promise(e=>{let n=0,o=setInterval(()=>{if(n+=10,this.state.status==="INITIALIZED"&&this.state.priority==="HIGH"){clearInterval(o),e();return}if(this.state.status==="INITIALIZING"&&this.state.priority==="HIGH"){n=0;return}n>=this.HIGH_PRIORITY_WAIT_TIMEOUT&&(clearInterval(o),i&&_chunkMFYHD6S5js.a.debug(`[CrudifyInitialization] Timeout waiting for HIGH priority (${this.HIGH_PRIORITY_WAIT_TIMEOUT}ms)`),e())},10)})}async performInitialization(i,e,t){let n=_crudifybrowser2.default.getTokenData();if(n&&n.endpoint){t&&_chunkMFYHD6S5js.a.debug("[CrudifyInitialization] SDK already initialized externally");return}_crudifybrowser2.default.config(e);let o=t?"debug":"none",m=await _crudifybrowser2.default.init(i,o);if(m.success===!1)throw new Error(`Crudify initialization failed: ${JSON.stringify(m.errors||"Unknown error")}`);m.apiEndpointAdmin&&m.apiKeyEndpointAdmin&&re.notifyCredentialsReady({apiUrl:m.apiEndpointAdmin,apiKey:m.apiKeyEndpointAdmin})}reset(){this.state={status:"UNINITIALIZED",priority:null,publicApiKey:null,env:null,error:null,initializedBy:null},this.initializationPromise=null,this.highPriorityInitializerPresent=!1,this.waitingForHighPriority.clear()}isInitialized(){return this.state.status==="INITIALIZED"}getDiagnostics(){return{...this.state,waitingCount:this.waitingForHighPriority.size,waitingComponents:Array.from(this.waitingForHighPriority),hasActivePromise:this.initializationPromise!==null}}},Q= exports.o =he.getInstance();var _e=r=>{let i=new Uint8Array(r);return crypto.getRandomValues(i),Array.from(i,e=>e.toString(36).padStart(2,"0")).join("").substring(0,r)},Ve=()=>`file_${Date.now()}_${_e(7)}`,Hi=r=>{let i=r.lastIndexOf("."),e=i>0?r.substring(i):"",t=Date.now(),n=_e(6);return`${t}_${n}${e}`},Ee=(r,i)=>{if(r.startsWith("http://")||r.startsWith("https://"))try{let e=new URL(r);return e.pathname.startsWith("/")?e.pathname.substring(1):e.pathname}catch (e12){if(i&&r.startsWith(i))return r.substring(i.length)}return i&&r.startsWith(i)?r.substring(i.length):r},ir= exports.p =(r={})=>{let{acceptedTypes:i,maxFileSize:e=10*1024*1024,maxFiles:t,minFiles:n=0,visibility:o="private",onUploadComplete:m,onUploadError:T,onFileRemoved:x,onFilesChange:A,mode:F="edit"}=r,[u,l]=_react.useState.call(void 0, []),[f,s]=_react.useState.call(void 0, !1),[E,k]=_react.useState.call(void 0, !1),[S,R]=_react.useState.call(void 0, []),w=_react.useRef.call(void 0, new Map),z=_react.useCallback.call(void 0, ()=>{s(!0)},[]),U=_react.useCallback.call(void 0, ()=>{k(!0),s(!0)},[]),C=_react.useCallback.call(void 0, (c,p)=>{l(d=>d.map(h=>h.id===c?{...h,...p}:h))},[]),v=_react.useCallback.call(void 0, c=>{_optionalChain([A, 'optionalCall', _126 => _126(c)])},[A]),X=_react.useCallback.call(void 0, c=>i&&i.length>0&&!i.includes(c.type)?{valid:!1,error:`File type not allowed: ${c.type}`}:c.size>e?{valid:!1,error:`File exceeds maximum size of ${(e/1048576).toFixed(1)}MB`}:{valid:!0},[i,e]),V=_react.useCallback.call(void 0, async(c,p)=>{try{if(!Q.isInitialized())throw new Error("Crudify is not initialized. Please wait for the application to finish loading.");let d=Hi(p.name),y=await _crudifybrowser2.default.generateSignedUrl({fileName:d,contentType:p.type,visibility:o});if(!y.success||!y.data)throw new Error("Failed to get upload URL");let h=y.data,{uploadUrl:P,s3Key:I,publicUrl:H}=h;if(!P||!I)throw new Error("Incomplete signed URL response");let Y=I.indexOf("/"),ci=Y>0?I.substring(Y+1):I;C(c.id,{status:"uploading",progress:0}),await new Promise((ue,$)=>{let O=new XMLHttpRequest;O.upload.addEventListener("progress",_=>{if(_.lengthComputable){let di=Math.round(_.loaded/_.total*100);C(c.id,{progress:di})}}),O.addEventListener("load",()=>{O.status>=200&&O.status<300?ue():$(new Error(`Upload failed with status ${O.status}`))}),O.addEventListener("error",()=>{$(new Error("Network error during upload"))}),O.addEventListener("abort",()=>{$(new Error("Upload cancelled"))}),O.open("PUT",P),O.setRequestHeader("Content-Type",p.type),O.send(p)});let ui={status:"completed",progress:100,filePath:ci,visibility:o,publicUrl:o==="public"?H:void 0,file:void 0};l(ue=>{let $=ue.map(_=>_.id===c.id?{..._,...ui}:_);v($);let O=$.find(_=>_.id===c.id);return O&&_optionalChain([m, 'optionalCall', _127 => _127(O)]),$})}catch(d){let y=d instanceof Error?d.message:"Unknown error";C(c.id,{status:"error",progress:0,errorMessage:y}),l(h=>{let P=h.find(I=>I.id===c.id);return P&&_optionalChain([T, 'optionalCall', _128 => _128(P,y)]),h})}},[C,m,T,o]),K=_react.useCallback.call(void 0, async c=>{let p=Array.from(c),d=[];l(y=>{if(t!==void 0){let I=y.filter(Y=>Y.status!=="pendingDeletion"&&Y.status!=="error").length,H=t-I;if(H<=0)return _chunkMFYHD6S5js.a.warn(`File limit of ${t} already reached`),y;p.length>H&&(p=p.slice(0,H),_chunkMFYHD6S5js.a.warn(`Only ${H} files will be added to not exceed limit`))}let h=[];for(let I of p){let H=X(I),Y={id:Ve(),name:I.name,size:I.size,contentType:I.type,status:H.valid?"pending":"error",progress:0,createdAt:Date.now(),file:H.valid?I:void 0,errorMessage:H.error,isExisting:!1};h.push(Y)}d=h;let P=[...y,...h];return v(P),P}),setTimeout(()=>{let y=d.filter(h=>h.status==="pending"&&h.file);for(let h of y)if(h.file){let P=V(h,h.file);w.current.set(h.id,P),P.finally(()=>{w.current.delete(h.id)})}},0)},[t,X,V,v]),ce=_react.useCallback.call(void 0, async c=>{let p=u.find(y=>y.id===c);if(!p)return{needsConfirmation:!1,isExisting:!1};let d=p.isExisting===!0;return F==="create"||!d?{needsConfirmation:!0,isExisting:d}:(R(y=>[...y,c]),l(y=>{let h=y.map(I=>I.id===c?{...I,status:"pendingDeletion"}:I),P=h.filter(I=>I.status!=="pendingDeletion");return v(P),h}),{needsConfirmation:!1,isExisting:d})},[u,F,v]),Ye=_react.useCallback.call(void 0, async c=>{let p=u.find(d=>d.id===c);if(!p)return{success:!1,error:"File not found"};if(!p.filePath)return l(d=>{let y=d.filter(h=>h.id!==c);return v(y),y}),{success:!0};try{if(!Q.isInitialized())return{success:!1,error:"Crudify not initialized"};let d=Ee(p.filePath);return(await _crudifybrowser2.default.disableFile({filePath:d})).success?(l(h=>{let P=h.filter(I=>I.id!==c);return v(P),P}),_optionalChain([x, 'optionalCall', _129 => _129(p)]),{success:!0}):{success:!1,error:"Failed to delete file"}}catch(d){return{success:!1,error:d instanceof Error?d.message:"Unknown error"}}},[u,v,x]),$e=_react.useCallback.call(void 0, c=>{let p=u.find(d=>d.id===c);return!p||!p.isExisting?!1:(R(d=>d.filter(y=>y!==c)),l(d=>{let y=d.map(h=>h.id===c?{...h,status:"completed"}:h);return v(y),y}),!0)},[u,v]),We=_react.useCallback.call(void 0, ()=>{S.length!==0&&(l(c=>{let p=c.map(d=>S.includes(d.id)?{...d,status:"completed"}:d);return v(p),p}),R([]))},[S,v]),Be=_react.useCallback.call(void 0, async()=>{if(S.length===0)return{success:!0,errors:[]};let c=[],p=[];if(!Q.isInitialized())return{success:!1,errors:["Crudify is not initialized. Please wait for the application to finish loading."]};for(let d of S){let y=u.find(h=>h.id===d);if(!_optionalChain([y, 'optionalAccess', _130 => _130.filePath])){p.push(d);continue}try{let h=Ee(y.filePath);(await _crudifybrowser2.default.disableFile({filePath:h})).success?(p.push(d),_optionalChain([x, 'optionalCall', _131 => _131(y)])):c.push(`Failed to delete ${y.name}`)}catch(h){c.push(`Error deleting ${y.name}: ${h instanceof Error?h.message:"Unknown error"}`)}}return p.length>0&&(l(d=>d.filter(h=>!p.includes(h.id))),R(d=>d.filter(y=>!p.includes(y)))),{success:c.length===0,errors:c}},[u,S,x]),Xe=_react.useCallback.call(void 0, ()=>{l([]),v([])},[v]),Ze=_react.useCallback.call(void 0, async c=>{let p=u.find(y=>y.id===c);if(!p||p.status!=="error"||!p.file){_chunkMFYHD6S5js.a.warn("Cannot retry: file not found or no original file");return}C(c,{status:"pending",progress:0,errorMessage:void 0});let d=V(p,p.file);w.current.set(c,d),d.finally(()=>{w.current.delete(c)})},[u,C,V]),qe=_react.useCallback.call(void 0, async()=>{let c=Array.from(w.current.values());return c.length>0&&await Promise.allSettled(c),new Promise(p=>{setTimeout(()=>{l(d=>{let y=d.filter(h=>h.status==="completed"&&h.filePath).map(h=>h.filePath);return p(y),d})},0)})},[]),je=c=>{let p=_optionalChain([c, 'access', _132 => _132.split, 'call', _133 => _133("."), 'access', _134 => _134.pop, 'call', _135 => _135(), 'optionalAccess', _136 => _136.toLowerCase, 'call', _137 => _137()])||"";return{jpg:"image/jpeg",jpeg:"image/jpeg",png:"image/png",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",bmp:"image/bmp",ico:"image/x-icon",pdf:"application/pdf",doc:"application/msword",docx:"application/vnd.openxmlformats-officedocument.wordprocessingml.document",xls:"application/vnd.ms-excel",xlsx:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",ppt:"application/vnd.ms-powerpoint",pptx:"application/vnd.openxmlformats-officedocument.presentationml.presentation",txt:"text/plain",csv:"text/csv",mp3:"audio/mpeg",wav:"audio/wav",mp4:"video/mp4",webm:"video/webm",zip:"application/zip",rar:"application/x-rar-compressed",json:"application/json",xml:"application/xml"}[p]||"application/octet-stream"},Je=_react.useCallback.call(void 0, (c,p)=>{let d=c.map(y=>{let h=Ee(y.filePath,p),P=h.includes("/public/")||h.startsWith("public/")?"public":"private",I=y.contentType||je(y.name);return{id:Ve(),name:y.name,size:y.size||0,contentType:I,status:"completed",progress:100,filePath:h,visibility:P,createdAt:Date.now(),isExisting:!0}});l(d),v(d)},[v]),Qe=_react.useCallback.call(void 0, async c=>{let p=u.find(d=>d.id===c);if(!p||!p.filePath)return null;if(p.visibility==="public"&&p.publicUrl)return p.publicUrl;try{if(!Q.isInitialized())return null;let d=await _crudifybrowser2.default.getFileUrl({filePath:p.filePath,expiresIn:3600}),y=d.data;return d.success&&_optionalChain([y, 'optionalAccess', _138 => _138.url])?y.url:null}catch (e13){return null}},[u]),ei=_react.useMemo.call(void 0, ()=>u.some(c=>c.status==="uploading"||c.status==="pending"),[u]),ii=_react.useMemo.call(void 0, ()=>u.filter(c=>c.status==="uploading"||c.status==="pending").length,[u]),ti=_react.useMemo.call(void 0, ()=>u.filter(c=>c.status==="completed"&&c.filePath).map(c=>c.filePath),[u]),Z=_react.useMemo.call(void 0, ()=>u.filter(c=>c.status!=="pendingDeletion"),[u]),ri=_react.useMemo.call(void 0, ()=>Z.filter(c=>c.status==="completed"||c.status==="pending"||c.status==="uploading").length,[Z]),{isValid:ni,validationError:si,validationErrorKey:oi,validationErrorParams:ai}=_react.useMemo.call(void 0, ()=>{let c=Z.filter(d=>d.status==="completed").length;if(c<n){let d=n===1?"file.validation.minFilesRequired":"file.validation.minFilesRequiredPlural";return{isValid:!1,validationError:d,validationErrorKey:d,validationErrorParams:{count:n}}}return t!==void 0&&c>t?{isValid:!1,validationError:"file.validation.maxFilesExceeded",validationErrorKey:"file.validation.maxFilesExceeded",validationErrorParams:{count:t}}:Z.some(d=>d.status==="error")?{isValid:!1,validationError:"file.validation.filesWithErrors",validationErrorKey:"file.validation.filesWithErrors",validationErrorParams:{}}:{isValid:!0,validationError:null,validationErrorKey:null,validationErrorParams:{}}},[Z,n,t]),li=S.length>0;return{files:u,activeFiles:Z,activeFileCount:ri,isUploading:ei,pendingCount:ii,addFiles:K,removeFile:ce,deleteFileImmediately:Ye,restoreFile:$e,clearFiles:Xe,retryUpload:Ze,isValid:ni,validationError:si,validationErrorKey:oi,validationErrorParams:ai,waitForUploads:qe,completedFilePaths:ti,initializeFiles:Je,isTouched:f,markAsTouched:z,isSubmitted:E,markAsSubmitted:U,getPreviewUrl:Qe,pendingDeletions:S,hasPendingDeletions:li,commitDeletions:Be,restorePendingDeletions:We}};exports.a = b; exports.b = ee; exports.c = Ce; exports.d = fe; exports.e = Fe; exports.f = re; exports.g = Ke; exports.h = Ue; exports.i = Ft; exports.j = Di; exports.k = zt; exports.l = Gt; exports.m = $t; exports.n = he; exports.o = Q; exports.p = ir;
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true});var _chunk5VOTRIDBjs = require('./chunk-5VOTRIDB.js');var _chunk3XZ3TEKQjs = require('./chunk-3XZ3TEKQ.js');require('./chunk-NSV6ECYO.js');require('./chunk-NXTXGTU6.js');var _react = require('react');var _jsxruntime = require('react/jsx-runtime');function z({showBelowMinutes:f=5,position:m="bottom-right",colorNormal:c="#ed6c02",colorCritical:x="#d32f2f",style:u,className:g}={}){let{isAuthenticated:o,tokens:t}=_chunk3XZ3TEKQjs.c.call(void 0, ),[i,y]=_react.useState.call(void 0, 0),[h,C]=_react.useState.call(void 0, 100);if(_react.useEffect.call(void 0, ()=>{if(!o||!t)return;let v=setInterval(()=>{let P=Date.now(),p=t.expiresAt-P,w=900*1e3;y(Math.max(0,p)),C(Math.max(0,p/w*100))},1e3);return()=>clearInterval(v)},[o,t]),!o||i<=0)return null;let e=Math.floor(i/6e4),S=Math.floor(i%6e4/1e3);if(e>=f)return null;let s=e<2,a=s?x:c,b={"top-left":{top:"16px",left:"16px"},"top-right":{top:"16px",right:"16px"},"bottom-left":{bottom:"16px",left:"16px"},"bottom-right":{bottom:"16px",right:"16px"}}[m];return _jsxruntime.jsxs.call(void 0, "div",{className:g,style:{position:"fixed",...b,padding:"12px 16px",backgroundColor:"white",borderRadius:"8px",boxShadow:"0 4px 12px rgba(0, 0, 0, 0.15)",minWidth:"200px",zIndex:9999,fontFamily:"system-ui, -apple-system, sans-serif",...u},children:[_jsxruntime.jsxs.call(void 0, "div",{style:{marginBottom:"8px"},children:[_jsxruntime.jsx.call(void 0, "div",{style:{fontSize:"12px",fontWeight:600,color:a,marginBottom:"4px"},children:s?"\u26A0\uFE0F Sesi\xF3n expirando":"\u23F0 Sesi\xF3n por expirar"}),_jsxruntime.jsxs.call(void 0, "div",{style:{fontSize:"14px",color:"#333",fontWeight:500},children:[e,":",S.toString().padStart(2,"0")]})]}),_jsxruntime.jsx.call(void 0, "div",{style:{width:"100%",height:"6px",backgroundColor:"#e0e0e0",borderRadius:"3px",overflow:"hidden"},children:_jsxruntime.jsx.call(void 0, "div",{style:{width:`${h}%`,height:"100%",backgroundColor:a,transition:"width 1s linear"}})})]})}exports.CrudiaAutoGenerate = _chunk5VOTRIDBjs.o; exports.CrudiaFileField = _chunk5VOTRIDBjs.p; exports.CrudiaMarkdownField = _chunk5VOTRIDBjs.q; exports.CrudifyLogin = _chunk5VOTRIDBjs.h; exports.GlobalNotificationProvider = _chunk3XZ3TEKQjs.d; exports.LoginComponent = _chunk5VOTRIDBjs.m; exports.Policies = _chunk5VOTRIDBjs.l; exports.SessionStatus = _chunk5VOTRIDBjs.n; exports.SessionTimeIndicator = z; exports.UserProfileDisplay = _chunk5VOTRIDBjs.i; exports.useGlobalNotification = _chunk3XZ3TEKQjs.e;
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true});var _chunkPYLSSR7Wjs = require('./chunk-PYLSSR7W.js');var _chunkSFIIFYMZjs = require('./chunk-SFIIFYMZ.js');require('./chunk-NSV6ECYO.js');require('./chunk-MFYHD6S5.js');var _react = require('react');var _jsxruntime = require('react/jsx-runtime');function z({showBelowMinutes:f=5,position:m="bottom-right",colorNormal:c="#ed6c02",colorCritical:x="#d32f2f",style:u,className:g}={}){let{isAuthenticated:o,tokens:t}=_chunkSFIIFYMZjs.c.call(void 0, ),[i,y]=_react.useState.call(void 0, 0),[h,C]=_react.useState.call(void 0, 100);if(_react.useEffect.call(void 0, ()=>{if(!o||!t)return;let v=setInterval(()=>{let P=Date.now(),p=t.expiresAt-P,w=900*1e3;y(Math.max(0,p)),C(Math.max(0,p/w*100))},1e3);return()=>clearInterval(v)},[o,t]),!o||i<=0)return null;let e=Math.floor(i/6e4),S=Math.floor(i%6e4/1e3);if(e>=f)return null;let s=e<2,a=s?x:c,b={"top-left":{top:"16px",left:"16px"},"top-right":{top:"16px",right:"16px"},"bottom-left":{bottom:"16px",left:"16px"},"bottom-right":{bottom:"16px",right:"16px"}}[m];return _jsxruntime.jsxs.call(void 0, "div",{className:g,style:{position:"fixed",...b,padding:"12px 16px",backgroundColor:"white",borderRadius:"8px",boxShadow:"0 4px 12px rgba(0, 0, 0, 0.15)",minWidth:"200px",zIndex:9999,fontFamily:"system-ui, -apple-system, sans-serif",...u},children:[_jsxruntime.jsxs.call(void 0, "div",{style:{marginBottom:"8px"},children:[_jsxruntime.jsx.call(void 0, "div",{style:{fontSize:"12px",fontWeight:600,color:a,marginBottom:"4px"},children:s?"\u26A0\uFE0F Sesi\xF3n expirando":"\u23F0 Sesi\xF3n por expirar"}),_jsxruntime.jsxs.call(void 0, "div",{style:{fontSize:"14px",color:"#333",fontWeight:500},children:[e,":",S.toString().padStart(2,"0")]})]}),_jsxruntime.jsx.call(void 0, "div",{style:{width:"100%",height:"6px",backgroundColor:"#e0e0e0",borderRadius:"3px",overflow:"hidden"},children:_jsxruntime.jsx.call(void 0, "div",{style:{width:`${h}%`,height:"100%",backgroundColor:a,transition:"width 1s linear"}})})]})}exports.CrudiaAutoGenerate = _chunkPYLSSR7Wjs.o; exports.CrudiaFileField = _chunkPYLSSR7Wjs.p; exports.CrudiaMarkdownField = _chunkPYLSSR7Wjs.q; exports.CrudifyLogin = _chunkPYLSSR7Wjs.h; exports.GlobalNotificationProvider = _chunkSFIIFYMZjs.d; exports.LoginComponent = _chunkPYLSSR7Wjs.m; exports.Policies = _chunkPYLSSR7Wjs.l; exports.SessionStatus = _chunkPYLSSR7Wjs.n; exports.SessionTimeIndicator = z; exports.UserProfileDisplay = _chunkPYLSSR7Wjs.i; exports.useGlobalNotification = _chunkSFIIFYMZjs.e;
@@ -1 +1 @@
1
- import{h as N,i as T,l as M,m as k,n as G,o as L,p as A,q as R}from"./chunk-NSA6YDHY.mjs";import{c as d,d as F,e as I}from"./chunk-PARX2RMU.mjs";import"./chunk-JAPL7EZJ.mjs";import"./chunk-6BQGRZYB.mjs";import{useEffect as B,useState as l}from"react";import{jsx as r,jsxs as n}from"react/jsx-runtime";function z({showBelowMinutes:f=5,position:m="bottom-right",colorNormal:c="#ed6c02",colorCritical:x="#d32f2f",style:u,className:g}={}){let{isAuthenticated:o,tokens:t}=d(),[i,y]=l(0),[h,C]=l(100);if(B(()=>{if(!o||!t)return;let v=setInterval(()=>{let P=Date.now(),p=t.expiresAt-P,w=900*1e3;y(Math.max(0,p)),C(Math.max(0,p/w*100))},1e3);return()=>clearInterval(v)},[o,t]),!o||i<=0)return null;let e=Math.floor(i/6e4),S=Math.floor(i%6e4/1e3);if(e>=f)return null;let s=e<2,a=s?x:c,b={"top-left":{top:"16px",left:"16px"},"top-right":{top:"16px",right:"16px"},"bottom-left":{bottom:"16px",left:"16px"},"bottom-right":{bottom:"16px",right:"16px"}}[m];return n("div",{className:g,style:{position:"fixed",...b,padding:"12px 16px",backgroundColor:"white",borderRadius:"8px",boxShadow:"0 4px 12px rgba(0, 0, 0, 0.15)",minWidth:"200px",zIndex:9999,fontFamily:"system-ui, -apple-system, sans-serif",...u},children:[n("div",{style:{marginBottom:"8px"},children:[r("div",{style:{fontSize:"12px",fontWeight:600,color:a,marginBottom:"4px"},children:s?"\u26A0\uFE0F Sesi\xF3n expirando":"\u23F0 Sesi\xF3n por expirar"}),n("div",{style:{fontSize:"14px",color:"#333",fontWeight:500},children:[e,":",S.toString().padStart(2,"0")]})]}),r("div",{style:{width:"100%",height:"6px",backgroundColor:"#e0e0e0",borderRadius:"3px",overflow:"hidden"},children:r("div",{style:{width:`${h}%`,height:"100%",backgroundColor:a,transition:"width 1s linear"}})})]})}export{L as CrudiaAutoGenerate,A as CrudiaFileField,R as CrudiaMarkdownField,N as CrudifyLogin,F as GlobalNotificationProvider,k as LoginComponent,M as Policies,G as SessionStatus,z as SessionTimeIndicator,T as UserProfileDisplay,I as useGlobalNotification};
1
+ import{h as N,i as T,l as M,m as k,n as G,o as L,p as A,q as R}from"./chunk-6M4Z5KHH.mjs";import{c as d,d as F,e as I}from"./chunk-3OA4S6UT.mjs";import"./chunk-JAPL7EZJ.mjs";import"./chunk-MGJZTOEM.mjs";import{useEffect as B,useState as l}from"react";import{jsx as r,jsxs as n}from"react/jsx-runtime";function z({showBelowMinutes:f=5,position:m="bottom-right",colorNormal:c="#ed6c02",colorCritical:x="#d32f2f",style:u,className:g}={}){let{isAuthenticated:o,tokens:t}=d(),[i,y]=l(0),[h,C]=l(100);if(B(()=>{if(!o||!t)return;let v=setInterval(()=>{let P=Date.now(),p=t.expiresAt-P,w=900*1e3;y(Math.max(0,p)),C(Math.max(0,p/w*100))},1e3);return()=>clearInterval(v)},[o,t]),!o||i<=0)return null;let e=Math.floor(i/6e4),S=Math.floor(i%6e4/1e3);if(e>=f)return null;let s=e<2,a=s?x:c,b={"top-left":{top:"16px",left:"16px"},"top-right":{top:"16px",right:"16px"},"bottom-left":{bottom:"16px",left:"16px"},"bottom-right":{bottom:"16px",right:"16px"}}[m];return n("div",{className:g,style:{position:"fixed",...b,padding:"12px 16px",backgroundColor:"white",borderRadius:"8px",boxShadow:"0 4px 12px rgba(0, 0, 0, 0.15)",minWidth:"200px",zIndex:9999,fontFamily:"system-ui, -apple-system, sans-serif",...u},children:[n("div",{style:{marginBottom:"8px"},children:[r("div",{style:{fontSize:"12px",fontWeight:600,color:a,marginBottom:"4px"},children:s?"\u26A0\uFE0F Sesi\xF3n expirando":"\u23F0 Sesi\xF3n por expirar"}),n("div",{style:{fontSize:"14px",color:"#333",fontWeight:500},children:[e,":",S.toString().padStart(2,"0")]})]}),r("div",{style:{width:"100%",height:"6px",backgroundColor:"#e0e0e0",borderRadius:"3px",overflow:"hidden"},children:r("div",{style:{width:`${h}%`,height:"100%",backgroundColor:a,transition:"width 1s linear"}})})]})}export{L as CrudiaAutoGenerate,A as CrudiaFileField,R as CrudiaMarkdownField,N as CrudifyLogin,F as GlobalNotificationProvider,k as LoginComponent,M as Policies,G as SessionStatus,z as SessionTimeIndicator,T as UserProfileDisplay,I as useGlobalNotification};
package/dist/hooks.js CHANGED
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true});var _chunkLVSNJ4OMjs = require('./chunk-LVSNJ4OM.js');var _chunk3XZ3TEKQjs = require('./chunk-3XZ3TEKQ.js');require('./chunk-NXTXGTU6.js');exports.useAuth = _chunkLVSNJ4OMjs.b; exports.useAutoGenerate = _chunk3XZ3TEKQjs.m; exports.useCrudifyWithNotifications = _chunkLVSNJ4OMjs.d; exports.useData = _chunkLVSNJ4OMjs.c; exports.useFileUpload = _chunk3XZ3TEKQjs.p; exports.useSession = _chunk3XZ3TEKQjs.c; exports.useUserData = _chunkLVSNJ4OMjs.a; exports.useUserProfile = _chunk3XZ3TEKQjs.l;
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true});var _chunkQ4RHNYTIjs = require('./chunk-Q4RHNYTI.js');var _chunkSFIIFYMZjs = require('./chunk-SFIIFYMZ.js');require('./chunk-MFYHD6S5.js');exports.useAuth = _chunkQ4RHNYTIjs.b; exports.useAutoGenerate = _chunkSFIIFYMZjs.m; exports.useCrudifyWithNotifications = _chunkQ4RHNYTIjs.d; exports.useData = _chunkQ4RHNYTIjs.c; exports.useFileUpload = _chunkSFIIFYMZjs.p; exports.useSession = _chunkSFIIFYMZjs.c; exports.useUserData = _chunkQ4RHNYTIjs.a; exports.useUserProfile = _chunkSFIIFYMZjs.l;
package/dist/hooks.mjs CHANGED
@@ -1 +1 @@
1
- import{a as s,b as u,c as a,d as p}from"./chunk-QPTL5FLE.mjs";import{c as e,l as t,m as o,p as r}from"./chunk-PARX2RMU.mjs";import"./chunk-6BQGRZYB.mjs";export{u as useAuth,o as useAutoGenerate,p as useCrudifyWithNotifications,a as useData,r as useFileUpload,e as useSession,s as useUserData,t as useUserProfile};
1
+ import{a as s,b as u,c as a,d as p}from"./chunk-A5CDJL6G.mjs";import{c as e,l as t,m as o,p as r}from"./chunk-3OA4S6UT.mjs";import"./chunk-MGJZTOEM.mjs";export{u as useAuth,o as useAutoGenerate,p as useCrudifyWithNotifications,a as useData,r as useFileUpload,e as useSession,s as useUserData,t as useUserProfile};
package/dist/index.d.mts CHANGED
@@ -10,7 +10,7 @@ import * as react_jsx_runtime from 'react/jsx-runtime';
10
10
  import { ThemeOptions } from '@mui/material';
11
11
  export { A as AutoGenerateConfig, G as GlobalNotificationProvider, a as GlobalNotificationProviderProps, N as Notification, b as NotificationSeverity, d as UseAutoGenerateOptions, U as UseAutoGenerateReturn, c as useAutoGenerate, u as useGlobalNotification } from './GlobalNotificationProvider-Zq18OkpI.mjs';
12
12
  export { E as ERROR_CODES, j as ERROR_SEVERITY_MAP, n as ErrorCode, o as ErrorSeverity, q as ErrorTranslationConfig, P as ParsedError, m as createErrorTranslator, d as decodeJwtSafely, a as getCookie, g as getCurrentUserEmail, f as getErrorMessage, h as handleCrudifyError, i as isTokenExpired, p as parseApiError, e as parseJavaScriptError, c as parseTransactionError, b as secureLocalStorage, s as secureSessionStorage, l as translateError, t as translateErrorCode, k as translateErrorCodes } from './errorTranslation-qwwQTvCO.mjs';
13
- import { ApiResponse, IModule, ModuleCreateInput, ModuleEditInput, ActionListFilters, IAction, ActionCreateInput, ActionEditInput, UpdateActionsProfilesInput, UpdateActionsProfilesResponse } from '@nocios/crudify-admin';
13
+ import { ApiResponse, IModule, ModuleCreateInput, ModuleEditInput, ActionListFilters, IAction, ActionCreateInput, ActionEditInput, UpdateActionsProfilesInput, UpdateActionsProfilesResponse, CalculatePermissionsInput, CalculatePermissionsResponse } from '@nocios/crudify-admin';
14
14
  export { ActionCreateInput, ActionEditInput, ActionListFilters, ApiResponse, IAction, IModule, ModuleCreateInput, ModuleEditInput, UpdateActionsProfilesInput, UpdateActionsProfilesResponse } from '@nocios/crudify-admin';
15
15
 
16
16
  interface CrudifyContextValue {
@@ -1024,6 +1024,7 @@ declare const crudifyAdmin: {
1024
1024
  getActionVersions: (actionKey: string) => Promise<ApiResponse<any[]>>;
1025
1025
  getActionsByProfile: (profileId: string) => Promise<ApiResponse<IAction[]>>;
1026
1026
  updateActionsProfiles: (data: UpdateActionsProfilesInput) => Promise<ApiResponse<UpdateActionsProfilesResponse>>;
1027
+ calculatePermissions: (data: CalculatePermissionsInput) => Promise<ApiResponse<CalculatePermissionsResponse>>;
1027
1028
  };
1028
1029
 
1029
1030
  export { AuthRoute, type AuthRouteProps, CRITICAL_TRANSLATIONS, type CriticalTranslationKey, CrudifyInitializationManager, CrudifyInitializer, type CrudifyInitializerConfig, type CrudifyInitializerProps, CrudifyLoginConfig, CrudifyProvider, CrudifyThemeProvider, type CrudifyThemeProviderProps, type FetchTranslationsOptions, type InitializationPriority, type InitializationRequest, type InitializationStatus, type LogContext, type LogLevel, ProtectedRoute, type ProtectedRouteProps, SessionLoadingScreen, type SessionLoadingScreenProps, type SupportedLanguage, type TranslationResponse, TranslationService, type TranslationsContextValue, TranslationsProvider, type TranslationsProviderProps, crudifyAdmin, crudifyInitManager, extractSafeRedirectFromUrl, getCriticalLanguages, getCriticalTranslations, logger, translationService, useCrudify, useCrudifyInitializer, useTranslations, validateInternalRedirect };
package/dist/index.d.ts CHANGED
@@ -10,7 +10,7 @@ import * as react_jsx_runtime from 'react/jsx-runtime';
10
10
  import { ThemeOptions } from '@mui/material';
11
11
  export { A as AutoGenerateConfig, G as GlobalNotificationProvider, a as GlobalNotificationProviderProps, N as Notification, b as NotificationSeverity, d as UseAutoGenerateOptions, U as UseAutoGenerateReturn, c as useAutoGenerate, u as useGlobalNotification } from './GlobalNotificationProvider-Zq18OkpI.js';
12
12
  export { E as ERROR_CODES, j as ERROR_SEVERITY_MAP, n as ErrorCode, o as ErrorSeverity, q as ErrorTranslationConfig, P as ParsedError, m as createErrorTranslator, d as decodeJwtSafely, a as getCookie, g as getCurrentUserEmail, f as getErrorMessage, h as handleCrudifyError, i as isTokenExpired, p as parseApiError, e as parseJavaScriptError, c as parseTransactionError, b as secureLocalStorage, s as secureSessionStorage, l as translateError, t as translateErrorCode, k as translateErrorCodes } from './errorTranslation-DGdrMidg.js';
13
- import { ApiResponse, IModule, ModuleCreateInput, ModuleEditInput, ActionListFilters, IAction, ActionCreateInput, ActionEditInput, UpdateActionsProfilesInput, UpdateActionsProfilesResponse } from '@nocios/crudify-admin';
13
+ import { ApiResponse, IModule, ModuleCreateInput, ModuleEditInput, ActionListFilters, IAction, ActionCreateInput, ActionEditInput, UpdateActionsProfilesInput, UpdateActionsProfilesResponse, CalculatePermissionsInput, CalculatePermissionsResponse } from '@nocios/crudify-admin';
14
14
  export { ActionCreateInput, ActionEditInput, ActionListFilters, ApiResponse, IAction, IModule, ModuleCreateInput, ModuleEditInput, UpdateActionsProfilesInput, UpdateActionsProfilesResponse } from '@nocios/crudify-admin';
15
15
 
16
16
  interface CrudifyContextValue {
@@ -1024,6 +1024,7 @@ declare const crudifyAdmin: {
1024
1024
  getActionVersions: (actionKey: string) => Promise<ApiResponse<any[]>>;
1025
1025
  getActionsByProfile: (profileId: string) => Promise<ApiResponse<IAction[]>>;
1026
1026
  updateActionsProfiles: (data: UpdateActionsProfilesInput) => Promise<ApiResponse<UpdateActionsProfilesResponse>>;
1027
+ calculatePermissions: (data: CalculatePermissionsInput) => Promise<ApiResponse<CalculatePermissionsResponse>>;
1027
1028
  };
1028
1029
 
1029
1030
  export { AuthRoute, type AuthRouteProps, CRITICAL_TRANSLATIONS, type CriticalTranslationKey, CrudifyInitializationManager, CrudifyInitializer, type CrudifyInitializerConfig, type CrudifyInitializerProps, CrudifyLoginConfig, CrudifyProvider, CrudifyThemeProvider, type CrudifyThemeProviderProps, type FetchTranslationsOptions, type InitializationPriority, type InitializationRequest, type InitializationStatus, type LogContext, type LogLevel, ProtectedRoute, type ProtectedRouteProps, SessionLoadingScreen, type SessionLoadingScreenProps, type SupportedLanguage, type TranslationResponse, TranslationService, type TranslationsContextValue, TranslationsProvider, type TranslationsProviderProps, crudifyAdmin, crudifyInitManager, extractSafeRedirectFromUrl, getCriticalLanguages, getCriticalTranslations, logger, translationService, useCrudify, useCrudifyInitializer, useTranslations, validateInternalRedirect };
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _createStarExport(obj) { Object.keys(obj) .filter((key) => key !== "default" && key !== "__esModule") .forEach((key) => { if (exports.hasOwnProperty(key)) { return; } Object.defineProperty(exports, key, {enumerable: true, configurable: true, get: () => obj[key]}); }); } 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; } async function _asyncOptionalChain(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 = await fn(value); } else if (op === 'call' || op === 'optionalCall') { value = await fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }var _chunk5VOTRIDBjs = require('./chunk-5VOTRIDB.js');var _chunkLVSNJ4OMjs = require('./chunk-LVSNJ4OM.js');var _chunk3XZ3TEKQjs = require('./chunk-3XZ3TEKQ.js');var _chunkKQ2XC5PNjs = require('./chunk-KQ2XC5PN.js');var _chunkNSV6ECYOjs = require('./chunk-NSV6ECYO.js');var _chunkNXTXGTU6js = require('./chunk-NXTXGTU6.js');var _crudifybrowser = require('@nocios/crudify-browser'); var _crudifybrowser2 = _interopRequireDefault(_crudifybrowser); _createStarExport(_crudifybrowser);var _react = require('react');var _material = require('@mui/material');var _jsxruntime = require('react/jsx-runtime');var Ve=(e={})=>{try{let r=_chunkNXTXGTU6js.b.call(void 0, "theme");if(r){let o=JSON.parse(decodeURIComponent(r));return{...e,...o}}}catch(r){_chunkNXTXGTU6js.a.warn("Error parsing theme from cookie",r instanceof Error?{errorMessage:r.message}:{message:String(r)})}return e};function _e({children:e,defaultTheme:r={},disableCssBaseline:o=!1}){let t=_react.useMemo.call(void 0, ()=>{let s=Ve(r);return _material.createTheme.call(void 0, s)},[r]);return _jsxruntime.jsxs.call(void 0, _material.ThemeProvider,{theme:t,children:[!o&&_jsxruntime.jsx.call(void 0, _material.CssBaseline,{}),e]})}var _reactrouterdom = require('react-router-dom');var qe={border:"5px solid rgba(0, 0, 0, 0.1)",borderTopColor:"#3B82F6",borderRadius:"50%",width:"50px",height:"50px",animation:"spin 1s linear infinite"},We=()=>_jsxruntime.jsx.call(void 0, "style",{children:`
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _createStarExport(obj) { Object.keys(obj) .filter((key) => key !== "default" && key !== "__esModule") .forEach((key) => { if (exports.hasOwnProperty(key)) { return; } Object.defineProperty(exports, key, {enumerable: true, configurable: true, get: () => obj[key]}); }); } 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; } async function _asyncOptionalChain(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 = await fn(value); } else if (op === 'call' || op === 'optionalCall') { value = await fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }var _chunkPYLSSR7Wjs = require('./chunk-PYLSSR7W.js');var _chunkQ4RHNYTIjs = require('./chunk-Q4RHNYTI.js');var _chunkSFIIFYMZjs = require('./chunk-SFIIFYMZ.js');var _chunk5HFI5CZ5js = require('./chunk-5HFI5CZ5.js');var _chunkNSV6ECYOjs = require('./chunk-NSV6ECYO.js');var _chunkMFYHD6S5js = require('./chunk-MFYHD6S5.js');var _crudifybrowser = require('@nocios/crudify-browser'); var _crudifybrowser2 = _interopRequireDefault(_crudifybrowser); _createStarExport(_crudifybrowser);var _react = require('react');var _material = require('@mui/material');var _jsxruntime = require('react/jsx-runtime');var Ve=(e={})=>{try{let r=_chunkMFYHD6S5js.b.call(void 0, "theme");if(r){let o=JSON.parse(decodeURIComponent(r));return{...e,...o}}}catch(r){_chunkMFYHD6S5js.a.warn("Error parsing theme from cookie",r instanceof Error?{errorMessage:r.message}:{message:String(r)})}return e};function _e({children:e,defaultTheme:r={},disableCssBaseline:o=!1}){let t=_react.useMemo.call(void 0, ()=>{let s=Ve(r);return _material.createTheme.call(void 0, s)},[r]);return _jsxruntime.jsxs.call(void 0, _material.ThemeProvider,{theme:t,children:[!o&&_jsxruntime.jsx.call(void 0, _material.CssBaseline,{}),e]})}var _reactrouterdom = require('react-router-dom');var qe={border:"5px solid rgba(0, 0, 0, 0.1)",borderTopColor:"#3B82F6",borderRadius:"50%",width:"50px",height:"50px",animation:"spin 1s linear infinite"},We=()=>_jsxruntime.jsx.call(void 0, "style",{children:`
2
2
  @keyframes spin {
3
3
  0% { transform: rotate(0deg); }
4
4
  100% { transform: rotate(360deg); }
5
5
  }
6
- `});function k({stage:e="loading",message:r}){let t=r||{initializing:"Initializing application...","validating-session":"Validating session...",loading:"Loading..."}[e];return _jsxruntime.jsxs.call(void 0, _jsxruntime.Fragment,{children:[_jsxruntime.jsx.call(void 0, We,{}),_jsxruntime.jsxs.call(void 0, "div",{style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",height:"100vh",width:"100vw",backgroundColor:"#f0f2f5",fontFamily:'"Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif',color:"#333",textAlign:"center",boxSizing:"border-box",padding:"20px",background:"#fff"},children:[_jsxruntime.jsx.call(void 0, "div",{style:qe}),_jsxruntime.jsx.call(void 0, "p",{style:{fontSize:"1.25em",fontWeight:"500",marginTop:"24px",color:"#1f2937"},children:t})]})]})}var $e=/^[a-zA-Z0-9\-_./\?=&%#]+$/,Ye=[/^https?:\/\//i,/^ftp:\/\//i,/^\/\//,/javascript:/i,/data:/i,/vbscript:/i,/about:/i,/\.\.\//,/\.\.\\/,/%2e%2e%2f/i,/%2e%2e%5c/i,/%2f%2f/i,/%5c%5c/i,/[\x00-\x1f\x7f-\x9f]/,/\\/],S= exports.validateInternalRedirect =(e,r="/")=>{if(!e||typeof e!="string")return r;let o=e.trim();if(!o)return r;if(!o.startsWith("/"))return _chunkNXTXGTU6js.a.warn("Open redirect blocked (relative path)",{path:e}),r;if(!$e.test(o))return _chunkNXTXGTU6js.a.warn("Open redirect blocked (invalid characters)",{path:e}),r;let t=o.toLowerCase();for(let a of Ye)if(a.test(t))return _chunkNXTXGTU6js.a.warn("Open redirect blocked (dangerous pattern)",{path:e}),r;let s=o.split("?")[0].split("/").filter(Boolean);if(s.length===0)return o;for(let a of s)if(a===".."||a.includes(":")||a.length>100)return _chunkNXTXGTU6js.a.warn("Open redirect blocked (suspicious path part)",{part:a}),r;return o},E= exports.extractSafeRedirectFromUrl =(e,r="/")=>{try{let t=(typeof e=="string"?new URLSearchParams(e):e).get("redirect");if(!t)return r;let s=decodeURIComponent(t);return S(s,r)}catch(o){return _chunkNXTXGTU6js.a.warn("Error parsing redirect parameter",o instanceof Error?{errorMessage:o.message}:{message:String(o)}),r}};function U({children:e,loadingComponent:r,loginPath:o="/login"}){let{isAuthenticated:t,isLoading:s,isInitialized:a,tokens:c,error:A}=_chunk3XZ3TEKQjs.j.call(void 0, ),l=_reactrouterdom.useLocation.call(void 0, );if(!a||s)return _jsxruntime.jsx.call(void 0, _jsxruntime.Fragment,{children:r||_jsxruntime.jsx.call(void 0, k,{stage:"validating-session"})});let u=t&&_optionalChain([c, 'optionalAccess', _2 => _2.accessToken])&&c.accessToken.length>0;if(A||!t||!u){c&&(!c.accessToken||c.accessToken.length===0)&&localStorage.removeItem("crudify_tokens");let x=l.pathname+l.search,C=S(x),R=encodeURIComponent(C);return _jsxruntime.jsx.call(void 0, _reactrouterdom.Navigate,{to:`${o}?redirect=${R}`,replace:!0})}return _jsxruntime.jsx.call(void 0, _jsxruntime.Fragment,{children:e})}function O({children:e,redirectTo:r="/"}){let{isAuthenticated:o}=_chunk3XZ3TEKQjs.j.call(void 0, ),t=_reactrouterdom.useLocation.call(void 0, );if(o){let s=new URLSearchParams(t.search),a=E(s,r);return _jsxruntime.jsx.call(void 0, _reactrouterdom.Navigate,{to:a,replace:!0})}return _jsxruntime.jsx.call(void 0, _jsxruntime.Fragment,{children:e})}var G=_react.createContext.call(void 0, void 0),ir= exports.CrudifyInitializer =({config:e,children:r,fallback:o=null,onInitialized:t,onError:s})=>{let[a,c]=_react.useState.call(void 0, !1),[A,l]=_react.useState.call(void 0, !1),[u,x]=_react.useState.call(void 0, null),C=_react.useRef.call(void 0, !1),R=_react.useRef.call(void 0, !1);_react.useEffect.call(void 0, ()=>{C.current||(_chunk3XZ3TEKQjs.o.registerHighPriorityInitializer(),C.current=!0),R.current||(R.current=!0,(async()=>{l(!0),x(null);try{let d=_chunkNXTXGTU6js.c.call(void 0, {publicApiKey:_optionalChain([e, 'optionalAccess', _3 => _3.publicApiKey]),env:_optionalChain([e, 'optionalAccess', _4 => _4.env]),enableDebug:_optionalChain([e, 'optionalAccess', _5 => _5.enableLogging])});if(!d.publicApiKey)throw new Error("Crudify configuration missing. Please provide publicApiKey via props or ensure cookies are set by Lambda.");let I=d.env||"prod";_chunkNXTXGTU6js.a.setEnvironment(I),await _chunk3XZ3TEKQjs.o.initialize({priority:"HIGH",publicApiKey:d.publicApiKey,env:d.env||"prod",enableLogging:_optionalChain([e, 'optionalAccess', _6 => _6.enableLogging]),requestedBy:"CrudifyInitializer"}),c(!0),l(!1),t&&t()}catch(d){let I=d instanceof Error?d:new Error(String(d));x(I),l(!1),s&&s(I)}})())},[_optionalChain([e, 'optionalAccess', _7 => _7.publicApiKey]),_optionalChain([e, 'optionalAccess', _8 => _8.env]),_optionalChain([e, 'optionalAccess', _9 => _9.enableLogging]),t,s]);let V={isInitialized:a,isInitializing:A,error:u};return A&&o?_jsxruntime.jsx.call(void 0, _jsxruntime.Fragment,{children:o}):(u&&_chunkNXTXGTU6js.a.error("[CrudifyInitializer] Initialization failed",u),_jsxruntime.jsx.call(void 0, G.Provider,{value:V,children:r}))},nr= exports.useCrudifyInitializer =()=>{let e=_react.useContext.call(void 0, G);if(!e)throw new Error("useCrudifyInitializer must be used within CrudifyInitializer");return e};var _crudifyadmin = require('@nocios/crudify-admin'); var _crudifyadmin2 = _interopRequireDefault(_crudifyadmin);var K=!1,g=null,y=null;async function ar(){let r=await _chunk3XZ3TEKQjs.b.getInstance().getTokenInfo(),o=_optionalChain([r, 'optionalAccess', _10 => _10.apiEndpointAdmin]),t=_optionalChain([r, 'optionalAccess', _11 => _11.apiKeyEndpointAdmin]);return o&&t?{apiUrl:o,apiKey:t}:_chunk3XZ3TEKQjs.f.waitForCredentials()}async function pr(){if(!K)return g||(g=(async()=>{try{let e=_chunk3XZ3TEKQjs.b.getInstance(),{apiUrl:r,apiKey:o}=await ar();y=await _asyncOptionalChain([(await e.getTokenInfo()), 'optionalAccess', async _12 => _12.crudifyTokens, 'optionalAccess', async _13 => _13.accessToken])||null,_crudifyadmin2.default.init({url:r,apiKey:o,getAdditionalHeaders:()=>y?{Authorization:`Bearer ${y}`}:{}}),K=!0}catch(e){throw g=null,_chunkNXTXGTU6js.a.error("[crudifyAdminWrapper] Initialization failed",e instanceof Error?e:{message:String(e)}),e}})(),g)}async function n(e){try{await pr();let r=_chunk3XZ3TEKQjs.b.getInstance();y=await _asyncOptionalChain([(await r.getTokenInfo()), 'optionalAccess', async _14 => _14.crudifyTokens, 'optionalAccess', async _15 => _15.accessToken])||null;let t=await e(),s=t.errors&&(typeof t.errors=="string"&&t.errors.includes("401")||Array.isArray(t.errors)&&t.errors.some(a=>typeof a=="string"&&a.includes("401")));return!t.success&&s?await r.refreshTokens()?(y=await _asyncOptionalChain([(await r.getTokenInfo()), 'optionalAccess', async _16 => _16.crudifyTokens, 'optionalAccess', async _17 => _17.accessToken])||null,await e()):(_chunkNXTXGTU6js.a.error("[crudifyAdmin] Token refresh failed"),typeof window<"u"&&(window.location.href="/login"),t):t}catch(r){return _chunkNXTXGTU6js.a.error("[crudifyAdmin] Operation error",r instanceof Error?r:{message:String(r)}),{success:!1,errors:r instanceof Error?r.message:"Unknown error"}}}var cr={listModules:()=>n(()=>_crudifyadmin2.default.listModules()),getModule:e=>n(()=>_crudifyadmin2.default.getModule(e)),createModule:e=>n(()=>_crudifyadmin2.default.createModule(e)),editModule:(e,r)=>n(()=>_crudifyadmin2.default.editModule(e,r)),deleteModule:e=>n(()=>_crudifyadmin2.default.deleteModule(e)),activateModule:e=>n(()=>_crudifyadmin2.default.activateModule(e)),deactivateModule:e=>n(()=>_crudifyadmin2.default.deactivateModule(e)),getModuleVersions:e=>n(()=>_crudifyadmin2.default.getModuleVersions(e)),listActions:e=>n(()=>_crudifyadmin2.default.listActions(e)),getAction:e=>n(()=>_crudifyadmin2.default.getAction(e)),createAction:e=>n(()=>_crudifyadmin2.default.createAction(e)),editAction:(e,r)=>n(()=>_crudifyadmin2.default.editAction(e,r)),deleteAction:e=>n(()=>_crudifyadmin2.default.deleteAction(e)),activateAction:e=>n(()=>_crudifyadmin2.default.activateAction(e)),deactivateAction:e=>n(()=>_crudifyadmin2.default.deactivateAction(e)),getActionVersions:e=>n(()=>_crudifyadmin2.default.getActionVersions(e)),getActionsByProfile:e=>n(()=>_crudifyadmin2.default.getActionsByProfile(e)),updateActionsProfiles:e=>n(()=>_crudifyadmin2.default.updateActionsProfiles(e))};exports.AuthRoute = O; exports.CRITICAL_TRANSLATIONS = _chunk5VOTRIDBjs.a; exports.CrudiaAutoGenerate = _chunk5VOTRIDBjs.o; exports.CrudiaFileField = _chunk5VOTRIDBjs.p; exports.CrudiaMarkdownField = _chunk5VOTRIDBjs.q; exports.CrudifyInitializationManager = _chunk3XZ3TEKQjs.n; exports.CrudifyInitializer = ir; exports.CrudifyLogin = _chunk5VOTRIDBjs.h; exports.CrudifyProvider = _chunk3XZ3TEKQjs.g; exports.CrudifyThemeProvider = _e; exports.ERROR_CODES = _chunkNSV6ECYOjs.a; exports.ERROR_SEVERITY_MAP = _chunkNSV6ECYOjs.b; exports.GlobalNotificationProvider = _chunk3XZ3TEKQjs.d; exports.LoginComponent = _chunk5VOTRIDBjs.m; exports.POLICY_ACTIONS = _chunk5VOTRIDBjs.j; exports.PREFERRED_POLICY_ORDER = _chunk5VOTRIDBjs.k; exports.Policies = _chunk5VOTRIDBjs.l; exports.ProtectedRoute = U; exports.SessionDebugInfo = _chunk3XZ3TEKQjs.k; exports.SessionLoadingScreen = k; exports.SessionManager = _chunk3XZ3TEKQjs.b; exports.SessionProvider = _chunk3XZ3TEKQjs.i; exports.SessionStatus = _chunk5VOTRIDBjs.n; exports.TokenStorage = _chunk3XZ3TEKQjs.a; exports.TranslationService = _chunk5VOTRIDBjs.d; exports.TranslationsProvider = _chunk5VOTRIDBjs.f; exports.UserProfileDisplay = _chunk5VOTRIDBjs.i; exports.createErrorTranslator = _chunkNXTXGTU6js.n; exports.crudify = _crudifybrowser2.default; exports.crudifyAdmin = cr; exports.crudifyInitManager = _chunk3XZ3TEKQjs.o; exports.decodeJwtSafely = _chunkNXTXGTU6js.q; exports.extractSafeRedirectFromUrl = E; exports.getCookie = _chunkNXTXGTU6js.b; exports.getCriticalLanguages = _chunk5VOTRIDBjs.b; exports.getCriticalTranslations = _chunk5VOTRIDBjs.c; exports.getCurrentUserEmail = _chunkNXTXGTU6js.r; exports.getErrorMessage = _chunkNSV6ECYOjs.e; exports.handleCrudifyError = _chunkNSV6ECYOjs.g; exports.isTokenExpired = _chunkNXTXGTU6js.s; exports.logger = _chunkNXTXGTU6js.a; exports.parseApiError = _chunkNSV6ECYOjs.c; exports.parseJavaScriptError = _chunkNSV6ECYOjs.f; exports.parseTransactionError = _chunkNSV6ECYOjs.d; exports.secureLocalStorage = _chunkKQ2XC5PNjs.b; exports.secureSessionStorage = _chunkKQ2XC5PNjs.a; exports.translateError = _chunkNXTXGTU6js.m; exports.translateErrorCode = _chunkNXTXGTU6js.k; exports.translateErrorCodes = _chunkNXTXGTU6js.l; exports.translationService = _chunk5VOTRIDBjs.e; exports.useAuth = _chunkLVSNJ4OMjs.b; exports.useAutoGenerate = _chunk3XZ3TEKQjs.m; exports.useCrudify = _chunk3XZ3TEKQjs.h; exports.useCrudifyInitializer = nr; exports.useCrudifyWithNotifications = _chunkLVSNJ4OMjs.d; exports.useData = _chunkLVSNJ4OMjs.c; exports.useFileUpload = _chunk3XZ3TEKQjs.p; exports.useGlobalNotification = _chunk3XZ3TEKQjs.e; exports.useSession = _chunk3XZ3TEKQjs.c; exports.useSessionContext = _chunk3XZ3TEKQjs.j; exports.useTranslations = _chunk5VOTRIDBjs.g; exports.useUserData = _chunkLVSNJ4OMjs.a; exports.useUserProfile = _chunk3XZ3TEKQjs.l; exports.validateInternalRedirect = S;
6
+ `});function k({stage:e="loading",message:r}){let t=r||{initializing:"Initializing application...","validating-session":"Validating session...",loading:"Loading..."}[e];return _jsxruntime.jsxs.call(void 0, _jsxruntime.Fragment,{children:[_jsxruntime.jsx.call(void 0, We,{}),_jsxruntime.jsxs.call(void 0, "div",{style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",height:"100vh",width:"100vw",backgroundColor:"#f0f2f5",fontFamily:'"Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif',color:"#333",textAlign:"center",boxSizing:"border-box",padding:"20px",background:"#fff"},children:[_jsxruntime.jsx.call(void 0, "div",{style:qe}),_jsxruntime.jsx.call(void 0, "p",{style:{fontSize:"1.25em",fontWeight:"500",marginTop:"24px",color:"#1f2937"},children:t})]})]})}var $e=/^[a-zA-Z0-9\-_./\?=&%#]+$/,Ye=[/^https?:\/\//i,/^ftp:\/\//i,/^\/\//,/javascript:/i,/data:/i,/vbscript:/i,/about:/i,/\.\.\//,/\.\.\\/,/%2e%2e%2f/i,/%2e%2e%5c/i,/%2f%2f/i,/%5c%5c/i,/[\x00-\x1f\x7f-\x9f]/,/\\/],S= exports.validateInternalRedirect =(e,r="/")=>{if(!e||typeof e!="string")return r;let o=e.trim();if(!o)return r;if(!o.startsWith("/"))return _chunkMFYHD6S5js.a.warn("Open redirect blocked (relative path)",{path:e}),r;if(!$e.test(o))return _chunkMFYHD6S5js.a.warn("Open redirect blocked (invalid characters)",{path:e}),r;let t=o.toLowerCase();for(let a of Ye)if(a.test(t))return _chunkMFYHD6S5js.a.warn("Open redirect blocked (dangerous pattern)",{path:e}),r;let s=o.split("?")[0].split("/").filter(Boolean);if(s.length===0)return o;for(let a of s)if(a===".."||a.includes(":")||a.length>100)return _chunkMFYHD6S5js.a.warn("Open redirect blocked (suspicious path part)",{part:a}),r;return o},E= exports.extractSafeRedirectFromUrl =(e,r="/")=>{try{let t=(typeof e=="string"?new URLSearchParams(e):e).get("redirect");if(!t)return r;let s=decodeURIComponent(t);return S(s,r)}catch(o){return _chunkMFYHD6S5js.a.warn("Error parsing redirect parameter",o instanceof Error?{errorMessage:o.message}:{message:String(o)}),r}};function U({children:e,loadingComponent:r,loginPath:o="/login"}){let{isAuthenticated:t,isLoading:s,isInitialized:a,tokens:c,error:A}=_chunkSFIIFYMZjs.j.call(void 0, ),u=_reactrouterdom.useLocation.call(void 0, );if(!a||s)return _jsxruntime.jsx.call(void 0, _jsxruntime.Fragment,{children:r||_jsxruntime.jsx.call(void 0, k,{stage:"validating-session"})});let d=t&&_optionalChain([c, 'optionalAccess', _2 => _2.accessToken])&&c.accessToken.length>0;if(A||!t||!d){c&&(!c.accessToken||c.accessToken.length===0)&&localStorage.removeItem("crudify_tokens");let x=u.pathname+u.search,C=S(x),P=encodeURIComponent(C);return _jsxruntime.jsx.call(void 0, _reactrouterdom.Navigate,{to:`${o}?redirect=${P}`,replace:!0})}return _jsxruntime.jsx.call(void 0, _jsxruntime.Fragment,{children:e})}function O({children:e,redirectTo:r="/"}){let{isAuthenticated:o}=_chunkSFIIFYMZjs.j.call(void 0, ),t=_reactrouterdom.useLocation.call(void 0, );if(o){let s=new URLSearchParams(t.search),a=E(s,r);return _jsxruntime.jsx.call(void 0, _reactrouterdom.Navigate,{to:a,replace:!0})}return _jsxruntime.jsx.call(void 0, _jsxruntime.Fragment,{children:e})}var G=_react.createContext.call(void 0, void 0),ir= exports.CrudifyInitializer =({config:e,children:r,fallback:o=null,onInitialized:t,onError:s})=>{let[a,c]=_react.useState.call(void 0, !1),[A,u]=_react.useState.call(void 0, !1),[d,x]=_react.useState.call(void 0, null),C=_react.useRef.call(void 0, !1),P=_react.useRef.call(void 0, !1);_react.useEffect.call(void 0, ()=>{C.current||(_chunkSFIIFYMZjs.o.registerHighPriorityInitializer(),C.current=!0),P.current||(P.current=!0,(async()=>{u(!0),x(null);try{let l=_chunkMFYHD6S5js.c.call(void 0, {publicApiKey:_optionalChain([e, 'optionalAccess', _3 => _3.publicApiKey]),env:_optionalChain([e, 'optionalAccess', _4 => _4.env]),enableDebug:_optionalChain([e, 'optionalAccess', _5 => _5.enableLogging])});if(!l.publicApiKey)throw new Error("Crudify configuration missing. Please provide publicApiKey via props or ensure cookies are set by Lambda.");let R=l.env||"prod";_chunkMFYHD6S5js.a.setEnvironment(R),await _chunkSFIIFYMZjs.o.initialize({priority:"HIGH",publicApiKey:l.publicApiKey,env:l.env||"prod",enableLogging:_optionalChain([e, 'optionalAccess', _6 => _6.enableLogging]),requestedBy:"CrudifyInitializer"}),c(!0),u(!1),t&&t()}catch(l){let R=l instanceof Error?l:new Error(String(l));x(R),u(!1),s&&s(R)}})())},[_optionalChain([e, 'optionalAccess', _7 => _7.publicApiKey]),_optionalChain([e, 'optionalAccess', _8 => _8.env]),_optionalChain([e, 'optionalAccess', _9 => _9.enableLogging]),t,s]);let V={isInitialized:a,isInitializing:A,error:d};return A&&o?_jsxruntime.jsx.call(void 0, _jsxruntime.Fragment,{children:o}):(d&&_chunkMFYHD6S5js.a.error("[CrudifyInitializer] Initialization failed",d),_jsxruntime.jsx.call(void 0, G.Provider,{value:V,children:r}))},nr= exports.useCrudifyInitializer =()=>{let e=_react.useContext.call(void 0, G);if(!e)throw new Error("useCrudifyInitializer must be used within CrudifyInitializer");return e};var _crudifyadmin = require('@nocios/crudify-admin'); var _crudifyadmin2 = _interopRequireDefault(_crudifyadmin);var K=!1,g=null,y=null;async function ar(){let r=await _chunkSFIIFYMZjs.b.getInstance().getTokenInfo(),o=_optionalChain([r, 'optionalAccess', _10 => _10.apiEndpointAdmin]),t=_optionalChain([r, 'optionalAccess', _11 => _11.apiKeyEndpointAdmin]);return o&&t?{apiUrl:o,apiKey:t}:_chunkSFIIFYMZjs.f.waitForCredentials()}async function pr(){if(!K)return g||(g=(async()=>{try{let e=_chunkSFIIFYMZjs.b.getInstance(),{apiUrl:r,apiKey:o}=await ar();y=await _asyncOptionalChain([(await e.getTokenInfo()), 'optionalAccess', async _12 => _12.crudifyTokens, 'optionalAccess', async _13 => _13.accessToken])||null,_crudifyadmin2.default.init({url:r,apiKey:o,getAdditionalHeaders:()=>y?{Authorization:`Bearer ${y}`}:{}}),K=!0}catch(e){throw g=null,_chunkMFYHD6S5js.a.error("[crudifyAdminWrapper] Initialization failed",e instanceof Error?e:{message:String(e)}),e}})(),g)}async function n(e){try{await pr();let r=_chunkSFIIFYMZjs.b.getInstance();y=await _asyncOptionalChain([(await r.getTokenInfo()), 'optionalAccess', async _14 => _14.crudifyTokens, 'optionalAccess', async _15 => _15.accessToken])||null;let t=await e(),s=t.errors&&(typeof t.errors=="string"&&t.errors.includes("401")||Array.isArray(t.errors)&&t.errors.some(a=>typeof a=="string"&&a.includes("401")));return!t.success&&s?await r.refreshTokens()?(y=await _asyncOptionalChain([(await r.getTokenInfo()), 'optionalAccess', async _16 => _16.crudifyTokens, 'optionalAccess', async _17 => _17.accessToken])||null,await e()):(_chunkMFYHD6S5js.a.error("[crudifyAdmin] Token refresh failed"),typeof window<"u"&&(window.location.href="/login"),t):t}catch(r){return _chunkMFYHD6S5js.a.error("[crudifyAdmin] Operation error",r instanceof Error?r:{message:String(r)}),{success:!1,errors:r instanceof Error?r.message:"Unknown error"}}}var cr={listModules:()=>n(()=>_crudifyadmin2.default.listModules()),getModule:e=>n(()=>_crudifyadmin2.default.getModule(e)),createModule:e=>n(()=>_crudifyadmin2.default.createModule(e)),editModule:(e,r)=>n(()=>_crudifyadmin2.default.editModule(e,r)),deleteModule:e=>n(()=>_crudifyadmin2.default.deleteModule(e)),activateModule:e=>n(()=>_crudifyadmin2.default.activateModule(e)),deactivateModule:e=>n(()=>_crudifyadmin2.default.deactivateModule(e)),getModuleVersions:e=>n(()=>_crudifyadmin2.default.getModuleVersions(e)),listActions:e=>n(()=>_crudifyadmin2.default.listActions(e)),getAction:e=>n(()=>_crudifyadmin2.default.getAction(e)),createAction:e=>n(()=>_crudifyadmin2.default.createAction(e)),editAction:(e,r)=>n(()=>_crudifyadmin2.default.editAction(e,r)),deleteAction:e=>n(()=>_crudifyadmin2.default.deleteAction(e)),activateAction:e=>n(()=>_crudifyadmin2.default.activateAction(e)),deactivateAction:e=>n(()=>_crudifyadmin2.default.deactivateAction(e)),getActionVersions:e=>n(()=>_crudifyadmin2.default.getActionVersions(e)),getActionsByProfile:e=>n(()=>_crudifyadmin2.default.getActionsByProfile(e)),updateActionsProfiles:e=>n(()=>_crudifyadmin2.default.updateActionsProfiles(e)),calculatePermissions:e=>n(()=>_crudifyadmin2.default.calculatePermissions(e))};exports.AuthRoute = O; exports.CRITICAL_TRANSLATIONS = _chunkPYLSSR7Wjs.a; exports.CrudiaAutoGenerate = _chunkPYLSSR7Wjs.o; exports.CrudiaFileField = _chunkPYLSSR7Wjs.p; exports.CrudiaMarkdownField = _chunkPYLSSR7Wjs.q; exports.CrudifyInitializationManager = _chunkSFIIFYMZjs.n; exports.CrudifyInitializer = ir; exports.CrudifyLogin = _chunkPYLSSR7Wjs.h; exports.CrudifyProvider = _chunkSFIIFYMZjs.g; exports.CrudifyThemeProvider = _e; exports.ERROR_CODES = _chunkNSV6ECYOjs.a; exports.ERROR_SEVERITY_MAP = _chunkNSV6ECYOjs.b; exports.GlobalNotificationProvider = _chunkSFIIFYMZjs.d; exports.LoginComponent = _chunkPYLSSR7Wjs.m; exports.POLICY_ACTIONS = _chunkPYLSSR7Wjs.j; exports.PREFERRED_POLICY_ORDER = _chunkPYLSSR7Wjs.k; exports.Policies = _chunkPYLSSR7Wjs.l; exports.ProtectedRoute = U; exports.SessionDebugInfo = _chunkSFIIFYMZjs.k; exports.SessionLoadingScreen = k; exports.SessionManager = _chunkSFIIFYMZjs.b; exports.SessionProvider = _chunkSFIIFYMZjs.i; exports.SessionStatus = _chunkPYLSSR7Wjs.n; exports.TokenStorage = _chunkSFIIFYMZjs.a; exports.TranslationService = _chunkPYLSSR7Wjs.d; exports.TranslationsProvider = _chunkPYLSSR7Wjs.f; exports.UserProfileDisplay = _chunkPYLSSR7Wjs.i; exports.createErrorTranslator = _chunkMFYHD6S5js.o; exports.crudify = _crudifybrowser2.default; exports.crudifyAdmin = cr; exports.crudifyInitManager = _chunkSFIIFYMZjs.o; exports.decodeJwtSafely = _chunkMFYHD6S5js.q; exports.extractSafeRedirectFromUrl = E; exports.getCookie = _chunkMFYHD6S5js.b; exports.getCriticalLanguages = _chunkPYLSSR7Wjs.b; exports.getCriticalTranslations = _chunkPYLSSR7Wjs.c; exports.getCurrentUserEmail = _chunkMFYHD6S5js.r; exports.getErrorMessage = _chunkNSV6ECYOjs.e; exports.handleCrudifyError = _chunkNSV6ECYOjs.g; exports.isTokenExpired = _chunkMFYHD6S5js.s; exports.logger = _chunkMFYHD6S5js.a; exports.parseApiError = _chunkNSV6ECYOjs.c; exports.parseJavaScriptError = _chunkNSV6ECYOjs.f; exports.parseTransactionError = _chunkNSV6ECYOjs.d; exports.secureLocalStorage = _chunk5HFI5CZ5js.b; exports.secureSessionStorage = _chunk5HFI5CZ5js.a; exports.translateError = _chunkMFYHD6S5js.n; exports.translateErrorCode = _chunkMFYHD6S5js.l; exports.translateErrorCodes = _chunkMFYHD6S5js.m; exports.translationService = _chunkPYLSSR7Wjs.e; exports.useAuth = _chunkQ4RHNYTIjs.b; exports.useAutoGenerate = _chunkSFIIFYMZjs.m; exports.useCrudify = _chunkSFIIFYMZjs.h; exports.useCrudifyInitializer = nr; exports.useCrudifyWithNotifications = _chunkQ4RHNYTIjs.d; exports.useData = _chunkQ4RHNYTIjs.c; exports.useFileUpload = _chunkSFIIFYMZjs.p; exports.useGlobalNotification = _chunkSFIIFYMZjs.e; exports.useSession = _chunkSFIIFYMZjs.c; exports.useSessionContext = _chunkSFIIFYMZjs.j; exports.useTranslations = _chunkPYLSSR7Wjs.g; exports.useUserData = _chunkQ4RHNYTIjs.a; exports.useUserProfile = _chunkSFIIFYMZjs.l; exports.validateInternalRedirect = S;
package/dist/index.mjs CHANGED
@@ -1,6 +1,6 @@
1
- import{a as _,b as B,c as H,d as q,e as W,f as J,g as $,h as Ae,i as Ce,j as Re,k as Ie,l as Pe,m as he,n as Se,o as Te,p as Me,q as ze}from"./chunk-NSA6YDHY.mjs";import{a as we,b as Le,c as be,d as Oe}from"./chunk-QPTL5FLE.mjs";import{a as Y,b as f,c as ee,d as ie,e as ne,f as w,g as se,h as ae,i as pe,j as m,k as ce,l as xe,m as ve,n as ke,o as P,p as Ee}from"./chunk-PARX2RMU.mjs";import{a as Ue,b as Fe}from"./chunk-OGAGYHG4.mjs";import{a as de,b as le,c as ue,d as fe,e as me,f as ge,g as ye}from"./chunk-JAPL7EZJ.mjs";import{a as p,b as T,c as z,k as Z,l as Q,m as X,n as j,q as re,r as oe,s as te}from"./chunk-6BQGRZYB.mjs";import{default as Qr}from"@nocios/crudify-browser";export*from"@nocios/crudify-browser";import{useMemo as Ne}from"react";import{ThemeProvider as De,createTheme as Ge,CssBaseline as Ke}from"@mui/material";import{jsx as Be,jsxs as He}from"react/jsx-runtime";var Ve=(e={})=>{try{let r=T("theme");if(r){let o=JSON.parse(decodeURIComponent(r));return{...e,...o}}}catch(r){p.warn("Error parsing theme from cookie",r instanceof Error?{errorMessage:r.message}:{message:String(r)})}return e};function _e({children:e,defaultTheme:r={},disableCssBaseline:o=!1}){let t=Ne(()=>{let s=Ve(r);return Ge(s)},[r]);return He(De,{theme:t,children:[!o&&Be(Ke,{}),e]})}import{Navigate as Ze,useLocation as Qe}from"react-router-dom";import{Fragment as Je,jsx as h,jsxs as L}from"react/jsx-runtime";var qe={border:"5px solid rgba(0, 0, 0, 0.1)",borderTopColor:"#3B82F6",borderRadius:"50%",width:"50px",height:"50px",animation:"spin 1s linear infinite"},We=()=>h("style",{children:`
1
+ import{a as _,b as B,c as H,d as q,e as W,f as J,g as $,h as Ae,i as Ce,j as Pe,k as Re,l as Ie,m as he,n as Se,o as Te,p as Me,q as ze}from"./chunk-6M4Z5KHH.mjs";import{a as we,b as Le,c as be,d as Oe}from"./chunk-A5CDJL6G.mjs";import{a as Y,b as f,c as ee,d as ie,e as ne,f as w,g as se,h as ae,i as pe,j as m,k as ce,l as xe,m as ve,n as ke,o as I,p as Ee}from"./chunk-3OA4S6UT.mjs";import{a as Ue,b as Fe}from"./chunk-JNEWPO2J.mjs";import{a as le,b as ue,c as de,d as fe,e as me,f as ge,g as ye}from"./chunk-JAPL7EZJ.mjs";import{a as p,b as T,c as z,l as Z,m as Q,n as X,o as j,q as re,r as oe,s as te}from"./chunk-MGJZTOEM.mjs";import{default as Qr}from"@nocios/crudify-browser";export*from"@nocios/crudify-browser";import{useMemo as Ne}from"react";import{ThemeProvider as De,createTheme as Ge,CssBaseline as Ke}from"@mui/material";import{jsx as Be,jsxs as He}from"react/jsx-runtime";var Ve=(e={})=>{try{let r=T("theme");if(r){let o=JSON.parse(decodeURIComponent(r));return{...e,...o}}}catch(r){p.warn("Error parsing theme from cookie",r instanceof Error?{errorMessage:r.message}:{message:String(r)})}return e};function _e({children:e,defaultTheme:r={},disableCssBaseline:o=!1}){let t=Ne(()=>{let s=Ve(r);return Ge(s)},[r]);return He(De,{theme:t,children:[!o&&Be(Ke,{}),e]})}import{Navigate as Ze,useLocation as Qe}from"react-router-dom";import{Fragment as Je,jsx as h,jsxs as L}from"react/jsx-runtime";var qe={border:"5px solid rgba(0, 0, 0, 0.1)",borderTopColor:"#3B82F6",borderRadius:"50%",width:"50px",height:"50px",animation:"spin 1s linear infinite"},We=()=>h("style",{children:`
2
2
  @keyframes spin {
3
3
  0% { transform: rotate(0deg); }
4
4
  100% { transform: rotate(360deg); }
5
5
  }
6
- `});function k({stage:e="loading",message:r}){let t=r||{initializing:"Initializing application...","validating-session":"Validating session...",loading:"Loading..."}[e];return L(Je,{children:[h(We,{}),L("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",height:"100vh",width:"100vw",backgroundColor:"#f0f2f5",fontFamily:'"Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif',color:"#333",textAlign:"center",boxSizing:"border-box",padding:"20px",background:"#fff"},children:[h("div",{style:qe}),h("p",{style:{fontSize:"1.25em",fontWeight:"500",marginTop:"24px",color:"#1f2937"},children:t})]})]})}var $e=/^[a-zA-Z0-9\-_./\?=&%#]+$/,Ye=[/^https?:\/\//i,/^ftp:\/\//i,/^\/\//,/javascript:/i,/data:/i,/vbscript:/i,/about:/i,/\.\.\//,/\.\.\\/,/%2e%2e%2f/i,/%2e%2e%5c/i,/%2f%2f/i,/%5c%5c/i,/[\x00-\x1f\x7f-\x9f]/,/\\/],S=(e,r="/")=>{if(!e||typeof e!="string")return r;let o=e.trim();if(!o)return r;if(!o.startsWith("/"))return p.warn("Open redirect blocked (relative path)",{path:e}),r;if(!$e.test(o))return p.warn("Open redirect blocked (invalid characters)",{path:e}),r;let t=o.toLowerCase();for(let a of Ye)if(a.test(t))return p.warn("Open redirect blocked (dangerous pattern)",{path:e}),r;let s=o.split("?")[0].split("/").filter(Boolean);if(s.length===0)return o;for(let a of s)if(a===".."||a.includes(":")||a.length>100)return p.warn("Open redirect blocked (suspicious path part)",{part:a}),r;return o},E=(e,r="/")=>{try{let t=(typeof e=="string"?new URLSearchParams(e):e).get("redirect");if(!t)return r;let s=decodeURIComponent(t);return S(s,r)}catch(o){return p.warn("Error parsing redirect parameter",o instanceof Error?{errorMessage:o.message}:{message:String(o)}),r}};import{Fragment as b,jsx as v}from"react/jsx-runtime";function U({children:e,loadingComponent:r,loginPath:o="/login"}){let{isAuthenticated:t,isLoading:s,isInitialized:a,tokens:c,error:A}=m(),l=Qe();if(!a||s)return v(b,{children:r||v(k,{stage:"validating-session"})});let u=t&&c?.accessToken&&c.accessToken.length>0;if(A||!t||!u){c&&(!c.accessToken||c.accessToken.length===0)&&localStorage.removeItem("crudify_tokens");let x=l.pathname+l.search,C=S(x),R=encodeURIComponent(C);return v(Ze,{to:`${o}?redirect=${R}`,replace:!0})}return v(b,{children:e})}import{Navigate as Xe,useLocation as je}from"react-router-dom";import{Fragment as er,jsx as F}from"react/jsx-runtime";function O({children:e,redirectTo:r="/"}){let{isAuthenticated:o}=m(),t=je();if(o){let s=new URLSearchParams(t.search),a=E(s,r);return F(Xe,{to:a,replace:!0})}return F(er,{children:e})}import{createContext as rr,useContext as or,useEffect as tr,useRef as N,useState as M}from"react";import{Fragment as sr,jsx as D}from"react/jsx-runtime";var G=rr(void 0),ir=({config:e,children:r,fallback:o=null,onInitialized:t,onError:s})=>{let[a,c]=M(!1),[A,l]=M(!1),[u,x]=M(null),C=N(!1),R=N(!1);tr(()=>{C.current||(P.registerHighPriorityInitializer(),C.current=!0),R.current||(R.current=!0,(async()=>{l(!0),x(null);try{let d=z({publicApiKey:e?.publicApiKey,env:e?.env,enableDebug:e?.enableLogging});if(!d.publicApiKey)throw new Error("Crudify configuration missing. Please provide publicApiKey via props or ensure cookies are set by Lambda.");let I=d.env||"prod";p.setEnvironment(I),await P.initialize({priority:"HIGH",publicApiKey:d.publicApiKey,env:d.env||"prod",enableLogging:e?.enableLogging,requestedBy:"CrudifyInitializer"}),c(!0),l(!1),t&&t()}catch(d){let I=d instanceof Error?d:new Error(String(d));x(I),l(!1),s&&s(I)}})())},[e?.publicApiKey,e?.env,e?.enableLogging,t,s]);let V={isInitialized:a,isInitializing:A,error:u};return A&&o?D(sr,{children:o}):(u&&p.error("[CrudifyInitializer] Initialization failed",u),D(G.Provider,{value:V,children:r}))},nr=()=>{let e=or(G);if(!e)throw new Error("useCrudifyInitializer must be used within CrudifyInitializer");return e};import i from"@nocios/crudify-admin";var K=!1,g=null,y=null;async function ar(){let r=await f.getInstance().getTokenInfo(),o=r?.apiEndpointAdmin,t=r?.apiKeyEndpointAdmin;return o&&t?{apiUrl:o,apiKey:t}:w.waitForCredentials()}async function pr(){if(!K)return g||(g=(async()=>{try{let e=f.getInstance(),{apiUrl:r,apiKey:o}=await ar();y=(await e.getTokenInfo())?.crudifyTokens?.accessToken||null,i.init({url:r,apiKey:o,getAdditionalHeaders:()=>y?{Authorization:`Bearer ${y}`}:{}}),K=!0}catch(e){throw g=null,p.error("[crudifyAdminWrapper] Initialization failed",e instanceof Error?e:{message:String(e)}),e}})(),g)}async function n(e){try{await pr();let r=f.getInstance();y=(await r.getTokenInfo())?.crudifyTokens?.accessToken||null;let t=await e(),s=t.errors&&(typeof t.errors=="string"&&t.errors.includes("401")||Array.isArray(t.errors)&&t.errors.some(a=>typeof a=="string"&&a.includes("401")));return!t.success&&s?await r.refreshTokens()?(y=(await r.getTokenInfo())?.crudifyTokens?.accessToken||null,await e()):(p.error("[crudifyAdmin] Token refresh failed"),typeof window<"u"&&(window.location.href="/login"),t):t}catch(r){return p.error("[crudifyAdmin] Operation error",r instanceof Error?r:{message:String(r)}),{success:!1,errors:r instanceof Error?r.message:"Unknown error"}}}var cr={listModules:()=>n(()=>i.listModules()),getModule:e=>n(()=>i.getModule(e)),createModule:e=>n(()=>i.createModule(e)),editModule:(e,r)=>n(()=>i.editModule(e,r)),deleteModule:e=>n(()=>i.deleteModule(e)),activateModule:e=>n(()=>i.activateModule(e)),deactivateModule:e=>n(()=>i.deactivateModule(e)),getModuleVersions:e=>n(()=>i.getModuleVersions(e)),listActions:e=>n(()=>i.listActions(e)),getAction:e=>n(()=>i.getAction(e)),createAction:e=>n(()=>i.createAction(e)),editAction:(e,r)=>n(()=>i.editAction(e,r)),deleteAction:e=>n(()=>i.deleteAction(e)),activateAction:e=>n(()=>i.activateAction(e)),deactivateAction:e=>n(()=>i.deactivateAction(e)),getActionVersions:e=>n(()=>i.getActionVersions(e)),getActionsByProfile:e=>n(()=>i.getActionsByProfile(e)),updateActionsProfiles:e=>n(()=>i.updateActionsProfiles(e))};export{O as AuthRoute,_ as CRITICAL_TRANSLATIONS,Te as CrudiaAutoGenerate,Me as CrudiaFileField,ze as CrudiaMarkdownField,ke as CrudifyInitializationManager,ir as CrudifyInitializer,Ae as CrudifyLogin,se as CrudifyProvider,_e as CrudifyThemeProvider,de as ERROR_CODES,le as ERROR_SEVERITY_MAP,ie as GlobalNotificationProvider,he as LoginComponent,Re as POLICY_ACTIONS,Ie as PREFERRED_POLICY_ORDER,Pe as Policies,U as ProtectedRoute,ce as SessionDebugInfo,k as SessionLoadingScreen,f as SessionManager,pe as SessionProvider,Se as SessionStatus,Y as TokenStorage,q as TranslationService,J as TranslationsProvider,Ce as UserProfileDisplay,j as createErrorTranslator,Qr as crudify,cr as crudifyAdmin,P as crudifyInitManager,re as decodeJwtSafely,E as extractSafeRedirectFromUrl,T as getCookie,B as getCriticalLanguages,H as getCriticalTranslations,oe as getCurrentUserEmail,me as getErrorMessage,ye as handleCrudifyError,te as isTokenExpired,p as logger,ue as parseApiError,ge as parseJavaScriptError,fe as parseTransactionError,Fe as secureLocalStorage,Ue as secureSessionStorage,X as translateError,Z as translateErrorCode,Q as translateErrorCodes,W as translationService,Le as useAuth,ve as useAutoGenerate,ae as useCrudify,nr as useCrudifyInitializer,Oe as useCrudifyWithNotifications,be as useData,Ee as useFileUpload,ne as useGlobalNotification,ee as useSession,m as useSessionContext,$ as useTranslations,we as useUserData,xe as useUserProfile,S as validateInternalRedirect};
6
+ `});function k({stage:e="loading",message:r}){let t=r||{initializing:"Initializing application...","validating-session":"Validating session...",loading:"Loading..."}[e];return L(Je,{children:[h(We,{}),L("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",height:"100vh",width:"100vw",backgroundColor:"#f0f2f5",fontFamily:'"Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif',color:"#333",textAlign:"center",boxSizing:"border-box",padding:"20px",background:"#fff"},children:[h("div",{style:qe}),h("p",{style:{fontSize:"1.25em",fontWeight:"500",marginTop:"24px",color:"#1f2937"},children:t})]})]})}var $e=/^[a-zA-Z0-9\-_./\?=&%#]+$/,Ye=[/^https?:\/\//i,/^ftp:\/\//i,/^\/\//,/javascript:/i,/data:/i,/vbscript:/i,/about:/i,/\.\.\//,/\.\.\\/,/%2e%2e%2f/i,/%2e%2e%5c/i,/%2f%2f/i,/%5c%5c/i,/[\x00-\x1f\x7f-\x9f]/,/\\/],S=(e,r="/")=>{if(!e||typeof e!="string")return r;let o=e.trim();if(!o)return r;if(!o.startsWith("/"))return p.warn("Open redirect blocked (relative path)",{path:e}),r;if(!$e.test(o))return p.warn("Open redirect blocked (invalid characters)",{path:e}),r;let t=o.toLowerCase();for(let a of Ye)if(a.test(t))return p.warn("Open redirect blocked (dangerous pattern)",{path:e}),r;let s=o.split("?")[0].split("/").filter(Boolean);if(s.length===0)return o;for(let a of s)if(a===".."||a.includes(":")||a.length>100)return p.warn("Open redirect blocked (suspicious path part)",{part:a}),r;return o},E=(e,r="/")=>{try{let t=(typeof e=="string"?new URLSearchParams(e):e).get("redirect");if(!t)return r;let s=decodeURIComponent(t);return S(s,r)}catch(o){return p.warn("Error parsing redirect parameter",o instanceof Error?{errorMessage:o.message}:{message:String(o)}),r}};import{Fragment as b,jsx as v}from"react/jsx-runtime";function U({children:e,loadingComponent:r,loginPath:o="/login"}){let{isAuthenticated:t,isLoading:s,isInitialized:a,tokens:c,error:A}=m(),u=Qe();if(!a||s)return v(b,{children:r||v(k,{stage:"validating-session"})});let d=t&&c?.accessToken&&c.accessToken.length>0;if(A||!t||!d){c&&(!c.accessToken||c.accessToken.length===0)&&localStorage.removeItem("crudify_tokens");let x=u.pathname+u.search,C=S(x),P=encodeURIComponent(C);return v(Ze,{to:`${o}?redirect=${P}`,replace:!0})}return v(b,{children:e})}import{Navigate as Xe,useLocation as je}from"react-router-dom";import{Fragment as er,jsx as F}from"react/jsx-runtime";function O({children:e,redirectTo:r="/"}){let{isAuthenticated:o}=m(),t=je();if(o){let s=new URLSearchParams(t.search),a=E(s,r);return F(Xe,{to:a,replace:!0})}return F(er,{children:e})}import{createContext as rr,useContext as or,useEffect as tr,useRef as N,useState as M}from"react";import{Fragment as sr,jsx as D}from"react/jsx-runtime";var G=rr(void 0),ir=({config:e,children:r,fallback:o=null,onInitialized:t,onError:s})=>{let[a,c]=M(!1),[A,u]=M(!1),[d,x]=M(null),C=N(!1),P=N(!1);tr(()=>{C.current||(I.registerHighPriorityInitializer(),C.current=!0),P.current||(P.current=!0,(async()=>{u(!0),x(null);try{let l=z({publicApiKey:e?.publicApiKey,env:e?.env,enableDebug:e?.enableLogging});if(!l.publicApiKey)throw new Error("Crudify configuration missing. Please provide publicApiKey via props or ensure cookies are set by Lambda.");let R=l.env||"prod";p.setEnvironment(R),await I.initialize({priority:"HIGH",publicApiKey:l.publicApiKey,env:l.env||"prod",enableLogging:e?.enableLogging,requestedBy:"CrudifyInitializer"}),c(!0),u(!1),t&&t()}catch(l){let R=l instanceof Error?l:new Error(String(l));x(R),u(!1),s&&s(R)}})())},[e?.publicApiKey,e?.env,e?.enableLogging,t,s]);let V={isInitialized:a,isInitializing:A,error:d};return A&&o?D(sr,{children:o}):(d&&p.error("[CrudifyInitializer] Initialization failed",d),D(G.Provider,{value:V,children:r}))},nr=()=>{let e=or(G);if(!e)throw new Error("useCrudifyInitializer must be used within CrudifyInitializer");return e};import i from"@nocios/crudify-admin";var K=!1,g=null,y=null;async function ar(){let r=await f.getInstance().getTokenInfo(),o=r?.apiEndpointAdmin,t=r?.apiKeyEndpointAdmin;return o&&t?{apiUrl:o,apiKey:t}:w.waitForCredentials()}async function pr(){if(!K)return g||(g=(async()=>{try{let e=f.getInstance(),{apiUrl:r,apiKey:o}=await ar();y=(await e.getTokenInfo())?.crudifyTokens?.accessToken||null,i.init({url:r,apiKey:o,getAdditionalHeaders:()=>y?{Authorization:`Bearer ${y}`}:{}}),K=!0}catch(e){throw g=null,p.error("[crudifyAdminWrapper] Initialization failed",e instanceof Error?e:{message:String(e)}),e}})(),g)}async function n(e){try{await pr();let r=f.getInstance();y=(await r.getTokenInfo())?.crudifyTokens?.accessToken||null;let t=await e(),s=t.errors&&(typeof t.errors=="string"&&t.errors.includes("401")||Array.isArray(t.errors)&&t.errors.some(a=>typeof a=="string"&&a.includes("401")));return!t.success&&s?await r.refreshTokens()?(y=(await r.getTokenInfo())?.crudifyTokens?.accessToken||null,await e()):(p.error("[crudifyAdmin] Token refresh failed"),typeof window<"u"&&(window.location.href="/login"),t):t}catch(r){return p.error("[crudifyAdmin] Operation error",r instanceof Error?r:{message:String(r)}),{success:!1,errors:r instanceof Error?r.message:"Unknown error"}}}var cr={listModules:()=>n(()=>i.listModules()),getModule:e=>n(()=>i.getModule(e)),createModule:e=>n(()=>i.createModule(e)),editModule:(e,r)=>n(()=>i.editModule(e,r)),deleteModule:e=>n(()=>i.deleteModule(e)),activateModule:e=>n(()=>i.activateModule(e)),deactivateModule:e=>n(()=>i.deactivateModule(e)),getModuleVersions:e=>n(()=>i.getModuleVersions(e)),listActions:e=>n(()=>i.listActions(e)),getAction:e=>n(()=>i.getAction(e)),createAction:e=>n(()=>i.createAction(e)),editAction:(e,r)=>n(()=>i.editAction(e,r)),deleteAction:e=>n(()=>i.deleteAction(e)),activateAction:e=>n(()=>i.activateAction(e)),deactivateAction:e=>n(()=>i.deactivateAction(e)),getActionVersions:e=>n(()=>i.getActionVersions(e)),getActionsByProfile:e=>n(()=>i.getActionsByProfile(e)),updateActionsProfiles:e=>n(()=>i.updateActionsProfiles(e)),calculatePermissions:e=>n(()=>i.calculatePermissions(e))};export{O as AuthRoute,_ as CRITICAL_TRANSLATIONS,Te as CrudiaAutoGenerate,Me as CrudiaFileField,ze as CrudiaMarkdownField,ke as CrudifyInitializationManager,ir as CrudifyInitializer,Ae as CrudifyLogin,se as CrudifyProvider,_e as CrudifyThemeProvider,le as ERROR_CODES,ue as ERROR_SEVERITY_MAP,ie as GlobalNotificationProvider,he as LoginComponent,Pe as POLICY_ACTIONS,Re as PREFERRED_POLICY_ORDER,Ie as Policies,U as ProtectedRoute,ce as SessionDebugInfo,k as SessionLoadingScreen,f as SessionManager,pe as SessionProvider,Se as SessionStatus,Y as TokenStorage,q as TranslationService,J as TranslationsProvider,Ce as UserProfileDisplay,j as createErrorTranslator,Qr as crudify,cr as crudifyAdmin,I as crudifyInitManager,re as decodeJwtSafely,E as extractSafeRedirectFromUrl,T as getCookie,B as getCriticalLanguages,H as getCriticalTranslations,oe as getCurrentUserEmail,me as getErrorMessage,ye as handleCrudifyError,te as isTokenExpired,p as logger,de as parseApiError,ge as parseJavaScriptError,fe as parseTransactionError,Fe as secureLocalStorage,Ue as secureSessionStorage,X as translateError,Z as translateErrorCode,Q as translateErrorCodes,W as translationService,Le as useAuth,ve as useAutoGenerate,ae as useCrudify,nr as useCrudifyInitializer,Oe as useCrudifyWithNotifications,be as useData,Ee as useFileUpload,ne as useGlobalNotification,ee as useSession,m as useSessionContext,$ as useTranslations,we as useUserData,xe as useUserProfile,S as validateInternalRedirect};
package/dist/utils.d.mts CHANGED
@@ -56,7 +56,7 @@ declare function useResolvedConfig(options?: ConfigResolverOptions): ResolvedCon
56
56
  * - Suscribirse para recibir notificaciones de eventos
57
57
  * - Debounce automático para evitar múltiples disparos
58
58
  */
59
- type AuthEventType = "SESSION_EXPIRED" | "TOKEN_REFRESH_FAILED" | "UNAUTHORIZED" | "TOKEN_EXPIRED";
59
+ type AuthEventType = "SESSION_EXPIRED" | "TOKEN_REFRESH_FAILED" | "UNAUTHORIZED" | "TOKEN_EXPIRED" | "LOGOUT";
60
60
  type AuthEventDetails = {
61
61
  message?: string;
62
62
  error?: unknown;
package/dist/utils.d.ts CHANGED
@@ -56,7 +56,7 @@ declare function useResolvedConfig(options?: ConfigResolverOptions): ResolvedCon
56
56
  * - Suscribirse para recibir notificaciones de eventos
57
57
  * - Debounce automático para evitar múltiples disparos
58
58
  */
59
- type AuthEventType = "SESSION_EXPIRED" | "TOKEN_REFRESH_FAILED" | "UNAUTHORIZED" | "TOKEN_EXPIRED";
59
+ type AuthEventType = "SESSION_EXPIRED" | "TOKEN_REFRESH_FAILED" | "UNAUTHORIZED" | "TOKEN_EXPIRED" | "LOGOUT";
60
60
  type AuthEventDetails = {
61
61
  message?: string;
62
62
  error?: unknown;
package/dist/utils.js CHANGED
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true});var _chunkKQ2XC5PNjs = require('./chunk-KQ2XC5PN.js');var _chunkNSV6ECYOjs = require('./chunk-NSV6ECYO.js');var _chunkNXTXGTU6js = require('./chunk-NXTXGTU6.js');exports.ERROR_CODES = _chunkNSV6ECYOjs.a; exports.ERROR_SEVERITY_MAP = _chunkNSV6ECYOjs.b; exports.NavigationTracker = _chunkNXTXGTU6js.p; exports.authEventBus = _chunkNXTXGTU6js.o; exports.createErrorTranslator = _chunkNXTXGTU6js.n; exports.decodeJwtSafely = _chunkNXTXGTU6js.q; exports.getCookie = _chunkNXTXGTU6js.b; exports.getCurrentUserEmail = _chunkNXTXGTU6js.r; exports.getErrorMessage = _chunkNSV6ECYOjs.e; exports.handleCrudifyError = _chunkNSV6ECYOjs.g; exports.isTokenExpired = _chunkNXTXGTU6js.s; exports.parseApiError = _chunkNSV6ECYOjs.c; exports.parseJavaScriptError = _chunkNSV6ECYOjs.f; exports.parseTransactionError = _chunkNSV6ECYOjs.d; exports.resolveConfig = _chunkNXTXGTU6js.c; exports.secureLocalStorage = _chunkKQ2XC5PNjs.b; exports.secureSessionStorage = _chunkKQ2XC5PNjs.a; exports.translateError = _chunkNXTXGTU6js.m; exports.translateErrorCode = _chunkNXTXGTU6js.k; exports.translateErrorCodes = _chunkNXTXGTU6js.l; exports.useResolvedConfig = _chunkNXTXGTU6js.d;
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true});var _chunk5HFI5CZ5js = require('./chunk-5HFI5CZ5.js');var _chunkNSV6ECYOjs = require('./chunk-NSV6ECYO.js');var _chunkMFYHD6S5js = require('./chunk-MFYHD6S5.js');exports.ERROR_CODES = _chunkNSV6ECYOjs.a; exports.ERROR_SEVERITY_MAP = _chunkNSV6ECYOjs.b; exports.NavigationTracker = _chunkMFYHD6S5js.p; exports.authEventBus = _chunkMFYHD6S5js.e; exports.createErrorTranslator = _chunkMFYHD6S5js.o; exports.decodeJwtSafely = _chunkMFYHD6S5js.q; exports.getCookie = _chunkMFYHD6S5js.b; exports.getCurrentUserEmail = _chunkMFYHD6S5js.r; exports.getErrorMessage = _chunkNSV6ECYOjs.e; exports.handleCrudifyError = _chunkNSV6ECYOjs.g; exports.isTokenExpired = _chunkMFYHD6S5js.s; exports.parseApiError = _chunkNSV6ECYOjs.c; exports.parseJavaScriptError = _chunkNSV6ECYOjs.f; exports.parseTransactionError = _chunkNSV6ECYOjs.d; exports.resolveConfig = _chunkMFYHD6S5js.c; exports.secureLocalStorage = _chunk5HFI5CZ5js.b; exports.secureSessionStorage = _chunk5HFI5CZ5js.a; exports.translateError = _chunkMFYHD6S5js.n; exports.translateErrorCode = _chunkMFYHD6S5js.l; exports.translateErrorCodes = _chunkMFYHD6S5js.m; exports.useResolvedConfig = _chunkMFYHD6S5js.d;
package/dist/utils.mjs CHANGED
@@ -1 +1 @@
1
- import{a as R,b as c}from"./chunk-OGAGYHG4.mjs";import{a as m,b as v,c as d,d as g,e as u,f as x,g as C}from"./chunk-JAPL7EZJ.mjs";import{b as r,c as e,d as o,k as t,l as a,m as n,n as s,o as E,p as i,q as p,r as f,s as l}from"./chunk-6BQGRZYB.mjs";export{m as ERROR_CODES,v as ERROR_SEVERITY_MAP,i as NavigationTracker,E as authEventBus,s as createErrorTranslator,p as decodeJwtSafely,r as getCookie,f as getCurrentUserEmail,u as getErrorMessage,C as handleCrudifyError,l as isTokenExpired,d as parseApiError,x as parseJavaScriptError,g as parseTransactionError,e as resolveConfig,c as secureLocalStorage,R as secureSessionStorage,n as translateError,t as translateErrorCode,a as translateErrorCodes,o as useResolvedConfig};
1
+ import{a as R,b as c}from"./chunk-JNEWPO2J.mjs";import{a as m,b as v,c as d,d as g,e as u,f as x,g as C}from"./chunk-JAPL7EZJ.mjs";import{b as r,c as e,d as o,e as t,l as a,m as n,n as s,o as E,p as i,q as p,r as f,s as l}from"./chunk-MGJZTOEM.mjs";export{m as ERROR_CODES,v as ERROR_SEVERITY_MAP,i as NavigationTracker,t as authEventBus,E as createErrorTranslator,p as decodeJwtSafely,r as getCookie,f as getCurrentUserEmail,u as getErrorMessage,C as handleCrudifyError,l as isTokenExpired,d as parseApiError,x as parseJavaScriptError,g as parseTransactionError,e as resolveConfig,c as secureLocalStorage,R as secureSessionStorage,s as translateError,a as translateErrorCode,n as translateErrorCodes,o as useResolvedConfig};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nocios/crudify-ui",
3
- "version": "5.0.2",
3
+ "version": "5.0.6",
4
4
  "engines": {
5
5
  "node": ">=24.12.0"
6
6
  },
@@ -42,7 +42,7 @@
42
42
  },
43
43
  "dependencies": {
44
44
  "@mdxeditor/editor": "^3.52.0",
45
- "@nocios/crudify-admin": "^5.0.0",
45
+ "@nocios/crudify-admin": "^5.0.2",
46
46
  "@nocios/crudify-browser": "^5.0.0",
47
47
  "dompurify": "^3.2.7",
48
48
  "uuid": "^13.0.0"
package/vitest.config.ts CHANGED
@@ -17,14 +17,7 @@ export default defineConfig({
17
17
  coverage: {
18
18
  provider: "v8",
19
19
  reporter: ["text", "json", "html"],
20
- exclude: [
21
- "node_modules/",
22
- "src/__tests__/",
23
- "dist/",
24
- "**/*.d.ts",
25
- "**/*.config.*",
26
- "**/mockData.ts",
27
- ],
20
+ exclude: ["node_modules/", "src/__tests__/", "dist/", "**/*.d.ts", "**/*.config.*", "**/mockData.ts"],
28
21
  },
29
22
  },
30
23
  resolve: {