@nocios/crudify-components 1.0.0 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +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 ze="crudify_storage_version",Ue=2,a=class a{static setStorageType(t){a.storageType=t}static async initialize(){if(!(a.encryptionKey&&a.salt))return a.initPromise||(a.initPromise=(async()=>{let e=null;for(let i=1;i<=3;i++)try{a.checkStorageVersion(),a.salt=a.getOrCreateSalt(),a.fingerprint=await a.generateFingerprint(),a.encryptionKey=await _chunkMFYHD6S5js.g.call(void 0, a.fingerprint,a.salt);return}catch(n){e=n instanceof Error?n:new Error(String(n)),i<3&&await new Promise(s=>setTimeout(s,100*i))}throw _chunkMFYHD6S5js.a.error("Crudify: Failed to initialize encryption after retries",_nullishCoalesce(e, () => ({message:"Unknown error"}))),e})()),a.initPromise}static checkStorageVersion(){try{if(parseInt(localStorage.getItem(ze)||"1",10)<Ue){let e=a.getStorage();e&&e.removeItem(a.TOKEN_KEY),localStorage.removeItem(a.ENCRYPTION_KEY_STORAGE),localStorage.removeItem(a.SALT_KEY),localStorage.setItem(ze,Ue.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 i=atob(e),n=new Uint8Array(i.length);for(let s=0;s<i.length;s++)n[s]=i.charCodeAt(s);return n}}catch (e3){}let t=_chunkMFYHD6S5js.j.call(void 0, );try{let e="";for(let i=0;i<t.length;i++)e+=String.fromCharCode(t[i]);localStorage.setItem(a.SALT_KEY,btoa(e))}catch (e4){_chunkMFYHD6S5js.a.warn("Crudify: Cannot persist salt, encryption may not persist across sessions")}return t}static async generateFingerprint(){try{let n=localStorage.getItem(a.ENCRYPTION_KEY_STORAGE);if(n&&n.length>=32)return n}catch (e5){}let e=[navigator.userAgent,navigator.language,navigator.platform||"unknown",String(screen.width),String(screen.height),String(screen.colorDepth||24),String(new Date().getTimezoneOffset()),"crudify-session-v3"].join("|"),i=await _chunkMFYHD6S5js.f.call(void 0, e);try{localStorage.setItem(a.ENCRYPTION_KEY_STORAGE,i)}catch (e6){_chunkMFYHD6S5js.a.warn("Crudify: Cannot persist encryption key hash, session may not survive page reload")}return i}static isStorageAvailable(t){try{let e=window[t],i="__storage_test__";return e.setItem(i,"test"),e.removeItem(i),!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(t){if(await a.initialize(),!a.encryptionKey||!a.salt)throw new Error("Encryption not initialized");return _chunkMFYHD6S5js.h.call(void 0, t,a.encryptionKey,a.salt)}static async decryptData(t){if(await a.initialize(),!a.fingerprint)throw new Error("Encryption not initialized");return _chunkMFYHD6S5js.k.call(void 0, t)?_chunkMFYHD6S5js.i.call(void 0, t,a.fingerprint):(_chunkMFYHD6S5js.a.warn("Crudify: Legacy encrypted data detected, cannot decrypt"),null)}static async saveTokens(t){let e=a.getStorage();if(e)try{let i={accessToken:t.accessToken,refreshToken:t.refreshToken,expiresAt:t.expiresAt,refreshExpiresAt:t.refreshExpiresAt,savedAt:Date.now()},n=await a.encryptData(JSON.stringify(i));e.setItem(a.TOKEN_KEY,n),_chunkMFYHD6S5js.a.debug("Crudify: Tokens saved successfully")}catch(i){_chunkMFYHD6S5js.a.error("Crudify: Failed to save tokens",i instanceof Error?i:{message:String(i)})}}static async getTokens(){let t=a.getStorage();if(!t)return null;try{let e=t.getItem(a.TOKEN_KEY);if(!e)return null;let i=await a.decryptData(e);if(!i)return _chunkMFYHD6S5js.a.warn("Crudify: Failed to decrypt tokens, clearing storage"),await a.clearTokens(),null;let n=JSON.parse(i);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 t=a.getStorage();if(t)try{t.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(t){_chunkMFYHD6S5js.a.error("Crudify: Failed to rotate encryption key",t instanceof Error?t:{message:String(t)})}}static async hasValidTokens(){return await a.getTokens()!==null}static async ensureInitialized(){await a.initialize()}static async getExpirationInfo(){let t=await a.getTokens();if(!t)return null;let e=Date.now();return{accessExpired:e>=t.expiresAt,refreshExpired:e>=t.refreshExpiresAt,accessExpiresIn:Math.max(0,t.expiresAt-e),refreshExpiresIn:Math.max(0,t.refreshExpiresAt-e)}}static async updateAccessToken(t,e){let i=await a.getTokens();if(!i){_chunkMFYHD6S5js.a.warn("Crudify: Cannot update access token, no existing tokens found");return}await a.saveTokens({...i,accessToken:t,expiresAt:e})}static createSyncEvent(t,e,i){return{type:t,tokens:e,hadPreviousTokens:i}}static markLocalChange(){a.ignoreNextStorageEvent=!0,a.ignoreStorageEventTimeout&&clearTimeout(a.ignoreStorageEventTimeout),a.ignoreStorageEventTimeout=setTimeout(()=>{a.ignoreNextStorageEvent=!1},100)}static markSuccessfulLogin(){a.lastSuccessfulLoginTime=Date.now()}static isWithinLoginGracePeriod(){return a.lastSuccessfulLoginTime===0?!1:Date.now()-a.lastSuccessfulLoginTime<a.LOGIN_GRACE_PERIOD_MS}static subscribeToChanges(t){let e=async i=>{if(i.key!==a.TOKEN_KEY)return;if(a.ignoreNextStorageEvent){a.ignoreNextStorageEvent=!1;return}if(i.newValue===null&&a.isWithinLoginGracePeriod())return;if(i.newValue===null){let l=_optionalChain([a, 'access', _2 => _2.getStorage, 'call', _3 => _3(), 'optionalAccess', _4 => _4.getItem, 'call', _5 => _5(a.TOKEN_KEY)]);if(l!==null&&l!=="")return}let n=i.oldValue!==null&&i.oldValue!=="";if(i.newValue===null){_chunkMFYHD6S5js.a.debug("Crudify: Tokens removed in another tab"),t(null,a.SYNC_EVENTS.TOKENS_CLEARED,n);return}if(i.newValue){_chunkMFYHD6S5js.a.debug("Crudify: Tokens updated in another tab");let s=await a.getTokens();t(s,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.lastSuccessfulLoginTime=0,a.LOGIN_GRACE_PERIOD_MS=5e3,a.SYNC_EVENTS={TOKENS_CLEARED:"TOKENS_CLEARED",TOKENS_UPDATED:"TOKENS_UPDATED"},a.ignoreNextStorageEvent=!1,a.ignoreStorageEventTimeout=null;var v=a;var K=class K{constructor(){this.broadcastChannel=null;this.CHANNEL_NAME="crudify-session-sync";this.listeners=new Set;this.isInitialized=!1;this.tabId=K.generateTabId(),this.initialize()}static generateTabId(){let t=Date.now().toString(36),e=Math.random().toString(36).substring(2,9);return`tab_${t}_${e}`}static getInstance(){return K.instance||(K.instance=new K),K.instance}static resetInstance(){K.instance&&(K.instance.destroy(),K.instance=null)}initialize(){if(!this.isInitialized)try{typeof BroadcastChannel<"u"?(this.broadcastChannel=new BroadcastChannel(this.CHANNEL_NAME),this.broadcastChannel.onmessage=t=>{this.handleMessage(t.data)},this.broadcastChannel.onmessageerror=()=>{_chunkMFYHD6S5js.a.warn("Crudify: CrossTabSync message error")},_chunkMFYHD6S5js.a.debug("Crudify: CrossTabSync initialized with BroadcastChannel")):_chunkMFYHD6S5js.a.debug("Crudify: BroadcastChannel not available, using localStorage fallback"),this.isInitialized=!0}catch(t){_chunkMFYHD6S5js.a.warn("Crudify: Failed to initialize CrossTabSync",{message:t instanceof Error?t.message:String(t)})}}destroy(){this.broadcastChannel&&(this.broadcastChannel.close(),this.broadcastChannel=null),this.listeners.clear(),this.isInitialized=!1}getTabId(){return this.tabId}subscribe(t){return this.listeners.add(t),()=>{this.listeners.delete(t)}}notifyLogin(){this.broadcast({type:"SESSION_STARTED",tabId:this.tabId,timestamp:Date.now()})}notifyLogout(){this.broadcast({type:"SESSION_ENDED",tabId:this.tabId,timestamp:Date.now()})}notifyTokenRefreshed(){this.broadcast({type:"TOKEN_REFRESHED",tabId:this.tabId,timestamp:Date.now()})}ping(){this.broadcast({type:"SESSION_PING",tabId:this.tabId,timestamp:Date.now()})}broadcast(t){this.isInitialized||this.initialize();try{this.broadcastChannel&&(this.broadcastChannel.postMessage(t),_chunkMFYHD6S5js.a.debug(`Crudify: CrossTab broadcast ${t.type}`))}catch(e){_chunkMFYHD6S5js.a.warn("Crudify: Failed to broadcast cross-tab message",{message:e instanceof Error?e.message:String(e)})}}handleMessage(t){t.tabId!==this.tabId&&(_chunkMFYHD6S5js.a.debug(`Crudify: CrossTab received ${t.type} from ${t.tabId}`),t.type==="SESSION_PING"&&this.broadcast({type:"SESSION_PONG",tabId:this.tabId,timestamp:Date.now(),payload:{respondingTo:t.tabId}}),this.listeners.forEach(e=>{try{e(t)}catch(i){_chunkMFYHD6S5js.a.error("Crudify: CrossTab listener error",{message:i instanceof Error?i.message:String(i)})}}))}};K.instance=null;var ye=K,W= exports.c =ye.getInstance();var _crudifysdk = require('@nocios/crudify-sdk'); var _crudifysdk2 = _interopRequireDefault(_crudifysdk);var ne=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(t={}){if(!this.initialized){if(this.config={storageType:"localStorage",autoRestore:!0,enableLogging:!1,env:"stg",...t},v.setStorageType(this.config.storageType||"localStorage"),this.config.publicApiKey&&!this.crudifyInitialized&&await this.ensureCrudifyInitialized(),_crudifysdk2.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 v.getTokens();e?await v.saveTokens({...e,apiEndpointAdmin:this.config.apiEndpointAdmin,apiKeyEndpointAdmin:this.config.apiKeyEndpointAdmin}):await v.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(t,e){try{let i=await _crudifysdk2.default.login(t,e);if(!i.success)return{success:!1,error:this.formatError(i.errors),rawResponse:i};let n=await v.getTokens(),s=i.data,l={accessToken:s.token,refreshToken:s.refreshToken,expiresAt:s.expiresAt,refreshExpiresAt:s.refreshExpiresAt,apiEndpointAdmin:_optionalChain([n, 'optionalAccess', _6 => _6.apiEndpointAdmin])||this.config.apiEndpointAdmin,apiKeyEndpointAdmin:_optionalChain([n, 'optionalAccess', _7 => _7.apiKeyEndpointAdmin])||this.config.apiKeyEndpointAdmin};return await v.saveTokens(l),v.markSuccessfulLogin(),this.lastActivityTime=Date.now(),W.notifyLogin(),_optionalChain([this, 'access', _8 => _8.config, 'access', _9 => _9.onLoginSuccess, 'optionalCall', _10 => _10(l)]),{success:!0,tokens:l,data:s}}catch(i){return _chunkMFYHD6S5js.a.error("[SessionManager] Login error",i instanceof Error?i:{message:String(i)}),{success:!1,error:i instanceof Error?i.message:"Unknown error"}}}async logout(){try{this.log("Logging out..."),_chunkMFYHD6S5js.e.emit("LOGOUT",{message:"User logged out",source:"SessionManager.logout"}),await _crudifysdk2.default.logout(),await v.clearTokens(),W.notifyLogout(),this.log("Logout successful"),_optionalChain([this, 'access', _11 => _11.config, 'access', _12 => _12.onLogout, 'optionalCall', _13 => _13()])}catch(t){this.log("Logout error",{error:t instanceof Error?t.message:String(t)}),await v.clearTokens(),W.notifyLogout()}}async restoreSession(){try{this.log("Attempting to restore session...");let t=await v.getTokens();if(!t)return this.log("No valid tokens found in storage"),!1;if(Date.now()>=t.refreshExpiresAt)return this.log("Refresh token expired, clearing storage"),await v.clearTokens(),!1;if(_crudifysdk2.default.setTokens({accessToken:t.accessToken,refreshToken:t.refreshToken,expiresAt:t.expiresAt,refreshExpiresAt:t.refreshExpiresAt}),_crudifysdk2.default.getTokenData().isValid===!1){if(this.log("Restored access token is invalid or expired"),Date.now()<t.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 v.getTokens();return n&&_optionalChain([this, 'access', _14 => _14.config, 'access', _15 => _15.onSessionRestored, 'optionalCall', _16 => _16(n)]),!0}return await v.clearTokens(),await _crudifysdk2.default.logout(),!1}return this.log("Session restored successfully"),this.lastActivityTime=Date.now(),_optionalChain([this, 'access', _17 => _17.config, 'access', _18 => _18.onSessionRestored, 'optionalCall', _19 => _19(t)]),!0}catch(t){return this.log("Session restore error",{error:t instanceof Error?t.message:String(t)}),await v.clearTokens(),await _crudifysdk2.default.logout(),!1}}async isAuthenticated(){return _crudifysdk2.default.isLogin()||await v.hasValidTokens()}async getTokenInfo(){let t=_crudifysdk2.default.getTokenData(),e=await v.getExpirationInfo(),i=await v.getTokens();return{isLoggedIn:await this.isAuthenticated(),crudifyTokens:t,storageInfo:e,hasValidTokens:await v.hasValidTokens(),apiEndpointAdmin:_optionalChain([i, 'optionalAccess', _20 => _20.apiEndpointAdmin]),apiKeyEndpointAdmin:_optionalChain([i, 'optionalAccess', _21 => _21.apiKeyEndpointAdmin])}}async refreshTokens(){if(this.isRefreshingLocally&&this.refreshPromise)return this.log("Refresh already in progress, waiting for existing promise..."),this.refreshPromise;this.isRefreshingLocally=!0,this.refreshPromise=this._performRefresh();try{return await this.refreshPromise}finally{this.isRefreshingLocally=!1,this.refreshPromise=null}}async _performRefresh(){try{this.log("Starting token refresh...");let t=await _crudifysdk2.default.refreshAccessToken();if(!t.success)return this.log("Token refresh failed",{errors:t.errors}),await v.clearTokens(),_optionalChain([this, 'access', _22 => _22.config, 'access', _23 => _23.showNotification, 'optionalCall', _24 => _24(this.getSessionExpiredMessage(),"warning")]),_optionalChain([this, 'access', _25 => _25.config, 'access', _26 => _26.onSessionExpired, 'optionalCall', _27 => _27()]),!1;let e=t.data,i={accessToken:e.token,refreshToken:e.refreshToken,expiresAt:e.expiresAt,refreshExpiresAt:e.refreshExpiresAt};return await v.saveTokens(i),this.log("Tokens refreshed and saved successfully"),this.lastActivityTime=Date.now(),W.notifyTokenRefreshed(),!0}catch(t){return this.log("Token refresh error",{error:t instanceof Error?t.message:String(t)}),await v.clearTokens(),_optionalChain([this, 'access', _28 => _28.config, 'access', _29 => _29.showNotification, 'optionalCall', _30 => _30(this.getSessionExpiredMessage(),"warning")]),_optionalChain([this, 'access', _31 => _31.config, 'access', _32 => _32.onSessionExpired, 'optionalCall', _33 => _33()]),!1}}isRefreshing(){return this.isRefreshingLocally}setupResponseInterceptor(){_crudifysdk2.default.setResponseInterceptor(async t=>{this.updateLastActivity();let e=this.detectAuthorizationError(t);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"}),t;e.shouldTriggerLogout&&(await v.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 t}),this.log("Response interceptor configured (non-blocking mode)")}async ensureCrudifyInitialized(){if(!this.crudifyInitialized)try{this.log("Initializing crudify SDK...");let t=_crudifysdk2.default.getTokenData();if(t&&t.endpoint){this.log("Crudify already initialized by another service"),this.crudifyInitialized=!0;return}let e=this.config.env||"stg";_crudifysdk2.default.config(e);let i=this.config.publicApiKey,n=this.config.enableLogging?"debug":"none",s=await _crudifysdk2.default.init(i,n);if(s&&s.success===!1&&s.errors)throw new Error(`Failed to initialize crudify: ${JSON.stringify(s.errors)}`);this.crudifyInitialized=!0,this.log("Crudify SDK initialized successfully")}catch(t){throw _chunkMFYHD6S5js.a.error("[SessionManager] Failed to initialize crudify",t instanceof Error?t:{message:String(t)}),t}}detectAuthorizationError(t){let e={isAuthError:!1,isRefreshTokenInvalid:!1,isTokenRefreshFailed:!1,isTokenExpired:!1,isUnauthorized:!1,isIrrecoverable:!1,shouldTriggerLogout:!1,errorType:"",errorDetails:null,userFriendlyMessage:""};if(t.errors&&Array.isArray(t.errors)){let i=t.errors.find(n=>n.errorType==="Unauthorized"||_optionalChain([n, 'access', _34 => _34.message, 'optionalAccess', _35 => _35.includes, 'call', _36 => _36("Unauthorized")])||_optionalChain([n, 'access', _37 => _37.message, 'optionalAccess', _38 => _38.includes, 'call', _39 => _39("Not Authorized")])||_optionalChain([n, 'access', _40 => _40.message, 'optionalAccess', _41 => _41.includes, 'call', _42 => _42("NOT_AUTHORIZED")])||_optionalChain([n, 'access', _43 => _43.message, 'optionalAccess', _44 => _44.includes, 'call', _45 => _45("Token")])||_optionalChain([n, 'access', _46 => _46.message, 'optionalAccess', _47 => _47.includes, 'call', _48 => _48("TOKEN")])||_optionalChain([n, 'access', _49 => _49.message, 'optionalAccess', _50 => _50.includes, 'call', _51 => _51("Authentication")])||_optionalChain([n, 'access', _52 => _52.message, 'optionalAccess', _53 => _53.includes, 'call', _54 => _54("UNAUTHENTICATED")])||_optionalChain([n, 'access', _55 => _55.extensions, 'optionalAccess', _56 => _56.code])==="UNAUTHENTICATED"||_optionalChain([n, 'access', _57 => _57.extensions, 'optionalAccess', _58 => _58.code])==="FORBIDDEN");i&&(e.isAuthError=!0,e.errorType="GraphQL Array",e.errorDetails=i,e.shouldTriggerLogout=!0,e.userFriendlyMessage="Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente.",(_optionalChain([i, 'access', _59 => _59.message, 'optionalAccess', _60 => _60.includes, 'call', _61 => _61("TOKEN")])||_optionalChain([i, 'access', _62 => _62.message, 'optionalAccess', _63 => _63.includes, 'call', _64 => _64("Token")]))&&(e.isTokenExpired=!0),_optionalChain([i, 'access', _65 => _65.extensions, 'optionalAccess', _66 => _66.code])==="UNAUTHENTICATED"&&(e.isUnauthorized=!0))}if(!e.isAuthError&&t.errors&&typeof t.errors=="object"&&!Array.isArray(t.errors)){let n=Object.values(t.errors).flat().find(s=>typeof s=="string"&&(s.includes("NOT_AUTHORIZED")||s.includes("TOKEN_REFRESH_FAILED")||s.includes("TOKEN_HAS_EXPIRED")||s.includes("PLEASE_LOGIN")||s.includes("Unauthorized")||s.includes("UNAUTHENTICATED")||s.includes("SESSION_EXPIRED")||s.includes("INVALID_TOKEN")));n&&typeof n=="string"&&(e.isAuthError=!0,e.errorType="GraphQL Object",e.errorDetails=t.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([t, 'access', _67 => _67.data, 'optionalAccess', _68 => _68.response, 'optionalAccess', _69 => _69.status])){let i=t.data.response.status.toUpperCase();(i==="UNAUTHORIZED"||i==="UNAUTHENTICATED")&&(e.isAuthError=!0,e.errorType="Status",e.errorDetails=t.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([t, 'access', _70 => _70.data, 'optionalAccess', _71 => _71.response, 'optionalAccess', _72 => _72.data]))try{let i=typeof t.data.response.data=="string"?JSON.parse(t.data.response.data):t.data.response.data;(i.error==="REFRESH_TOKEN_INVALID"||i.error==="TOKEN_EXPIRED"||i.error==="INVALID_TOKEN")&&(e.isAuthError=!0,e.errorType="Parsed Data",e.errorDetails=i,e.shouldTriggerLogout=!0,e.isIrrecoverable=!0,i.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&&t.errorCode){let i=String(t.errorCode).toUpperCase();(i==="UNAUTHORIZED"||i==="UNAUTHENTICATED"||i==="TOKEN_EXPIRED"||i==="INVALID_TOKEN")&&(e.isAuthError=!0,e.errorType="Error Code",e.errorDetails={errorCode:i},e.shouldTriggerLogout=!0,i==="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 t=this.getTimeSinceLastActivity();if(this.lastActivityTime===0)return"none";let e=1800*1e3;return t>e?(this.log(`Inactivity timeout: ${Math.floor(t/6e4)} minutes since last activity`),"logout"):"none"}async clearSession(){await v.clearTokens(),await _crudifysdk2.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(t,e){this.config.enableLogging&&_chunkMFYHD6S5js.a.debug(`[SessionManager] ${t}`,e)}formatError(t){return t?typeof t=="string"?t:typeof t=="object"?Object.values(t).flat().map(String).join(", "):"Authentication failed":"Unknown error"}};var _react = require('react'); var _react2 = _interopRequireDefault(_react);var Ke={isAuthenticated:!1,isLoading:!0,isLoggingOut:!1,isInitialized:!1,tokens:null,error:null};function Me(){let[r,t]=_react.useState.call(void 0, Ke),e=_react.useCallback.call(void 0, o=>{t(f=>({...f,isLoading:o}))},[]),i=_react.useCallback.call(void 0, (o,f)=>{t(E=>({...E,isAuthenticated:o,tokens:f,error:o?null:E.error}))},[]),n=_react.useCallback.call(void 0, o=>{t(f=>({...f,isLoggingOut:o}))},[]),s=_react.useCallback.call(void 0, o=>{t(f=>({...f,error:o}))},[]),l=_react.useCallback.call(void 0, o=>{t(f=>({...f,isInitialized:o}))},[]);return{state:r,setState:t,setLoading:e,setAuthenticated:i,setLoggingOut:n,setError:s,setInitialized:l}}var se={AGGRESSIVE:3e4,MODERATE:6e4,RELAXED:12e4},he={AGGRESSIVE:300*1e3,MODERATE:1800*1e3},He=.5;function Ge(r){return r?r.expiresAt-Date.now()<3e5:!1}function _e(r){return r?Math.max(0,r.expiresAt-Date.now()):0}function Ve(r){return r?Math.max(0,r.refreshExpiresAt-Date.now()):0}function $(r){return r.crudifyTokens.accessToken?{accessToken:r.crudifyTokens.accessToken,refreshToken:r.crudifyTokens.refreshToken||"",expiresAt:r.crudifyTokens.expiresAt,refreshExpiresAt:r.crudifyTokens.refreshExpiresAt}:null}function $e(r){let{sessionManager:t,stateManager:e}=r,i=_react.useCallback.call(void 0, async(o,f)=>{e.setState(E=>({...E,isLoading:!0,isLoggingOut:!1,error:null}));try{let E=await t.login(o,f);return E.success&&E.tokens?e.setState(b=>({...b,isAuthenticated:!0,tokens:E.tokens,isLoading:!1,isLoggingOut:!1,error:null})):e.setState(b=>({...b,isAuthenticated:!1,tokens:null,isLoading:!1,isLoggingOut:!1,error:null})),E}catch(E){let b=E instanceof Error?E.message:"Login failed";_chunkMFYHD6S5js.a.error("[useSession] Login error",E instanceof Error?E:{message:b});let T=b.includes("INVALID_CREDENTIALS")||b.includes("Invalid email")||b.includes("Invalid password")||b.includes("credentials");return e.setState(m=>({...m,isAuthenticated:!1,tokens:null,isLoading:!1,isLoggingOut:!1,error:T?null:b})),{success:!1,error:b}}},[t,e]),n=_react.useCallback.call(void 0, async()=>{e.setState(o=>({...o,isLoading:!0,isLoggingOut:!0}));try{await t.logout(),e.setState(o=>({...o,isAuthenticated:!1,tokens:null,isLoading:!1,error:null}))}catch(o){e.setState(f=>({...f,isAuthenticated:!1,tokens:null,isLoading:!1,error:o instanceof Error?o.message:"Logout error"}))}},[t,e]),s=_react.useCallback.call(void 0, async()=>{try{let o=await t.refreshTokens();if(o){let f=await t.getTokenInfo();e.setState(E=>({...E,tokens:$(f),error:null}))}else e.setState(f=>({...f,isAuthenticated:!1,tokens:null,error:"Token refresh failed"}));return o}catch(o){return e.setState(f=>({...f,isAuthenticated:!1,tokens:null,error:o instanceof Error?o.message:"Token refresh failed"})),!1}},[t,e]),l=_react.useCallback.call(void 0, ()=>{e.setError(null)},[e]);return{login:i,logout:n,refreshTokens:s,clearError:l}}function zt(r){return r<he.AGGRESSIVE?se.AGGRESSIVE:r<he.MODERATE?se.MODERATE:se.RELAXED}function Ye(r){let{isAuthenticated:t,tokens:e,sessionManager:i,onTokensRefreshed:n,onSessionExpired:s,onSetLoading:l,logout:o}=r,f=_react.useCallback.call(void 0, ()=>{i.updateLastActivity()},[i]);_react.useEffect.call(void 0, ()=>{if(!t||!e)return;let b=_chunkMFYHD6S5js.p.getInstance().subscribe(f);window.addEventListener("popstate",f);let T,m=!0,I=async()=>{if(!m)return;let A=(await i.getTokenInfo()).crudifyTokens.expiresIn||0,N=zt(A);T=setTimeout(async()=>{if(!m)return;if(i.isRefreshing()){I();return}let x=await i.getTokenInfo(),O=x.crudifyTokens.expiresIn||0,z=((x.crudifyTokens.expiresAt||0)-(Date.now()-O))*He;if(O>0&&O<=z)if(l(!0),await i.refreshTokens()){let Z=await i.getTokenInfo();n($(Z)),l(!1)}else n(null),s(),l(!1);i.getTimeSinceLastActivity()>18e5?await o():m&&I()},N)};return I(),()=>{m=!1,clearTimeout(T),window.removeEventListener("popstate",f),b()}},[t,e,i,f,n,s,l,o])}function Be(r){let{sessionManager:t,onTokensUpdated:e,onSessionExpired:i,onSetLoading:n,onSetError:s}=r;_react.useEffect.call(void 0, ()=>{let l=_chunkMFYHD6S5js.e.subscribe(async o=>{if(o.type==="TOKEN_EXPIRED"){if(t.isRefreshing())return;n(!0);try{if(await t.refreshTokens()){let E=await t.getTokenInfo();e($(E)),n(!1)}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)"})}}(o.type==="SESSION_EXPIRED"||o.type==="TOKEN_REFRESH_FAILED")&&(e(null),n(!1),s(_optionalChain([o, 'access', _73 => _73.details, 'optionalAccess', _74 => _74.message, 'optionalAccess', _75 => _75.toString, 'call', _76 => _76()])||"Session expired"),i())});return()=>l()},[t,e,i,n,s])}function Xe(r){let{isAuthenticated:t,onTokensUpdated:e,onSessionExpired:i}=r;_react.useEffect.call(void 0, ()=>{let n=async l=>{switch(l.type){case"SESSION_STARTED":case"TOKEN_REFRESHED":try{await v.ensureInitialized();let o=await v.getTokens();o&&(_chunkMFYHD6S5js.a.debug(`[useCrossTabSync] Syncing ${l.type} from tab ${l.tabId}`),e(o))}catch(o){_chunkMFYHD6S5js.a.warn("[useCrossTabSync] Failed to read tokens after cross-tab event",{error:o instanceof Error?o.message:String(o)})}break;case"SESSION_ENDED":try{await v.hasValidTokens()||(_chunkMFYHD6S5js.a.debug(`[useCrossTabSync] Syncing SESSION_ENDED from tab ${l.tabId}`),e(null),t&&i())}catch(o){_chunkMFYHD6S5js.a.warn("[useCrossTabSync] Failed to verify tokens after logout event",{error:o instanceof Error?o.message:String(o)})}break;case"SESSION_PING":case"SESSION_PONG":break}},s=W.subscribe(n);return()=>s()},[t,e,i]),_react.useEffect.call(void 0, ()=>{let n=v.subscribeToChanges(async(s,l,o)=>{if(l===v.SYNC_EVENTS.TOKENS_CLEARED){if(await v.hasValidTokens())return;o&&t?(e(null),i()):o&&e(null)}else l===v.SYNC_EVENTS.TOKENS_UPDATED&&s&&e(s)});return()=>n()},[t,e,i])}async function Ze(r){let{sessionManager:t,options:e,stateActions:i}=r;try{i.setState(o=>({...o,isLoading:!0,error:null}));let n={autoRestore:_nullishCoalesce(e.autoRestore, () => (!0)),enableLogging:_nullishCoalesce(e.enableLogging, () => (!1)),showNotification:e.showNotification,translateFn:e.translateFn,apiEndpointAdmin:e.apiEndpointAdmin,apiKeyEndpointAdmin:e.apiKeyEndpointAdmin,publicApiKey:e.publicApiKey,env:e.env||"stg",onSessionExpired:()=>{i.setState(o=>({...o,isAuthenticated:!1,tokens:null,error:"Session expired"})),_optionalChain([e, 'access', _77 => _77.onSessionExpired, 'optionalCall', _78 => _78()])},onSessionRestored:o=>{i.setState(f=>({...f,isAuthenticated:!0,tokens:o,error:null})),_optionalChain([e, 'access', _79 => _79.onSessionRestored, 'optionalCall', _80 => _80(o)])},onLoginSuccess:o=>{i.setState(f=>({...f,isAuthenticated:!0,tokens:o,error:null}))},onLogout:()=>{i.setState(o=>({...o,isAuthenticated:!1,tokens:null,error:null}))}};await t.initialize(n),t.setupResponseInterceptor();let s=await t.isAuthenticated(),l=await t.getTokenInfo();i.setState(o=>({...o,isAuthenticated:s,isInitialized:!0,isLoading:!1,isLoggingOut:!1,tokens:$(l)}))}catch(n){let s=n instanceof Error?n.message:"Initialization failed";_chunkMFYHD6S5js.a.error("[useSession] Initialize failed",n instanceof Error?n:{message:s}),i.setState(l=>({...l,isLoading:!1,isInitialized:!0,isLoggingOut:!1,error:s}))}}function Ee(r={}){let t=ne.getInstance(),e=Me(),{state:i}=e,{login:n,logout:s,refreshTokens:l,clearError:o}=$e({sessionManager:t,stateManager:e}),f=_react.useCallback.call(void 0, g=>{e.setAuthenticated(!!g,g)},[e]),E=_react.useCallback.call(void 0, ()=>{e.setAuthenticated(!1,null),_optionalChain([r, 'access', _81 => _81.onSessionExpired, 'optionalCall', _82 => _82()])},[e,r.onSessionExpired]),b=_react.useCallback.call(void 0, g=>{e.setLoading(g)},[e]),T=_react.useCallback.call(void 0, g=>{e.setError(g)},[e]);_react.useEffect.call(void 0, ()=>{Ze({sessionManager:t,options:r,stateActions:e})},[]),Ye({isAuthenticated:i.isAuthenticated,tokens:i.tokens,sessionManager:t,onTokensRefreshed:f,onSessionExpired:E,onSetLoading:b,logout:s}),Be({sessionManager:t,onTokensUpdated:f,onSessionExpired:E,onSetLoading:b,onSetError:T}),Xe({isAuthenticated:i.isAuthenticated,onTokensUpdated:f,onSessionExpired:E});let m=_react.useCallback.call(void 0, ()=>{t.updateLastActivity()},[t]),I=_react.useCallback.call(void 0, async()=>t.getTokenInfo(),[t]);return{...i,login:n,logout:s,refreshTokens:l,clearError:o,getTokenInfo:I,updateActivity:m,isExpiringSoon:Ge(i.tokens),expiresIn:_e(i.tokens),refreshExpiresIn:Ve(i.tokens)}}var _material = require('@mui/material');var _uuid = require('uuid');var _dompurify = require('dompurify'); var _dompurify2 = _interopRequireDefault(_dompurify);var _jsxruntime = require('react/jsx-runtime');var je=_react.createContext.call(void 0, null),Xt=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}),Te= exports.f =({children:r,maxNotifications:t=5,defaultAutoHideDuration:e=6e3,position:i={vertical:"top",horizontal:"right"},enabled:n=!1,allowHtml:s=!1})=>{let[l,o]=_react.useState.call(void 0, []),f=_react.useCallback.call(void 0, (m,I="info",g)=>{if(!n)return"";if(!m||typeof m!="string")return _chunkMFYHD6S5js.a.warn("GlobalNotificationProvider: Invalid message provided"),"";m.length>1e3&&(_chunkMFYHD6S5js.a.warn("GlobalNotificationProvider: Message too long, truncating"),m=m.substring(0,1e3)+"...");let A=_uuid.v4.call(void 0, ),N={id:A,message:m,severity:I,autoHideDuration:_nullishCoalesce(_optionalChain([g, 'optionalAccess', _83 => _83.autoHideDuration]), () => (e)),persistent:_nullishCoalesce(_optionalChain([g, 'optionalAccess', _84 => _84.persistent]), () => (!1)),allowHtml:_nullishCoalesce(_optionalChain([g, 'optionalAccess', _85 => _85.allowHtml]), () => (s))};return o(x=>[...x.length>=t?x.slice(-(t-1)):x,N]),A},[t,e,n,s]),E=_react.useCallback.call(void 0, m=>{o(I=>I.filter(g=>g.id!==m))},[]),b=_react.useCallback.call(void 0, ()=>{o([])},[]),T={showNotification:f,hideNotification:E,clearAllNotifications:b};return _jsxruntime.jsxs.call(void 0, je.Provider,{value:T,children:[r,n&&_jsxruntime.jsx.call(void 0, _material.Portal,{children:_jsxruntime.jsx.call(void 0, _material.Box,{sx:{position:"fixed",zIndex:9999,[i.vertical]:(i.vertical==="top",24),[i.horizontal]:i.horizontal==="right"||i.horizontal==="left"?24:"50%",...i.horizontal==="center"&&{transform:"translateX(-50%)"},display:"flex",flexDirection:i.vertical==="top"?"column":"column-reverse",gap:1,maxWidth:"400px",width:"auto"},children:l.map(m=>_jsxruntime.jsx.call(void 0, Zt,{notification:m,onClose:()=>E(m.id)},m.id))})})]})},Zt=({notification:r,onClose:t})=>{let[e,i]=_react.useState.call(void 0, !0),n=_react.useCallback.call(void 0, (s,l)=>{l!=="clickaway"&&(i(!1),setTimeout(t,300))},[t]);return _react.useEffect.call(void 0, ()=>{if(!r.persistent&&r.autoHideDuration){let s=setTimeout(()=>{n()},r.autoHideDuration);return()=>clearTimeout(s)}},[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:Xt(r.message)}}):_jsxruntime.jsx.call(void 0, "span",{children:r.message})})})},Je= exports.g =()=>{let r=_react.useContext.call(void 0, je);if(!r)throw new Error("useGlobalNotification debe ser usado dentro de un GlobalNotificationProvider");return r};var Se=class r{constructor(){this.listeners=[];this.credentials=null;this.isReady=!1}static getInstance(){return r.instance||(r.instance=new r),r.instance}notifyCredentialsReady(t){this.credentials=t,this.isReady=!0,this.listeners.forEach(e=>{try{e(t)}catch(i){_chunkMFYHD6S5js.a.error("[CredentialsEventBus] Error in listener",i instanceof Error?i:{message:String(i)})}}),this.listeners=[]}waitForCredentials(){return this.isReady&&this.credentials?Promise.resolve(this.credentials):new Promise(t=>{this.listeners.push(t)})}reset(){this.credentials=null,this.isReady=!1,this.listeners=[]}areCredentialsReady(){return this.isReady&&this.credentials!==null}},le= exports.h =Se.getInstance();var Qe=_react.createContext.call(void 0, void 0),et= exports.i =({config:r,children:t})=>{let[e,i]=_react.useState.call(void 0, !0),[n,s]=_react.useState.call(void 0, null),[l,o]=_react.useState.call(void 0, !1),[f,E]=_react.useState.call(void 0, ""),[b,T]=_react.useState.call(void 0, );_react.useEffect.call(void 0, ()=>{if(!r.publicApiKey){s("No publicApiKey provided"),i(!1),o(!1);return}let I=`${r.publicApiKey}-${r.env}`;if(I===f&&l){i(!1);return}(async()=>{i(!0),s(null),o(!1);try{_crudifysdk2.default.config(r.env||"prod");let A=await _crudifysdk2.default.init(r.publicApiKey,"none");if(T(A),typeof _crudifysdk2.default.transaction=="function"&&typeof _crudifysdk2.default.login=="function")o(!0),E(I),A.apiEndpointAdmin&&A.apiKeyEndpointAdmin&&le.notifyCredentialsReady({apiUrl:A.apiEndpointAdmin,apiKey:A.apiKeyEndpointAdmin});else throw new Error("Crudify methods not properly initialized")}catch(A){let N=A instanceof Error?A.message:"Failed to initialize Crudify";_chunkMFYHD6S5js.a.error("[CrudifyProvider] Initialization error",A instanceof Error?A:{message:String(A)}),s(N),o(!1)}finally{i(!1)}})()},[r.publicApiKey,r.env,f,l]);let m={crudify:l?_crudifysdk2.default:null,isLoading:e,error:n,isInitialized:l,adminCredentials:b};return _jsxruntime.jsx.call(void 0, Qe.Provider,{value:m,children:t})},tt= exports.j =()=>{let r=_react.useContext.call(void 0, Qe);if(r===void 0)throw new Error("useCrudify must be used within a CrudifyProvider");return r};var rt=_react.createContext.call(void 0, void 0);function it({children:r,options:t={},config:e,showNotifications:i=!1,notificationOptions:n={}}){let s;try{let{showNotification:g}=Je();s=g}catch (e10){}let l={};try{let g=tt();g.isInitialized&&g.adminCredentials&&(l=g.adminCredentials)}catch (e11){}let o=_react.useMemo.call(void 0, ()=>{let g=_chunkMFYHD6S5js.c.call(void 0, {publicApiKey:_optionalChain([e, 'optionalAccess', _86 => _86.publicApiKey]),env:_optionalChain([e, 'optionalAccess', _87 => _87.env]),enableDebug:_optionalChain([t, 'optionalAccess', _88 => _88.enableLogging])});return{publicApiKey:g.publicApiKey,env:g.env||"prod"}},[e,_optionalChain([t, 'optionalAccess', _89 => _89.enableLogging])]),f=_react2.default.useMemo(()=>({...t,showNotification:s,apiEndpointAdmin:l.apiEndpointAdmin,apiKeyEndpointAdmin:l.apiKeyEndpointAdmin,publicApiKey:o.publicApiKey,env:o.env,onSessionExpired:()=>{_optionalChain([t, 'access', _90 => _90.onSessionExpired, 'optionalCall', _91 => _91()])}}),[t,s,l.apiEndpointAdmin,l.apiKeyEndpointAdmin,o]),E=Ee(f),b=_react.useMemo.call(void 0, ()=>{let g=_chunkMFYHD6S5js.c.call(void 0, {publicApiKey:_optionalChain([e, 'optionalAccess', _92 => _92.publicApiKey]),env:_optionalChain([e, 'optionalAccess', _93 => _93.env]),appName:_optionalChain([e, 'optionalAccess', _94 => _94.appName]),logo:_optionalChain([e, 'optionalAccess', _95 => _95.logo]),loginActions:_optionalChain([e, 'optionalAccess', _96 => _96.loginActions]),enableDebug:_optionalChain([t, 'optionalAccess', _97 => _97.enableLogging])});return{publicApiKey:g.publicApiKey,env:g.env,appName:g.appName,loginActions:g.loginActions,logo:g.logo}},[e,_optionalChain([t, 'optionalAccess', _98 => _98.enableLogging])]),T=_react.useMemo.call(void 0, ()=>{if(!_optionalChain([E, 'access', _99 => _99.tokens, 'optionalAccess', _100 => _100.accessToken])||!E.isAuthenticated)return null;try{let g=_chunkMFYHD6S5js.q.call(void 0, E.tokens.accessToken);if(g&&g.sub&&g.email&&g.subscriber){let A={_id:g.sub,email:g.email,subscriberKey:g.subscriber};return Object.keys(g).forEach(N=>{["sub","email","subscriber"].includes(N)||(A[N]=g[N])}),A}}catch(g){_chunkMFYHD6S5js.a.error("Error decoding JWT token for sessionData",g instanceof Error?g:{message:String(g)})}return null},[_optionalChain([E, 'access', _101 => _101.tokens, 'optionalAccess', _102 => _102.accessToken]),E.isAuthenticated]),m={...E,sessionData:T,config:b},I={enabled:i,maxNotifications:n.maxNotifications||5,defaultAutoHideDuration:n.defaultAutoHideDuration||6e3,position:n.position||{vertical:"top",horizontal:"right"}};return _jsxruntime.jsx.call(void 0, rt.Provider,{value:m,children:r})}function Vr(r){let t={enabled:r.showNotifications,maxNotifications:_optionalChain([r, 'access', _103 => _103.notificationOptions, 'optionalAccess', _104 => _104.maxNotifications])||5,defaultAutoHideDuration:_optionalChain([r, 'access', _105 => _105.notificationOptions, 'optionalAccess', _106 => _106.defaultAutoHideDuration])||6e3,position:_optionalChain([r, 'access', _107 => _107.notificationOptions, 'optionalAccess', _108 => _108.position])||{vertical:"top",horizontal:"right"},allowHtml:_optionalChain([r, 'access', _109 => _109.notificationOptions, 'optionalAccess', _110 => _110.allowHtml])||!1};return _optionalChain([r, 'access', _111 => _111.config, 'optionalAccess', _112 => _112.publicApiKey])?_jsxruntime.jsx.call(void 0, et,{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, Te,{...t,children:_jsxruntime.jsx.call(void 0, it,{...r})})}):_jsxruntime.jsx.call(void 0, Te,{...t,children:_jsxruntime.jsx.call(void 0, it,{...r})})}function ni(){let r=_react.useContext.call(void 0, rt);if(r===void 0)throw new Error("useSessionContext must be used within a SessionProvider");return r}function $r(){let r=ni();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 qr=(r={})=>{let{autoFetch:t=!0,retryOnError:e=!1,maxRetries:i=3}=r,[n,s]=_react.useState.call(void 0, null),[l,o]=_react.useState.call(void 0, !1),[f,E]=_react.useState.call(void 0, null),[b,T]=_react.useState.call(void 0, {}),m=_react.useRef.call(void 0, null),I=_react.useRef.call(void 0, !0),g=_react.useRef.call(void 0, 0),A=_react.useRef.call(void 0, 0),N=_react.useCallback.call(void 0, ()=>{s(null),E(null),o(!1),T({})},[]),x=_react.useCallback.call(void 0, async()=>{let O=_chunkMFYHD6S5js.r.call(void 0, );if(!O){I.current&&(E("No user email available"),o(!1));return}m.current&&m.current.abort();let w=new AbortController;m.current=w;let F=++g.current;try{I.current&&(o(!0),E(null));let z=await _crudifysdk2.default.readItems("users",{filter:{email:O},pagination:{limit:1}});if(F===g.current&&I.current&&!w.signal.aborted){let D=z.data;if(z.success&&D&&D.length>0){let S=D[0];s(S);let Z={fullProfile:S,totalFields:Object.keys(S).length,displayData:{id:S.id,email:S.email,username:S.username,firstName:S.firstName,lastName:S.lastName,fullName:S.fullName||`${S.firstName||""} ${S.lastName||""}`.trim(),role:S.role,permissions:S.permissions||[],isActive:S.isActive,lastLogin:S.lastLogin,createdAt:S.createdAt,updatedAt:S.updatedAt,...Object.keys(S).filter(V=>!["id","email","username","firstName","lastName","fullName","role","permissions","isActive","lastLogin","createdAt","updatedAt"].includes(V)).reduce((V,re)=>({...V,[re]:S[re]}),{})}};T(Z),E(null),A.current=0}else E("User profile not found"),s(null),T({})}}catch(z){if(F===g.current&&I.current){let D=z;if(D.name==="AbortError")return;e&&A.current<i&&(_optionalChain([D, 'access', _113 => _113.message, 'optionalAccess', _114 => _114.includes, 'call', _115 => _115("Network Error")])||_optionalChain([D, 'access', _116 => _116.message, 'optionalAccess', _117 => _117.includes, 'call', _118 => _118("Failed to fetch")]))?(A.current++,setTimeout(()=>{I.current&&x()},1e3*A.current)):(E("Failed to load user profile"),s(null),T({}))}}finally{F===g.current&&I.current&&o(!1),m.current===w&&(m.current=null)}},[e,i]);return _react.useEffect.call(void 0, ()=>{t&&x()},[t,x]),_react.useEffect.call(void 0, ()=>(I.current=!0,()=>{I.current=!1,m.current&&(m.current.abort(),m.current=null)}),[]),{userProfile:n,loading:l,error:f,extendedData:b,refreshProfile:x,clearProfile:N}};var en=(r,t={})=>{let{autoFetch:e=!0,onSuccess:i,onError:n}=t,{prefix:s,padding:l=0,separator:o=""}=r,[f,E]=_react.useState.call(void 0, ""),[b,T]=_react.useState.call(void 0, !1),[m,I]=_react.useState.call(void 0, null),g=_react.useRef.call(void 0, !1),A=_react.useCallback.call(void 0, w=>{let F=String(w).padStart(l,"0");return`${s}${o}${F}`},[s,l,o]),N=_react.useCallback.call(void 0, async()=>{T(!0),I(null);try{let w=await _crudifysdk2.default.getNextSequence(s),F=w.data;if(w.success&&_optionalChain([F, 'optionalAccess', _119 => _119.value])){let z=A(F.value);E(z),_optionalChain([i, 'optionalCall', _120 => _120(z)])}else{let z=_optionalChain([w, 'access', _121 => _121.errors, 'optionalAccess', _122 => _122._error, 'optionalAccess', _123 => _123[0]])||"Failed to generate code";I(z),_optionalChain([n, 'optionalCall', _124 => _124(z)])}}catch(w){let F=w instanceof Error?w.message:"Unknown error";I(F),_optionalChain([n, 'optionalCall', _125 => _125(F)])}finally{T(!1)}},[s,A,i,n]),x=_react.useCallback.call(void 0, async()=>{await N()},[N]),O=_react.useCallback.call(void 0, ()=>{I(null)},[]);return _react.useEffect.call(void 0, ()=>{e&&!f&&!g.current&&(g.current=!0,N())},[e,f,N]),{value:f,loading:b,error:m,regenerate:x,clearError:O}};var Ae=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(t){let{priority:e,publicApiKey:i,env:n,enableLogging:s,requestedBy:l}=t;if(this.state.status==="INITIALIZED"){this.state.publicApiKey!==i&&_chunkMFYHD6S5js.a.warn(`[CrudifyInitialization] ${l} attempted to initialize with different key. Already initialized with key: ${_optionalChain([this, 'access', _126 => _126.state, 'access', _127 => _127.publicApiKey, 'optionalAccess', _128 => _128.slice, 'call', _129 => _129(0,10)])}... by ${this.state.initializedBy}`);return}if(this.initializationPromise)return s&&_chunkMFYHD6S5js.a.debug(`[CrudifyInitialization] ${l} waiting for ongoing initialization...`),this.initializationPromise;if(e==="LOW"&&this.highPriorityInitializerPresent&&this.state.status==="UNINITIALIZED"){if(s&&_chunkMFYHD6S5js.a.debug(`[CrudifyInitialization] ${l} (LOW priority) waiting for HIGH priority initializer...`),this.waitingForHighPriority.add(l),await this.waitForHighPriorityOrTimeout(s),this.waitingForHighPriority.delete(l),this.getState().status==="INITIALIZED"){s&&_chunkMFYHD6S5js.a.debug(`[CrudifyInitialization] ${l} found initialization completed by HIGH priority`);return}s&&_chunkMFYHD6S5js.a.warn(`[CrudifyInitialization] ${l} 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 ${l} interrupting LOW priority initialization by ${this.state.initializedBy}`),this.state.status="UNINITIALIZED",this.initializationPromise=null),s&&_chunkMFYHD6S5js.a.debug(`[CrudifyInitialization] ${l} starting initialization (${e} priority)...`),this.state.status="INITIALIZING",this.state.priority=e,this.state.initializedBy=l,this.initializationPromise=this.performInitialization(i,n,s);try{await this.initializationPromise,this.state.status="INITIALIZED",this.state.publicApiKey=i,this.state.env=n,this.state.error=null,s&&_chunkMFYHD6S5js.a.info(`[CrudifyInitialization] Successfully initialized by ${l} (${e} priority)`)}catch(o){throw this.state.status="ERROR",this.state.error=o instanceof Error?o:new Error(String(o)),this.initializationPromise=null,_chunkMFYHD6S5js.a.error(`[CrudifyInitialization] Initialization failed for ${l}`,o instanceof Error?o:{message:String(o)}),o}}async waitForHighPriorityOrTimeout(t){return new Promise(e=>{let n=0,s=setInterval(()=>{if(n+=10,this.state.status==="INITIALIZED"&&this.state.priority==="HIGH"){clearInterval(s),e();return}if(this.state.status==="INITIALIZING"&&this.state.priority==="HIGH"){n=0;return}n>=this.HIGH_PRIORITY_WAIT_TIMEOUT&&(clearInterval(s),t&&_chunkMFYHD6S5js.a.debug(`[CrudifyInitialization] Timeout waiting for HIGH priority (${this.HIGH_PRIORITY_WAIT_TIMEOUT}ms)`),e())},10)})}async performInitialization(t,e,i){let n=_crudifysdk2.default.getTokenData();if(n&&n.endpoint){i&&_chunkMFYHD6S5js.a.debug("[CrudifyInitialization] SDK already initialized externally");return}_crudifysdk2.default.config(e);let s=i?"debug":"none",l=await _crudifysdk2.default.init(t,s);if(l.success===!1)throw new Error(`Crudify initialization failed: ${JSON.stringify(l.errors||"Unknown error")}`);l.apiEndpointAdmin&&l.apiKeyEndpointAdmin&&le.notifyCredentialsReady({apiUrl:l.apiEndpointAdmin,apiKey:l.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}}},ie= exports.q =Ae.getInstance();var at=r=>{let t=new Uint8Array(r);return crypto.getRandomValues(t),Array.from(t,e=>e.toString(36).padStart(2,"0")).join("").substring(0,r)},ot=()=>`file_${Date.now()}_${at(7)}`,di=r=>{let t=r.lastIndexOf("."),e=t>0?r.substring(t):"",i=Date.now(),n=at(6);return`${i}_${n}${e}`},ke=(r,t)=>{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(t&&r.startsWith(t))return r.substring(t.length)}return t&&r.startsWith(t)?r.substring(t.length):r},dn= exports.r =(r={})=>{let{acceptedTypes:t,maxFileSize:e=10*1024*1024,maxFiles:i,minFiles:n=0,visibility:s="private",onUploadComplete:l,onUploadError:o,onFileRemoved:f,onFilesChange:E,mode:b="edit"}=r,[T,m]=_react.useState.call(void 0, []),[I,g]=_react.useState.call(void 0, !1),[A,N]=_react.useState.call(void 0, !1),[x,O]=_react.useState.call(void 0, []),w=_react.useRef.call(void 0, new Map),F=_react.useCallback.call(void 0, ()=>{g(!0)},[]),z=_react.useCallback.call(void 0, ()=>{N(!0),g(!0)},[]),D=_react.useCallback.call(void 0, (c,p)=>{m(d=>d.map(h=>h.id===c?{...h,...p}:h))},[]),S=_react.useCallback.call(void 0, c=>{_optionalChain([E, 'optionalCall', _130 => _130(c)])},[E]),Z=_react.useCallback.call(void 0, c=>t&&t.length>0&&!t.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},[t,e]),V=_react.useCallback.call(void 0, async(c,p)=>{try{if(!ie.isInitialized())throw new Error("Crudify is not initialized. Please wait for the application to finish loading.");let d=di(p.name),y=await _crudifysdk2.default.generateSignedUrl({fileName:d,contentType:p.type,visibility:s});if(!y.success||!y.data)throw new Error("Failed to get upload URL");let h=y.data,{uploadUrl:R,s3Key:k,publicUrl:M}=h;if(!R||!k)throw new Error("Incomplete signed URL response");let Y=k.indexOf("/"),Rt=Y>0?k.substring(Y+1):k;D(c.id,{status:"uploading",progress:0}),await new Promise((pe,B)=>{let U=new XMLHttpRequest;U.upload.addEventListener("progress",_=>{if(_.lengthComputable){let Ct=Math.round(_.loaded/_.total*100);D(c.id,{progress:Ct})}}),U.addEventListener("load",()=>{U.status>=200&&U.status<300?pe():B(new Error(`Upload failed with status ${U.status}`))}),U.addEventListener("error",()=>{B(new Error("Network error during upload"))}),U.addEventListener("abort",()=>{B(new Error("Upload cancelled"))}),U.open("PUT",R),U.setRequestHeader("Content-Type",p.type),U.send(p)});let Nt={status:"completed",progress:100,filePath:Rt,visibility:s,publicUrl:s==="public"?M:void 0,file:void 0};m(pe=>{let B=pe.map(_=>_.id===c.id?{..._,...Nt}:_);S(B);let U=B.find(_=>_.id===c.id);return U&&_optionalChain([l, 'optionalCall', _131 => _131(U)]),B})}catch(d){let y=d instanceof Error?d.message:"Unknown error";D(c.id,{status:"error",progress:0,errorMessage:y}),m(h=>{let R=h.find(k=>k.id===c.id);return R&&_optionalChain([o, 'optionalCall', _132 => _132(R,y)]),h})}},[D,l,o,s]),re=_react.useCallback.call(void 0, async c=>{let p=Array.from(c),d=[];m(y=>{if(i!==void 0){let k=y.filter(Y=>Y.status!=="pendingDeletion"&&Y.status!=="error").length,M=i-k;if(M<=0)return _chunkMFYHD6S5js.a.warn(`File limit of ${i} already reached`),y;p.length>M&&(p=p.slice(0,M),_chunkMFYHD6S5js.a.warn(`Only ${M} files will be added to not exceed limit`))}let h=[];for(let k of p){let M=Z(k),Y={id:ot(),name:k.name,size:k.size,contentType:k.type,status:M.valid?"pending":"error",progress:0,createdAt:Date.now(),file:M.valid?k:void 0,errorMessage:M.error,isExisting:!1};h.push(Y)}d=h;let R=[...y,...h];return S(R),R}),setTimeout(()=>{let y=d.filter(h=>h.status==="pending"&&h.file);for(let h of y)if(h.file){let R=V(h,h.file);w.current.set(h.id,R),R.finally(()=>{w.current.delete(h.id)})}},0)},[i,Z,V,S]),lt=_react.useCallback.call(void 0, async c=>{let p=T.find(y=>y.id===c);if(!p)return{needsConfirmation:!1,isExisting:!1};let d=p.isExisting===!0;return b==="create"||!d?{needsConfirmation:!0,isExisting:d}:(O(y=>[...y,c]),m(y=>{let h=y.map(k=>k.id===c?{...k,status:"pendingDeletion"}:k),R=h.filter(k=>k.status!=="pendingDeletion");return S(R),h}),{needsConfirmation:!1,isExisting:d})},[T,b,S]),ct=_react.useCallback.call(void 0, async c=>{let p=T.find(d=>d.id===c);if(!p)return{success:!1,error:"File not found"};if(!p.filePath)return m(d=>{let y=d.filter(h=>h.id!==c);return S(y),y}),{success:!0};try{if(!ie.isInitialized())return{success:!1,error:"Crudify not initialized"};let d=ke(p.filePath);return(await _crudifysdk2.default.disableFile({filePath:d})).success?(m(h=>{let R=h.filter(k=>k.id!==c);return S(R),R}),_optionalChain([f, 'optionalCall', _133 => _133(p)]),{success:!0}):{success:!1,error:"Failed to delete file"}}catch(d){return{success:!1,error:d instanceof Error?d.message:"Unknown error"}}},[T,S,f]),ut=_react.useCallback.call(void 0, c=>{let p=T.find(d=>d.id===c);return!p||!p.isExisting?!1:(O(d=>d.filter(y=>y!==c)),m(d=>{let y=d.map(h=>h.id===c?{...h,status:"completed"}:h);return S(y),y}),!0)},[T,S]),dt=_react.useCallback.call(void 0, ()=>{x.length!==0&&(m(c=>{let p=c.map(d=>x.includes(d.id)?{...d,status:"completed"}:d);return S(p),p}),O([]))},[x,S]),ft=_react.useCallback.call(void 0, async()=>{if(x.length===0)return{success:!0,errors:[]};let c=[],p=[];if(!ie.isInitialized())return{success:!1,errors:["Crudify is not initialized. Please wait for the application to finish loading."]};for(let d of x){let y=T.find(h=>h.id===d);if(!_optionalChain([y, 'optionalAccess', _134 => _134.filePath])){p.push(d);continue}try{let h=ke(y.filePath);(await _crudifysdk2.default.disableFile({filePath:h})).success?(p.push(d),_optionalChain([f, 'optionalCall', _135 => _135(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&&(m(d=>d.filter(h=>!p.includes(h.id))),O(d=>d.filter(y=>!p.includes(y)))),{success:c.length===0,errors:c}},[T,x,f]),gt=_react.useCallback.call(void 0, ()=>{m([]),S([])},[S]),pt=_react.useCallback.call(void 0, async c=>{let p=T.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}D(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)})},[T,D,V]),mt=_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(()=>{m(d=>{let y=d.filter(h=>h.status==="completed"&&h.filePath).map(h=>h.filePath);return p(y),d})},0)})},[]),yt=c=>{let p=_optionalChain([c, 'access', _136 => _136.split, 'call', _137 => _137("."), 'access', _138 => _138.pop, 'call', _139 => _139(), 'optionalAccess', _140 => _140.toLowerCase, 'call', _141 => _141()])||"";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"},ht=_react.useCallback.call(void 0, (c,p)=>{let d=c.map(y=>{let h=ke(y.filePath,p),R=h.includes("/public/")||h.startsWith("public/")?"public":"private",k=y.contentType||yt(y.name);return{id:ot(),name:y.name,size:y.size||0,contentType:k,status:"completed",progress:100,filePath:h,visibility:R,createdAt:Date.now(),isExisting:!0}});m(d),S(d)},[S]),Et=_react.useCallback.call(void 0, async c=>{let p=T.find(d=>d.id===c);if(!p||!p.filePath)return null;if(p.visibility==="public"&&p.publicUrl)return p.publicUrl;try{if(!ie.isInitialized())return null;let d=await _crudifysdk2.default.getFileUrl({filePath:p.filePath,expiresIn:3600}),y=d.data;return d.success&&_optionalChain([y, 'optionalAccess', _142 => _142.url])?y.url:null}catch (e13){return null}},[T]),Tt=_react.useMemo.call(void 0, ()=>T.some(c=>c.status==="uploading"||c.status==="pending"),[T]),St=_react.useMemo.call(void 0, ()=>T.filter(c=>c.status==="uploading"||c.status==="pending").length,[T]),vt=_react.useMemo.call(void 0, ()=>T.filter(c=>c.status==="completed"&&c.filePath).map(c=>c.filePath),[T]),q=_react.useMemo.call(void 0, ()=>T.filter(c=>c.status!=="pendingDeletion"),[T]),bt=_react.useMemo.call(void 0, ()=>q.filter(c=>c.status==="completed"||c.status==="pending"||c.status==="uploading").length,[q]),{isValid:It,validationError:At,validationErrorKey:kt,validationErrorParams:xt}=_react.useMemo.call(void 0, ()=>{let c=q.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 i!==void 0&&c>i?{isValid:!1,validationError:"file.validation.maxFilesExceeded",validationErrorKey:"file.validation.maxFilesExceeded",validationErrorParams:{count:i}}:q.some(d=>d.status==="error")?{isValid:!1,validationError:"file.validation.filesWithErrors",validationErrorKey:"file.validation.filesWithErrors",validationErrorParams:{}}:{isValid:!0,validationError:null,validationErrorKey:null,validationErrorParams:{}}},[q,n,i]),wt=x.length>0;return{files:T,activeFiles:q,activeFileCount:bt,isUploading:Tt,pendingCount:St,addFiles:re,removeFile:lt,deleteFileImmediately:ct,restoreFile:ut,clearFiles:gt,retryUpload:pt,isValid:It,validationError:At,validationErrorKey:kt,validationErrorParams:xt,waitForUploads:mt,completedFilePaths:vt,initializeFiles:ht,isTouched:I,markAsTouched:F,isSubmitted:A,markAsSubmitted:z,getPreviewUrl:Et,pendingDeletions:x,hasPendingDeletions:wt,commitDeletions:ft,restorePendingDeletions:dt}};exports.a = v; exports.b = ye; exports.c = W; exports.d = ne; exports.e = Ee; exports.f = Te; exports.g = Je; exports.h = le; exports.i = et; exports.j = tt; exports.k = Vr; exports.l = ni; exports.m = $r; exports.n = qr; exports.o = en; exports.p = Ae; exports.q = ie; exports.r = dn;
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 _chunkCR5KJUSTjs = require('./chunk-CR5KJUST.js');var ze="crudify_storage_version",Ue=2,a=class a{static setStorageType(t){a.storageType=t}static async initialize(){if(!(a.encryptionKey&&a.salt))return a.initPromise||(a.initPromise=(async()=>{let e=null;for(let i=1;i<=3;i++)try{a.checkStorageVersion(),a.salt=a.getOrCreateSalt(),a.fingerprint=await a.generateFingerprint(),a.encryptionKey=await _chunkCR5KJUSTjs.h.call(void 0, a.fingerprint,a.salt);return}catch(n){e=n instanceof Error?n:new Error(String(n)),i<3&&await new Promise(s=>setTimeout(s,100*i))}throw _chunkCR5KJUSTjs.a.error("Crudify: Failed to initialize encryption after retries",_nullishCoalesce(e, () => ({message:"Unknown error"}))),e})()),a.initPromise}static checkStorageVersion(){try{if(parseInt(localStorage.getItem(ze)||"1",10)<Ue){let e=a.getStorage();e&&e.removeItem(a.TOKEN_KEY),localStorage.removeItem(a.ENCRYPTION_KEY_STORAGE),localStorage.removeItem(a.SALT_KEY),localStorage.setItem(ze,Ue.toString()),_chunkCR5KJUSTjs.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 i=atob(e),n=new Uint8Array(i.length);for(let s=0;s<i.length;s++)n[s]=i.charCodeAt(s);return n}}catch (e3){}let t=_chunkCR5KJUSTjs.k.call(void 0, );try{let e="";for(let i=0;i<t.length;i++)e+=String.fromCharCode(t[i]);localStorage.setItem(a.SALT_KEY,btoa(e))}catch (e4){_chunkCR5KJUSTjs.a.warn("Crudify: Cannot persist salt, encryption may not persist across sessions")}return t}static async generateFingerprint(){try{let n=localStorage.getItem(a.ENCRYPTION_KEY_STORAGE);if(n&&n.length>=32)return n}catch (e5){}let e=[navigator.userAgent,navigator.language,navigator.platform||"unknown",String(screen.width),String(screen.height),String(screen.colorDepth||24),String(new Date().getTimezoneOffset()),"crudify-session-v3"].join("|"),i=await _chunkCR5KJUSTjs.g.call(void 0, e);try{localStorage.setItem(a.ENCRYPTION_KEY_STORAGE,i)}catch (e6){_chunkCR5KJUSTjs.a.warn("Crudify: Cannot persist encryption key hash, session may not survive page reload")}return i}static isStorageAvailable(t){try{let e=window[t],i="__storage_test__";return e.setItem(i,"test"),e.removeItem(i),!0}catch (e7){return!1}}static getStorage(){return a.storageType==="none"?null:a.isStorageAvailable(a.storageType)?window[a.storageType]:(_chunkCR5KJUSTjs.a.warn(`Crudify: ${a.storageType} not available, tokens won't persist`),null)}static async encryptData(t){if(await a.initialize(),!a.encryptionKey||!a.salt)throw new Error("Encryption not initialized");return _chunkCR5KJUSTjs.i.call(void 0, t,a.encryptionKey,a.salt)}static async decryptData(t){if(await a.initialize(),!a.fingerprint)throw new Error("Encryption not initialized");return _chunkCR5KJUSTjs.l.call(void 0, t)?_chunkCR5KJUSTjs.j.call(void 0, t,a.fingerprint):(_chunkCR5KJUSTjs.a.warn("Crudify: Legacy encrypted data detected, cannot decrypt"),null)}static async saveTokens(t){let e=a.getStorage();if(e)try{let i={accessToken:t.accessToken,refreshToken:t.refreshToken,expiresAt:t.expiresAt,refreshExpiresAt:t.refreshExpiresAt,savedAt:Date.now()},n=await a.encryptData(JSON.stringify(i));e.setItem(a.TOKEN_KEY,n),_chunkCR5KJUSTjs.a.debug("Crudify: Tokens saved successfully")}catch(i){_chunkCR5KJUSTjs.a.error("Crudify: Failed to save tokens",i instanceof Error?i:{message:String(i)})}}static async getTokens(){let t=a.getStorage();if(!t)return null;try{let e=t.getItem(a.TOKEN_KEY);if(!e)return null;let i=await a.decryptData(e);if(!i)return _chunkCR5KJUSTjs.a.warn("Crudify: Failed to decrypt tokens, clearing storage"),await a.clearTokens(),null;let n=JSON.parse(i);return!n.accessToken||!n.refreshToken||!n.expiresAt||!n.refreshExpiresAt?(_chunkCR5KJUSTjs.a.warn("Crudify: Incomplete token data found, clearing storage"),await a.clearTokens(),null):Date.now()>=n.refreshExpiresAt?(_chunkCR5KJUSTjs.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 _chunkCR5KJUSTjs.a.error("Crudify: Failed to retrieve tokens",e instanceof Error?e:{message:String(e)}),await a.clearTokens(),null}}static async clearTokens(){let t=a.getStorage();if(t)try{t.removeItem(a.TOKEN_KEY),_chunkCR5KJUSTjs.a.debug("Crudify: Tokens cleared from storage")}catch(e){_chunkCR5KJUSTjs.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){}_chunkCR5KJUSTjs.a.info("Crudify: Encryption key rotated successfully")}catch(t){_chunkCR5KJUSTjs.a.error("Crudify: Failed to rotate encryption key",t instanceof Error?t:{message:String(t)})}}static async hasValidTokens(){return await a.getTokens()!==null}static async ensureInitialized(){await a.initialize()}static async getExpirationInfo(){let t=await a.getTokens();if(!t)return null;let e=Date.now();return{accessExpired:e>=t.expiresAt,refreshExpired:e>=t.refreshExpiresAt,accessExpiresIn:Math.max(0,t.expiresAt-e),refreshExpiresIn:Math.max(0,t.refreshExpiresAt-e)}}static async updateAccessToken(t,e){let i=await a.getTokens();if(!i){_chunkCR5KJUSTjs.a.warn("Crudify: Cannot update access token, no existing tokens found");return}await a.saveTokens({...i,accessToken:t,expiresAt:e})}static createSyncEvent(t,e,i){return{type:t,tokens:e,hadPreviousTokens:i}}static markLocalChange(){a.ignoreNextStorageEvent=!0,a.ignoreStorageEventTimeout&&clearTimeout(a.ignoreStorageEventTimeout),a.ignoreStorageEventTimeout=setTimeout(()=>{a.ignoreNextStorageEvent=!1},100)}static markSuccessfulLogin(){a.lastSuccessfulLoginTime=Date.now()}static isWithinLoginGracePeriod(){return a.lastSuccessfulLoginTime===0?!1:Date.now()-a.lastSuccessfulLoginTime<a.LOGIN_GRACE_PERIOD_MS}static subscribeToChanges(t){let e=async i=>{if(i.key!==a.TOKEN_KEY)return;if(a.ignoreNextStorageEvent){a.ignoreNextStorageEvent=!1;return}if(i.newValue===null&&a.isWithinLoginGracePeriod())return;if(i.newValue===null){let l=_optionalChain([a, 'access', _2 => _2.getStorage, 'call', _3 => _3(), 'optionalAccess', _4 => _4.getItem, 'call', _5 => _5(a.TOKEN_KEY)]);if(l!==null&&l!=="")return}let n=i.oldValue!==null&&i.oldValue!=="";if(i.newValue===null){_chunkCR5KJUSTjs.a.debug("Crudify: Tokens removed in another tab"),t(null,a.SYNC_EVENTS.TOKENS_CLEARED,n);return}if(i.newValue){_chunkCR5KJUSTjs.a.debug("Crudify: Tokens updated in another tab");let s=await a.getTokens();t(s,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.lastSuccessfulLoginTime=0,a.LOGIN_GRACE_PERIOD_MS=5e3,a.SYNC_EVENTS={TOKENS_CLEARED:"TOKENS_CLEARED",TOKENS_UPDATED:"TOKENS_UPDATED"},a.ignoreNextStorageEvent=!1,a.ignoreStorageEventTimeout=null;var v=a;var K=class K{constructor(){this.broadcastChannel=null;this.CHANNEL_NAME="crudify-session-sync";this.listeners=new Set;this.isInitialized=!1;this.tabId=K.generateTabId(),this.initialize()}static generateTabId(){let t=Date.now().toString(36),e=Math.random().toString(36).substring(2,9);return`tab_${t}_${e}`}static getInstance(){return K.instance||(K.instance=new K),K.instance}static resetInstance(){K.instance&&(K.instance.destroy(),K.instance=null)}initialize(){if(!this.isInitialized)try{typeof BroadcastChannel<"u"?(this.broadcastChannel=new BroadcastChannel(this.CHANNEL_NAME),this.broadcastChannel.onmessage=t=>{this.handleMessage(t.data)},this.broadcastChannel.onmessageerror=()=>{_chunkCR5KJUSTjs.a.warn("Crudify: CrossTabSync message error")},_chunkCR5KJUSTjs.a.debug("Crudify: CrossTabSync initialized with BroadcastChannel")):_chunkCR5KJUSTjs.a.debug("Crudify: BroadcastChannel not available, using localStorage fallback"),this.isInitialized=!0}catch(t){_chunkCR5KJUSTjs.a.warn("Crudify: Failed to initialize CrossTabSync",{message:t instanceof Error?t.message:String(t)})}}destroy(){this.broadcastChannel&&(this.broadcastChannel.close(),this.broadcastChannel=null),this.listeners.clear(),this.isInitialized=!1}getTabId(){return this.tabId}subscribe(t){return this.listeners.add(t),()=>{this.listeners.delete(t)}}notifyLogin(){this.broadcast({type:"SESSION_STARTED",tabId:this.tabId,timestamp:Date.now()})}notifyLogout(){this.broadcast({type:"SESSION_ENDED",tabId:this.tabId,timestamp:Date.now()})}notifyTokenRefreshed(){this.broadcast({type:"TOKEN_REFRESHED",tabId:this.tabId,timestamp:Date.now()})}ping(){this.broadcast({type:"SESSION_PING",tabId:this.tabId,timestamp:Date.now()})}broadcast(t){this.isInitialized||this.initialize();try{this.broadcastChannel&&(this.broadcastChannel.postMessage(t),_chunkCR5KJUSTjs.a.debug(`Crudify: CrossTab broadcast ${t.type}`))}catch(e){_chunkCR5KJUSTjs.a.warn("Crudify: Failed to broadcast cross-tab message",{message:e instanceof Error?e.message:String(e)})}}handleMessage(t){t.tabId!==this.tabId&&(_chunkCR5KJUSTjs.a.debug(`Crudify: CrossTab received ${t.type} from ${t.tabId}`),t.type==="SESSION_PING"&&this.broadcast({type:"SESSION_PONG",tabId:this.tabId,timestamp:Date.now(),payload:{respondingTo:t.tabId}}),this.listeners.forEach(e=>{try{e(t)}catch(i){_chunkCR5KJUSTjs.a.error("Crudify: CrossTab listener error",{message:i instanceof Error?i.message:String(i)})}}))}};K.instance=null;var ye=K,W= exports.c =ye.getInstance();var _crudifysdk = require('@nocios/crudify-sdk'); var _crudifysdk2 = _interopRequireDefault(_crudifysdk);var ne=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(t={}){if(!this.initialized){if(this.config={storageType:"localStorage",autoRestore:!0,enableLogging:!1,env:"stg",...t},v.setStorageType(this.config.storageType||"localStorage"),this.config.publicApiKey&&!this.crudifyInitialized&&await this.ensureCrudifyInitialized(),_crudifysdk2.default.setTokenInvalidationCallback(()=>{this.log("Tokens invalidated by crudify-core"),_chunkCR5KJUSTjs.f.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 v.getTokens();e?await v.saveTokens({...e,apiEndpointAdmin:this.config.apiEndpointAdmin,apiKeyEndpointAdmin:this.config.apiKeyEndpointAdmin}):await v.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(t,e){try{let i=await _crudifysdk2.default.login(t,e);if(!i.success)return{success:!1,error:this.formatError(i.errors),rawResponse:i};let n=await v.getTokens(),s=i.data,l={accessToken:s.token,refreshToken:s.refreshToken,expiresAt:s.expiresAt,refreshExpiresAt:s.refreshExpiresAt,apiEndpointAdmin:_optionalChain([n, 'optionalAccess', _6 => _6.apiEndpointAdmin])||this.config.apiEndpointAdmin,apiKeyEndpointAdmin:_optionalChain([n, 'optionalAccess', _7 => _7.apiKeyEndpointAdmin])||this.config.apiKeyEndpointAdmin};return await v.saveTokens(l),v.markSuccessfulLogin(),this.lastActivityTime=Date.now(),W.notifyLogin(),_optionalChain([this, 'access', _8 => _8.config, 'access', _9 => _9.onLoginSuccess, 'optionalCall', _10 => _10(l)]),{success:!0,tokens:l,data:s}}catch(i){return _chunkCR5KJUSTjs.a.error("[SessionManager] Login error",i instanceof Error?i:{message:String(i)}),{success:!1,error:i instanceof Error?i.message:"Unknown error"}}}async logout(){try{this.log("Logging out..."),_chunkCR5KJUSTjs.f.emit("LOGOUT",{message:"User logged out",source:"SessionManager.logout"}),await _crudifysdk2.default.logout(),await v.clearTokens(),W.notifyLogout(),this.log("Logout successful"),_optionalChain([this, 'access', _11 => _11.config, 'access', _12 => _12.onLogout, 'optionalCall', _13 => _13()])}catch(t){this.log("Logout error",{error:t instanceof Error?t.message:String(t)}),await v.clearTokens(),W.notifyLogout()}}async restoreSession(){try{this.log("Attempting to restore session...");let t=await v.getTokens();if(!t)return this.log("No valid tokens found in storage"),!1;if(Date.now()>=t.refreshExpiresAt)return this.log("Refresh token expired, clearing storage"),await v.clearTokens(),!1;if(_crudifysdk2.default.setTokens({accessToken:t.accessToken,refreshToken:t.refreshToken,expiresAt:t.expiresAt,refreshExpiresAt:t.refreshExpiresAt}),_crudifysdk2.default.getTokenData().isValid===!1){if(this.log("Restored access token is invalid or expired"),Date.now()<t.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 v.getTokens();return n&&_optionalChain([this, 'access', _14 => _14.config, 'access', _15 => _15.onSessionRestored, 'optionalCall', _16 => _16(n)]),!0}return await v.clearTokens(),await _crudifysdk2.default.logout(),!1}return this.log("Session restored successfully"),this.lastActivityTime=Date.now(),_optionalChain([this, 'access', _17 => _17.config, 'access', _18 => _18.onSessionRestored, 'optionalCall', _19 => _19(t)]),!0}catch(t){return this.log("Session restore error",{error:t instanceof Error?t.message:String(t)}),await v.clearTokens(),await _crudifysdk2.default.logout(),!1}}async isAuthenticated(){return _crudifysdk2.default.isLogin()||await v.hasValidTokens()}async getTokenInfo(){let t=_crudifysdk2.default.getTokenData(),e=await v.getExpirationInfo(),i=await v.getTokens();return{isLoggedIn:await this.isAuthenticated(),crudifyTokens:t,storageInfo:e,hasValidTokens:await v.hasValidTokens(),apiEndpointAdmin:_optionalChain([i, 'optionalAccess', _20 => _20.apiEndpointAdmin]),apiKeyEndpointAdmin:_optionalChain([i, 'optionalAccess', _21 => _21.apiKeyEndpointAdmin])}}async refreshTokens(){if(this.isRefreshingLocally&&this.refreshPromise)return this.log("Refresh already in progress, waiting for existing promise..."),this.refreshPromise;this.isRefreshingLocally=!0,this.refreshPromise=this._performRefresh();try{return await this.refreshPromise}finally{this.isRefreshingLocally=!1,this.refreshPromise=null}}async _performRefresh(){try{this.log("Starting token refresh...");let t=await _crudifysdk2.default.refreshAccessToken();if(!t.success)return this.log("Token refresh failed",{errors:t.errors}),await v.clearTokens(),_optionalChain([this, 'access', _22 => _22.config, 'access', _23 => _23.showNotification, 'optionalCall', _24 => _24(this.getSessionExpiredMessage(),"warning")]),_optionalChain([this, 'access', _25 => _25.config, 'access', _26 => _26.onSessionExpired, 'optionalCall', _27 => _27()]),!1;let e=t.data,i={accessToken:e.token,refreshToken:e.refreshToken,expiresAt:e.expiresAt,refreshExpiresAt:e.refreshExpiresAt};return await v.saveTokens(i),this.log("Tokens refreshed and saved successfully"),this.lastActivityTime=Date.now(),W.notifyTokenRefreshed(),!0}catch(t){return this.log("Token refresh error",{error:t instanceof Error?t.message:String(t)}),await v.clearTokens(),_optionalChain([this, 'access', _28 => _28.config, 'access', _29 => _29.showNotification, 'optionalCall', _30 => _30(this.getSessionExpiredMessage(),"warning")]),_optionalChain([this, 'access', _31 => _31.config, 'access', _32 => _32.onSessionExpired, 'optionalCall', _33 => _33()]),!1}}isRefreshing(){return this.isRefreshingLocally}setupResponseInterceptor(){_crudifysdk2.default.setResponseInterceptor(async t=>{this.updateLastActivity();let e=this.detectAuthorizationError(t);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"),_chunkCR5KJUSTjs.f.emit("TOKEN_REFRESH_FAILED",{message:e.userFriendlyMessage,error:e.errorDetails,source:"SessionManager.setupResponseInterceptor"}),t;e.shouldTriggerLogout&&(await v.hasValidTokens()&&!e.isIrrecoverable?(this.log("Access token expired, emitting TOKEN_EXPIRED event"),_chunkCR5KJUSTjs.f.emit("TOKEN_EXPIRED",{message:"Access token expired, refresh needed",error:e.errorDetails,source:"SessionManager.setupResponseInterceptor"})):(this.log("No valid tokens or irrecoverable error, emitting SESSION_EXPIRED event"),_chunkCR5KJUSTjs.f.emit("SESSION_EXPIRED",{message:e.userFriendlyMessage,error:e.errorDetails,source:"SessionManager.setupResponseInterceptor"})))}return t}),this.log("Response interceptor configured (non-blocking mode)")}async ensureCrudifyInitialized(){if(!this.crudifyInitialized)try{this.log("Initializing crudify SDK...");let t=_crudifysdk2.default.getTokenData();if(t&&t.endpoint){this.log("Crudify already initialized by another service"),this.crudifyInitialized=!0;return}let e=this.config.env||"stg";_crudifysdk2.default.config(e);let i=this.config.publicApiKey,n=this.config.enableLogging?"debug":"none",s=await _crudifysdk2.default.init(i,n);if(s&&s.success===!1&&s.errors)throw new Error(`Failed to initialize crudify: ${JSON.stringify(s.errors)}`);this.crudifyInitialized=!0,this.log("Crudify SDK initialized successfully")}catch(t){throw _chunkCR5KJUSTjs.a.error("[SessionManager] Failed to initialize crudify",t instanceof Error?t:{message:String(t)}),t}}detectAuthorizationError(t){let e={isAuthError:!1,isRefreshTokenInvalid:!1,isTokenRefreshFailed:!1,isTokenExpired:!1,isUnauthorized:!1,isIrrecoverable:!1,shouldTriggerLogout:!1,errorType:"",errorDetails:null,userFriendlyMessage:""};if(t.errors&&Array.isArray(t.errors)){let i=t.errors.find(n=>n.errorType==="Unauthorized"||_optionalChain([n, 'access', _34 => _34.message, 'optionalAccess', _35 => _35.includes, 'call', _36 => _36("Unauthorized")])||_optionalChain([n, 'access', _37 => _37.message, 'optionalAccess', _38 => _38.includes, 'call', _39 => _39("Not Authorized")])||_optionalChain([n, 'access', _40 => _40.message, 'optionalAccess', _41 => _41.includes, 'call', _42 => _42("NOT_AUTHORIZED")])||_optionalChain([n, 'access', _43 => _43.message, 'optionalAccess', _44 => _44.includes, 'call', _45 => _45("Token")])||_optionalChain([n, 'access', _46 => _46.message, 'optionalAccess', _47 => _47.includes, 'call', _48 => _48("TOKEN")])||_optionalChain([n, 'access', _49 => _49.message, 'optionalAccess', _50 => _50.includes, 'call', _51 => _51("Authentication")])||_optionalChain([n, 'access', _52 => _52.message, 'optionalAccess', _53 => _53.includes, 'call', _54 => _54("UNAUTHENTICATED")])||_optionalChain([n, 'access', _55 => _55.extensions, 'optionalAccess', _56 => _56.code])==="UNAUTHENTICATED"||_optionalChain([n, 'access', _57 => _57.extensions, 'optionalAccess', _58 => _58.code])==="FORBIDDEN");i&&(e.isAuthError=!0,e.errorType="GraphQL Array",e.errorDetails=i,e.shouldTriggerLogout=!0,e.userFriendlyMessage="Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente.",(_optionalChain([i, 'access', _59 => _59.message, 'optionalAccess', _60 => _60.includes, 'call', _61 => _61("TOKEN")])||_optionalChain([i, 'access', _62 => _62.message, 'optionalAccess', _63 => _63.includes, 'call', _64 => _64("Token")]))&&(e.isTokenExpired=!0),_optionalChain([i, 'access', _65 => _65.extensions, 'optionalAccess', _66 => _66.code])==="UNAUTHENTICATED"&&(e.isUnauthorized=!0))}if(!e.isAuthError&&t.errors&&typeof t.errors=="object"&&!Array.isArray(t.errors)){let n=Object.values(t.errors).flat().find(s=>typeof s=="string"&&(s.includes("NOT_AUTHORIZED")||s.includes("TOKEN_REFRESH_FAILED")||s.includes("TOKEN_HAS_EXPIRED")||s.includes("PLEASE_LOGIN")||s.includes("Unauthorized")||s.includes("UNAUTHENTICATED")||s.includes("SESSION_EXPIRED")||s.includes("INVALID_TOKEN")));n&&typeof n=="string"&&(e.isAuthError=!0,e.errorType="GraphQL Object",e.errorDetails=t.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([t, 'access', _67 => _67.data, 'optionalAccess', _68 => _68.response, 'optionalAccess', _69 => _69.status])){let i=t.data.response.status.toUpperCase();(i==="UNAUTHORIZED"||i==="UNAUTHENTICATED")&&(e.isAuthError=!0,e.errorType="Status",e.errorDetails=t.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([t, 'access', _70 => _70.data, 'optionalAccess', _71 => _71.response, 'optionalAccess', _72 => _72.data]))try{let i=typeof t.data.response.data=="string"?JSON.parse(t.data.response.data):t.data.response.data;(i.error==="REFRESH_TOKEN_INVALID"||i.error==="TOKEN_EXPIRED"||i.error==="INVALID_TOKEN")&&(e.isAuthError=!0,e.errorType="Parsed Data",e.errorDetails=i,e.shouldTriggerLogout=!0,e.isIrrecoverable=!0,i.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&&t.errorCode){let i=String(t.errorCode).toUpperCase();(i==="UNAUTHORIZED"||i==="UNAUTHENTICATED"||i==="TOKEN_EXPIRED"||i==="INVALID_TOKEN")&&(e.isAuthError=!0,e.errorType="Error Code",e.errorDetails={errorCode:i},e.shouldTriggerLogout=!0,i==="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 t=this.getTimeSinceLastActivity();if(this.lastActivityTime===0)return"none";let e=1800*1e3;return t>e?(this.log(`Inactivity timeout: ${Math.floor(t/6e4)} minutes since last activity`),"logout"):"none"}async clearSession(){await v.clearTokens(),await _crudifysdk2.default.logout(),this.lastActivityTime=0,this.log("Session cleared completely")}getSessionExpiredMessage(){return this.config.translateFn?_chunkCR5KJUSTjs.m.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(t,e){this.config.enableLogging&&_chunkCR5KJUSTjs.a.debug(`[SessionManager] ${t}`,e)}formatError(t){return t?typeof t=="string"?t:typeof t=="object"?Object.values(t).flat().map(String).join(", "):"Authentication failed":"Unknown error"}};var _react = require('react'); var _react2 = _interopRequireDefault(_react);var Ke={isAuthenticated:!1,isLoading:!0,isLoggingOut:!1,isInitialized:!1,tokens:null,error:null};function Me(){let[r,t]=_react.useState.call(void 0, Ke),e=_react.useCallback.call(void 0, o=>{t(f=>({...f,isLoading:o}))},[]),i=_react.useCallback.call(void 0, (o,f)=>{t(E=>({...E,isAuthenticated:o,tokens:f,error:o?null:E.error}))},[]),n=_react.useCallback.call(void 0, o=>{t(f=>({...f,isLoggingOut:o}))},[]),s=_react.useCallback.call(void 0, o=>{t(f=>({...f,error:o}))},[]),l=_react.useCallback.call(void 0, o=>{t(f=>({...f,isInitialized:o}))},[]);return{state:r,setState:t,setLoading:e,setAuthenticated:i,setLoggingOut:n,setError:s,setInitialized:l}}var se={AGGRESSIVE:3e4,MODERATE:6e4,RELAXED:12e4},he={AGGRESSIVE:300*1e3,MODERATE:1800*1e3},He=.5;function Ge(r){return r?r.expiresAt-Date.now()<3e5:!1}function _e(r){return r?Math.max(0,r.expiresAt-Date.now()):0}function Ve(r){return r?Math.max(0,r.refreshExpiresAt-Date.now()):0}function $(r){return r.crudifyTokens.accessToken?{accessToken:r.crudifyTokens.accessToken,refreshToken:r.crudifyTokens.refreshToken||"",expiresAt:r.crudifyTokens.expiresAt,refreshExpiresAt:r.crudifyTokens.refreshExpiresAt}:null}function $e(r){let{sessionManager:t,stateManager:e}=r,i=_react.useCallback.call(void 0, async(o,f)=>{e.setState(E=>({...E,isLoading:!0,isLoggingOut:!1,error:null}));try{let E=await t.login(o,f);return E.success&&E.tokens?e.setState(b=>({...b,isAuthenticated:!0,tokens:E.tokens,isLoading:!1,isLoggingOut:!1,error:null})):e.setState(b=>({...b,isAuthenticated:!1,tokens:null,isLoading:!1,isLoggingOut:!1,error:null})),E}catch(E){let b=E instanceof Error?E.message:"Login failed";_chunkCR5KJUSTjs.a.error("[useSession] Login error",E instanceof Error?E:{message:b});let T=b.includes("INVALID_CREDENTIALS")||b.includes("Invalid email")||b.includes("Invalid password")||b.includes("credentials");return e.setState(m=>({...m,isAuthenticated:!1,tokens:null,isLoading:!1,isLoggingOut:!1,error:T?null:b})),{success:!1,error:b}}},[t,e]),n=_react.useCallback.call(void 0, async()=>{e.setState(o=>({...o,isLoading:!0,isLoggingOut:!0}));try{await t.logout(),e.setState(o=>({...o,isAuthenticated:!1,tokens:null,isLoading:!1,error:null}))}catch(o){e.setState(f=>({...f,isAuthenticated:!1,tokens:null,isLoading:!1,error:o instanceof Error?o.message:"Logout error"}))}},[t,e]),s=_react.useCallback.call(void 0, async()=>{try{let o=await t.refreshTokens();if(o){let f=await t.getTokenInfo();e.setState(E=>({...E,tokens:$(f),error:null}))}else e.setState(f=>({...f,isAuthenticated:!1,tokens:null,error:"Token refresh failed"}));return o}catch(o){return e.setState(f=>({...f,isAuthenticated:!1,tokens:null,error:o instanceof Error?o.message:"Token refresh failed"})),!1}},[t,e]),l=_react.useCallback.call(void 0, ()=>{e.setError(null)},[e]);return{login:i,logout:n,refreshTokens:s,clearError:l}}function zt(r){return r<he.AGGRESSIVE?se.AGGRESSIVE:r<he.MODERATE?se.MODERATE:se.RELAXED}function Ye(r){let{isAuthenticated:t,tokens:e,sessionManager:i,onTokensRefreshed:n,onSessionExpired:s,onSetLoading:l,logout:o}=r,f=_react.useCallback.call(void 0, ()=>{i.updateLastActivity()},[i]);_react.useEffect.call(void 0, ()=>{if(!t||!e)return;let b=_chunkCR5KJUSTjs.q.getInstance().subscribe(f);window.addEventListener("popstate",f);let T,m=!0,I=async()=>{if(!m)return;let A=(await i.getTokenInfo()).crudifyTokens.expiresIn||0,N=zt(A);T=setTimeout(async()=>{if(!m)return;if(i.isRefreshing()){I();return}let x=await i.getTokenInfo(),O=x.crudifyTokens.expiresIn||0,z=((x.crudifyTokens.expiresAt||0)-(Date.now()-O))*He;if(O>0&&O<=z)if(l(!0),await i.refreshTokens()){let Z=await i.getTokenInfo();n($(Z)),l(!1)}else n(null),s(),l(!1);i.getTimeSinceLastActivity()>18e5?await o():m&&I()},N)};return I(),()=>{m=!1,clearTimeout(T),window.removeEventListener("popstate",f),b()}},[t,e,i,f,n,s,l,o])}function Be(r){let{sessionManager:t,onTokensUpdated:e,onSessionExpired:i,onSetLoading:n,onSetError:s}=r;_react.useEffect.call(void 0, ()=>{let l=_chunkCR5KJUSTjs.f.subscribe(async o=>{if(o.type==="TOKEN_EXPIRED"){if(t.isRefreshing())return;n(!0);try{if(await t.refreshTokens()){let E=await t.getTokenInfo();e($(E)),n(!1)}else _chunkCR5KJUSTjs.f.emit("SESSION_EXPIRED",{message:"Failed to refresh token after detecting expiration",source:"useSession.TOKEN_EXPIRED handler"})}catch(f){_chunkCR5KJUSTjs.f.emit("SESSION_EXPIRED",{message:f instanceof Error?f.message:"Unknown error during refresh",source:"useSession.TOKEN_EXPIRED handler (error)"})}}(o.type==="SESSION_EXPIRED"||o.type==="TOKEN_REFRESH_FAILED")&&(e(null),n(!1),s(_optionalChain([o, 'access', _73 => _73.details, 'optionalAccess', _74 => _74.message, 'optionalAccess', _75 => _75.toString, 'call', _76 => _76()])||"Session expired"),i())});return()=>l()},[t,e,i,n,s])}function Xe(r){let{isAuthenticated:t,onTokensUpdated:e,onSessionExpired:i}=r;_react.useEffect.call(void 0, ()=>{let n=async l=>{switch(l.type){case"SESSION_STARTED":case"TOKEN_REFRESHED":try{await v.ensureInitialized();let o=await v.getTokens();o&&(_chunkCR5KJUSTjs.a.debug(`[useCrossTabSync] Syncing ${l.type} from tab ${l.tabId}`),e(o))}catch(o){_chunkCR5KJUSTjs.a.warn("[useCrossTabSync] Failed to read tokens after cross-tab event",{error:o instanceof Error?o.message:String(o)})}break;case"SESSION_ENDED":try{await v.hasValidTokens()||(_chunkCR5KJUSTjs.a.debug(`[useCrossTabSync] Syncing SESSION_ENDED from tab ${l.tabId}`),e(null),t&&i())}catch(o){_chunkCR5KJUSTjs.a.warn("[useCrossTabSync] Failed to verify tokens after logout event",{error:o instanceof Error?o.message:String(o)})}break;case"SESSION_PING":case"SESSION_PONG":break}},s=W.subscribe(n);return()=>s()},[t,e,i]),_react.useEffect.call(void 0, ()=>{let n=v.subscribeToChanges(async(s,l,o)=>{if(l===v.SYNC_EVENTS.TOKENS_CLEARED){if(await v.hasValidTokens())return;o&&t?(e(null),i()):o&&e(null)}else l===v.SYNC_EVENTS.TOKENS_UPDATED&&s&&e(s)});return()=>n()},[t,e,i])}async function Ze(r){let{sessionManager:t,options:e,stateActions:i}=r;try{i.setState(o=>({...o,isLoading:!0,error:null}));let n={autoRestore:_nullishCoalesce(e.autoRestore, () => (!0)),enableLogging:_nullishCoalesce(e.enableLogging, () => (!1)),showNotification:e.showNotification,translateFn:e.translateFn,apiEndpointAdmin:e.apiEndpointAdmin,apiKeyEndpointAdmin:e.apiKeyEndpointAdmin,publicApiKey:e.publicApiKey,env:e.env||"stg",onSessionExpired:()=>{i.setState(o=>({...o,isAuthenticated:!1,tokens:null,error:"Session expired"})),_optionalChain([e, 'access', _77 => _77.onSessionExpired, 'optionalCall', _78 => _78()])},onSessionRestored:o=>{i.setState(f=>({...f,isAuthenticated:!0,tokens:o,error:null})),_optionalChain([e, 'access', _79 => _79.onSessionRestored, 'optionalCall', _80 => _80(o)])},onLoginSuccess:o=>{i.setState(f=>({...f,isAuthenticated:!0,tokens:o,error:null}))},onLogout:()=>{i.setState(o=>({...o,isAuthenticated:!1,tokens:null,error:null}))}};await t.initialize(n),t.setupResponseInterceptor();let s=await t.isAuthenticated(),l=await t.getTokenInfo();i.setState(o=>({...o,isAuthenticated:s,isInitialized:!0,isLoading:!1,isLoggingOut:!1,tokens:$(l)}))}catch(n){let s=n instanceof Error?n.message:"Initialization failed";_chunkCR5KJUSTjs.a.error("[useSession] Initialize failed",n instanceof Error?n:{message:s}),i.setState(l=>({...l,isLoading:!1,isInitialized:!0,isLoggingOut:!1,error:s}))}}function Ee(r={}){let t=ne.getInstance(),e=Me(),{state:i}=e,{login:n,logout:s,refreshTokens:l,clearError:o}=$e({sessionManager:t,stateManager:e}),f=_react.useCallback.call(void 0, g=>{e.setAuthenticated(!!g,g)},[e]),E=_react.useCallback.call(void 0, ()=>{e.setAuthenticated(!1,null),_optionalChain([r, 'access', _81 => _81.onSessionExpired, 'optionalCall', _82 => _82()])},[e,r.onSessionExpired]),b=_react.useCallback.call(void 0, g=>{e.setLoading(g)},[e]),T=_react.useCallback.call(void 0, g=>{e.setError(g)},[e]);_react.useEffect.call(void 0, ()=>{Ze({sessionManager:t,options:r,stateActions:e})},[]),Ye({isAuthenticated:i.isAuthenticated,tokens:i.tokens,sessionManager:t,onTokensRefreshed:f,onSessionExpired:E,onSetLoading:b,logout:s}),Be({sessionManager:t,onTokensUpdated:f,onSessionExpired:E,onSetLoading:b,onSetError:T}),Xe({isAuthenticated:i.isAuthenticated,onTokensUpdated:f,onSessionExpired:E});let m=_react.useCallback.call(void 0, ()=>{t.updateLastActivity()},[t]),I=_react.useCallback.call(void 0, async()=>t.getTokenInfo(),[t]);return{...i,login:n,logout:s,refreshTokens:l,clearError:o,getTokenInfo:I,updateActivity:m,isExpiringSoon:Ge(i.tokens),expiresIn:_e(i.tokens),refreshExpiresIn:Ve(i.tokens)}}var _material = require('@mui/material');var _uuid = require('uuid');var _dompurify = require('dompurify'); var _dompurify2 = _interopRequireDefault(_dompurify);var _jsxruntime = require('react/jsx-runtime');var je=_react.createContext.call(void 0, null),Xt=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}),Te= exports.f =({children:r,maxNotifications:t=5,defaultAutoHideDuration:e=6e3,position:i={vertical:"top",horizontal:"right"},enabled:n=!1,allowHtml:s=!1})=>{let[l,o]=_react.useState.call(void 0, []),f=_react.useCallback.call(void 0, (m,I="info",g)=>{if(!n)return"";if(!m||typeof m!="string")return _chunkCR5KJUSTjs.a.warn("GlobalNotificationProvider: Invalid message provided"),"";m.length>1e3&&(_chunkCR5KJUSTjs.a.warn("GlobalNotificationProvider: Message too long, truncating"),m=m.substring(0,1e3)+"...");let A=_uuid.v4.call(void 0, ),N={id:A,message:m,severity:I,autoHideDuration:_nullishCoalesce(_optionalChain([g, 'optionalAccess', _83 => _83.autoHideDuration]), () => (e)),persistent:_nullishCoalesce(_optionalChain([g, 'optionalAccess', _84 => _84.persistent]), () => (!1)),allowHtml:_nullishCoalesce(_optionalChain([g, 'optionalAccess', _85 => _85.allowHtml]), () => (s))};return o(x=>[...x.length>=t?x.slice(-(t-1)):x,N]),A},[t,e,n,s]),E=_react.useCallback.call(void 0, m=>{o(I=>I.filter(g=>g.id!==m))},[]),b=_react.useCallback.call(void 0, ()=>{o([])},[]),T={showNotification:f,hideNotification:E,clearAllNotifications:b};return _jsxruntime.jsxs.call(void 0, je.Provider,{value:T,children:[r,n&&_jsxruntime.jsx.call(void 0, _material.Portal,{children:_jsxruntime.jsx.call(void 0, _material.Box,{sx:{position:"fixed",zIndex:9999,[i.vertical]:(i.vertical==="top",24),[i.horizontal]:i.horizontal==="right"||i.horizontal==="left"?24:"50%",...i.horizontal==="center"&&{transform:"translateX(-50%)"},display:"flex",flexDirection:i.vertical==="top"?"column":"column-reverse",gap:1,maxWidth:"400px",width:"auto"},children:l.map(m=>_jsxruntime.jsx.call(void 0, Zt,{notification:m,onClose:()=>E(m.id)},m.id))})})]})},Zt=({notification:r,onClose:t})=>{let[e,i]=_react.useState.call(void 0, !0),n=_react.useCallback.call(void 0, (s,l)=>{l!=="clickaway"&&(i(!1),setTimeout(t,300))},[t]);return _react.useEffect.call(void 0, ()=>{if(!r.persistent&&r.autoHideDuration){let s=setTimeout(()=>{n()},r.autoHideDuration);return()=>clearTimeout(s)}},[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:Xt(r.message)}}):_jsxruntime.jsx.call(void 0, "span",{children:r.message})})})},Je= exports.g =()=>{let r=_react.useContext.call(void 0, je);if(!r)throw new Error("useGlobalNotification debe ser usado dentro de un GlobalNotificationProvider");return r};var Se=class r{constructor(){this.listeners=[];this.credentials=null;this.isReady=!1}static getInstance(){return r.instance||(r.instance=new r),r.instance}notifyCredentialsReady(t){this.credentials=t,this.isReady=!0,this.listeners.forEach(e=>{try{e(t)}catch(i){_chunkCR5KJUSTjs.a.error("[CredentialsEventBus] Error in listener",i instanceof Error?i:{message:String(i)})}}),this.listeners=[]}waitForCredentials(){return this.isReady&&this.credentials?Promise.resolve(this.credentials):new Promise(t=>{this.listeners.push(t)})}reset(){this.credentials=null,this.isReady=!1,this.listeners=[]}areCredentialsReady(){return this.isReady&&this.credentials!==null}},le= exports.h =Se.getInstance();var Qe=_react.createContext.call(void 0, void 0),et= exports.i =({config:r,children:t})=>{let[e,i]=_react.useState.call(void 0, !0),[n,s]=_react.useState.call(void 0, null),[l,o]=_react.useState.call(void 0, !1),[f,E]=_react.useState.call(void 0, ""),[b,T]=_react.useState.call(void 0, );_react.useEffect.call(void 0, ()=>{if(!r.publicApiKey){s("No publicApiKey provided"),i(!1),o(!1);return}let I=`${r.publicApiKey}-${r.env}`;if(I===f&&l){i(!1);return}(async()=>{i(!0),s(null),o(!1);try{_crudifysdk2.default.config(r.env||"prod");let A=await _crudifysdk2.default.init(r.publicApiKey,"none");if(T(A),typeof _crudifysdk2.default.transaction=="function"&&typeof _crudifysdk2.default.login=="function")o(!0),E(I),A.apiEndpointAdmin&&A.apiKeyEndpointAdmin&&le.notifyCredentialsReady({apiUrl:A.apiEndpointAdmin,apiKey:A.apiKeyEndpointAdmin});else throw new Error("Crudify methods not properly initialized")}catch(A){let N=A instanceof Error?A.message:"Failed to initialize Crudify";_chunkCR5KJUSTjs.a.error("[CrudifyProvider] Initialization error",A instanceof Error?A:{message:String(A)}),s(N),o(!1)}finally{i(!1)}})()},[r.publicApiKey,r.env,f,l]);let m={crudify:l?_crudifysdk2.default:null,isLoading:e,error:n,isInitialized:l,adminCredentials:b};return _jsxruntime.jsx.call(void 0, Qe.Provider,{value:m,children:t})},tt= exports.j =()=>{let r=_react.useContext.call(void 0, Qe);if(r===void 0)throw new Error("useCrudify must be used within a CrudifyProvider");return r};var rt=_react.createContext.call(void 0, void 0);function it({children:r,options:t={},config:e,showNotifications:i=!1,notificationOptions:n={}}){let s;try{let{showNotification:g}=Je();s=g}catch (e10){}let l={};try{let g=tt();g.isInitialized&&g.adminCredentials&&(l=g.adminCredentials)}catch (e11){}let o=_react.useMemo.call(void 0, ()=>{let g=_chunkCR5KJUSTjs.d.call(void 0, {publicApiKey:_optionalChain([e, 'optionalAccess', _86 => _86.publicApiKey]),env:_optionalChain([e, 'optionalAccess', _87 => _87.env]),enableDebug:_optionalChain([t, 'optionalAccess', _88 => _88.enableLogging])});return{publicApiKey:g.publicApiKey,env:g.env||"prod"}},[e,_optionalChain([t, 'optionalAccess', _89 => _89.enableLogging])]),f=_react2.default.useMemo(()=>({...t,showNotification:s,apiEndpointAdmin:l.apiEndpointAdmin,apiKeyEndpointAdmin:l.apiKeyEndpointAdmin,publicApiKey:o.publicApiKey,env:o.env,onSessionExpired:()=>{_optionalChain([t, 'access', _90 => _90.onSessionExpired, 'optionalCall', _91 => _91()])}}),[t,s,l.apiEndpointAdmin,l.apiKeyEndpointAdmin,o]),E=Ee(f),b=_react.useMemo.call(void 0, ()=>{let g=_chunkCR5KJUSTjs.d.call(void 0, {publicApiKey:_optionalChain([e, 'optionalAccess', _92 => _92.publicApiKey]),env:_optionalChain([e, 'optionalAccess', _93 => _93.env]),appName:_optionalChain([e, 'optionalAccess', _94 => _94.appName]),logo:_optionalChain([e, 'optionalAccess', _95 => _95.logo]),loginActions:_optionalChain([e, 'optionalAccess', _96 => _96.loginActions]),enableDebug:_optionalChain([t, 'optionalAccess', _97 => _97.enableLogging])});return{publicApiKey:g.publicApiKey,env:g.env,appName:g.appName,loginActions:g.loginActions,logo:g.logo}},[e,_optionalChain([t, 'optionalAccess', _98 => _98.enableLogging])]),T=_react.useMemo.call(void 0, ()=>{if(!_optionalChain([E, 'access', _99 => _99.tokens, 'optionalAccess', _100 => _100.accessToken])||!E.isAuthenticated)return null;try{let g=_chunkCR5KJUSTjs.r.call(void 0, E.tokens.accessToken);if(g&&g.sub&&g.email&&g.subscriber){let A={_id:g.sub,email:g.email,subscriberKey:g.subscriber};return Object.keys(g).forEach(N=>{["sub","email","subscriber"].includes(N)||(A[N]=g[N])}),A}}catch(g){_chunkCR5KJUSTjs.a.error("Error decoding JWT token for sessionData",g instanceof Error?g:{message:String(g)})}return null},[_optionalChain([E, 'access', _101 => _101.tokens, 'optionalAccess', _102 => _102.accessToken]),E.isAuthenticated]),m={...E,sessionData:T,config:b},I={enabled:i,maxNotifications:n.maxNotifications||5,defaultAutoHideDuration:n.defaultAutoHideDuration||6e3,position:n.position||{vertical:"top",horizontal:"right"}};return _jsxruntime.jsx.call(void 0, rt.Provider,{value:m,children:r})}function Vr(r){let t={enabled:r.showNotifications,maxNotifications:_optionalChain([r, 'access', _103 => _103.notificationOptions, 'optionalAccess', _104 => _104.maxNotifications])||5,defaultAutoHideDuration:_optionalChain([r, 'access', _105 => _105.notificationOptions, 'optionalAccess', _106 => _106.defaultAutoHideDuration])||6e3,position:_optionalChain([r, 'access', _107 => _107.notificationOptions, 'optionalAccess', _108 => _108.position])||{vertical:"top",horizontal:"right"},allowHtml:_optionalChain([r, 'access', _109 => _109.notificationOptions, 'optionalAccess', _110 => _110.allowHtml])||!1};return _optionalChain([r, 'access', _111 => _111.config, 'optionalAccess', _112 => _112.publicApiKey])?_jsxruntime.jsx.call(void 0, et,{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, Te,{...t,children:_jsxruntime.jsx.call(void 0, it,{...r})})}):_jsxruntime.jsx.call(void 0, Te,{...t,children:_jsxruntime.jsx.call(void 0, it,{...r})})}function ni(){let r=_react.useContext.call(void 0, rt);if(r===void 0)throw new Error("useSessionContext must be used within a SessionProvider");return r}function $r(){let r=ni();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 qr=(r={})=>{let{autoFetch:t=!0,retryOnError:e=!1,maxRetries:i=3}=r,[n,s]=_react.useState.call(void 0, null),[l,o]=_react.useState.call(void 0, !1),[f,E]=_react.useState.call(void 0, null),[b,T]=_react.useState.call(void 0, {}),m=_react.useRef.call(void 0, null),I=_react.useRef.call(void 0, !0),g=_react.useRef.call(void 0, 0),A=_react.useRef.call(void 0, 0),N=_react.useCallback.call(void 0, ()=>{s(null),E(null),o(!1),T({})},[]),x=_react.useCallback.call(void 0, async()=>{let O=_chunkCR5KJUSTjs.s.call(void 0, );if(!O){I.current&&(E("No user email available"),o(!1));return}m.current&&m.current.abort();let w=new AbortController;m.current=w;let F=++g.current;try{I.current&&(o(!0),E(null));let z=await _crudifysdk2.default.readItems("users",{filter:{email:O},pagination:{limit:1}});if(F===g.current&&I.current&&!w.signal.aborted){let D=z.data;if(z.success&&D&&D.length>0){let S=D[0];s(S);let Z={fullProfile:S,totalFields:Object.keys(S).length,displayData:{id:S.id,email:S.email,username:S.username,firstName:S.firstName,lastName:S.lastName,fullName:S.fullName||`${S.firstName||""} ${S.lastName||""}`.trim(),role:S.role,permissions:S.permissions||[],isActive:S.isActive,lastLogin:S.lastLogin,createdAt:S.createdAt,updatedAt:S.updatedAt,...Object.keys(S).filter(V=>!["id","email","username","firstName","lastName","fullName","role","permissions","isActive","lastLogin","createdAt","updatedAt"].includes(V)).reduce((V,re)=>({...V,[re]:S[re]}),{})}};T(Z),E(null),A.current=0}else E("User profile not found"),s(null),T({})}}catch(z){if(F===g.current&&I.current){let D=z;if(D.name==="AbortError")return;e&&A.current<i&&(_optionalChain([D, 'access', _113 => _113.message, 'optionalAccess', _114 => _114.includes, 'call', _115 => _115("Network Error")])||_optionalChain([D, 'access', _116 => _116.message, 'optionalAccess', _117 => _117.includes, 'call', _118 => _118("Failed to fetch")]))?(A.current++,setTimeout(()=>{I.current&&x()},1e3*A.current)):(E("Failed to load user profile"),s(null),T({}))}}finally{F===g.current&&I.current&&o(!1),m.current===w&&(m.current=null)}},[e,i]);return _react.useEffect.call(void 0, ()=>{t&&x()},[t,x]),_react.useEffect.call(void 0, ()=>(I.current=!0,()=>{I.current=!1,m.current&&(m.current.abort(),m.current=null)}),[]),{userProfile:n,loading:l,error:f,extendedData:b,refreshProfile:x,clearProfile:N}};var en=(r,t={})=>{let{autoFetch:e=!0,onSuccess:i,onError:n}=t,{prefix:s,padding:l=0,separator:o=""}=r,[f,E]=_react.useState.call(void 0, ""),[b,T]=_react.useState.call(void 0, !1),[m,I]=_react.useState.call(void 0, null),g=_react.useRef.call(void 0, !1),A=_react.useCallback.call(void 0, w=>{let F=String(w).padStart(l,"0");return`${s}${o}${F}`},[s,l,o]),N=_react.useCallback.call(void 0, async()=>{T(!0),I(null);try{let w=await _crudifysdk2.default.getNextSequence(s),F=w.data;if(w.success&&_optionalChain([F, 'optionalAccess', _119 => _119.value])){let z=A(F.value);E(z),_optionalChain([i, 'optionalCall', _120 => _120(z)])}else{let z=_optionalChain([w, 'access', _121 => _121.errors, 'optionalAccess', _122 => _122._error, 'optionalAccess', _123 => _123[0]])||"Failed to generate code";I(z),_optionalChain([n, 'optionalCall', _124 => _124(z)])}}catch(w){let F=w instanceof Error?w.message:"Unknown error";I(F),_optionalChain([n, 'optionalCall', _125 => _125(F)])}finally{T(!1)}},[s,A,i,n]),x=_react.useCallback.call(void 0, async()=>{await N()},[N]),O=_react.useCallback.call(void 0, ()=>{I(null)},[]);return _react.useEffect.call(void 0, ()=>{e&&!f&&!g.current&&(g.current=!0,N())},[e,f,N]),{value:f,loading:b,error:m,regenerate:x,clearError:O}};var Ae=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(t){let{priority:e,publicApiKey:i,env:n,enableLogging:s,requestedBy:l}=t;if(this.state.status==="INITIALIZED"){this.state.publicApiKey!==i&&_chunkCR5KJUSTjs.a.warn(`[CrudifyInitialization] ${l} attempted to initialize with different key. Already initialized with key: ${_optionalChain([this, 'access', _126 => _126.state, 'access', _127 => _127.publicApiKey, 'optionalAccess', _128 => _128.slice, 'call', _129 => _129(0,10)])}... by ${this.state.initializedBy}`);return}if(this.initializationPromise)return s&&_chunkCR5KJUSTjs.a.debug(`[CrudifyInitialization] ${l} waiting for ongoing initialization...`),this.initializationPromise;if(e==="LOW"&&this.highPriorityInitializerPresent&&this.state.status==="UNINITIALIZED"){if(s&&_chunkCR5KJUSTjs.a.debug(`[CrudifyInitialization] ${l} (LOW priority) waiting for HIGH priority initializer...`),this.waitingForHighPriority.add(l),await this.waitForHighPriorityOrTimeout(s),this.waitingForHighPriority.delete(l),this.getState().status==="INITIALIZED"){s&&_chunkCR5KJUSTjs.a.debug(`[CrudifyInitialization] ${l} found initialization completed by HIGH priority`);return}s&&_chunkCR5KJUSTjs.a.warn(`[CrudifyInitialization] ${l} timeout waiting for HIGH priority, initializing with LOW priority`)}e==="HIGH"&&this.state.status==="INITIALIZING"&&this.state.priority==="LOW"&&(_chunkCR5KJUSTjs.a.warn(`[CrudifyInitialization] HIGH priority request from ${l} interrupting LOW priority initialization by ${this.state.initializedBy}`),this.state.status="UNINITIALIZED",this.initializationPromise=null),s&&_chunkCR5KJUSTjs.a.debug(`[CrudifyInitialization] ${l} starting initialization (${e} priority)...`),this.state.status="INITIALIZING",this.state.priority=e,this.state.initializedBy=l,this.initializationPromise=this.performInitialization(i,n,s);try{await this.initializationPromise,this.state.status="INITIALIZED",this.state.publicApiKey=i,this.state.env=n,this.state.error=null,s&&_chunkCR5KJUSTjs.a.info(`[CrudifyInitialization] Successfully initialized by ${l} (${e} priority)`)}catch(o){throw this.state.status="ERROR",this.state.error=o instanceof Error?o:new Error(String(o)),this.initializationPromise=null,_chunkCR5KJUSTjs.a.error(`[CrudifyInitialization] Initialization failed for ${l}`,o instanceof Error?o:{message:String(o)}),o}}async waitForHighPriorityOrTimeout(t){return new Promise(e=>{let n=0,s=setInterval(()=>{if(n+=10,this.state.status==="INITIALIZED"&&this.state.priority==="HIGH"){clearInterval(s),e();return}if(this.state.status==="INITIALIZING"&&this.state.priority==="HIGH"){n=0;return}n>=this.HIGH_PRIORITY_WAIT_TIMEOUT&&(clearInterval(s),t&&_chunkCR5KJUSTjs.a.debug(`[CrudifyInitialization] Timeout waiting for HIGH priority (${this.HIGH_PRIORITY_WAIT_TIMEOUT}ms)`),e())},10)})}async performInitialization(t,e,i){let n=_crudifysdk2.default.getTokenData();if(n&&n.endpoint){i&&_chunkCR5KJUSTjs.a.debug("[CrudifyInitialization] SDK already initialized externally");return}_crudifysdk2.default.config(e);let s=i?"debug":"none",l=await _crudifysdk2.default.init(t,s);if(l.success===!1)throw new Error(`Crudify initialization failed: ${JSON.stringify(l.errors||"Unknown error")}`);l.apiEndpointAdmin&&l.apiKeyEndpointAdmin&&le.notifyCredentialsReady({apiUrl:l.apiEndpointAdmin,apiKey:l.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}}},ie= exports.q =Ae.getInstance();var at=r=>{let t=new Uint8Array(r);return crypto.getRandomValues(t),Array.from(t,e=>e.toString(36).padStart(2,"0")).join("").substring(0,r)},ot=()=>`file_${Date.now()}_${at(7)}`,di=r=>{let t=r.lastIndexOf("."),e=t>0?r.substring(t):"",i=Date.now(),n=at(6);return`${i}_${n}${e}`},ke=(r,t)=>{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(t&&r.startsWith(t))return r.substring(t.length)}return t&&r.startsWith(t)?r.substring(t.length):r},dn= exports.r =(r={})=>{let{acceptedTypes:t,maxFileSize:e=10*1024*1024,maxFiles:i,minFiles:n=0,visibility:s="private",onUploadComplete:l,onUploadError:o,onFileRemoved:f,onFilesChange:E,mode:b="edit"}=r,[T,m]=_react.useState.call(void 0, []),[I,g]=_react.useState.call(void 0, !1),[A,N]=_react.useState.call(void 0, !1),[x,O]=_react.useState.call(void 0, []),w=_react.useRef.call(void 0, new Map),F=_react.useCallback.call(void 0, ()=>{g(!0)},[]),z=_react.useCallback.call(void 0, ()=>{N(!0),g(!0)},[]),D=_react.useCallback.call(void 0, (c,p)=>{m(d=>d.map(h=>h.id===c?{...h,...p}:h))},[]),S=_react.useCallback.call(void 0, c=>{_optionalChain([E, 'optionalCall', _130 => _130(c)])},[E]),Z=_react.useCallback.call(void 0, c=>t&&t.length>0&&!t.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},[t,e]),V=_react.useCallback.call(void 0, async(c,p)=>{try{if(!ie.isInitialized())throw new Error("Crudify is not initialized. Please wait for the application to finish loading.");let d=di(p.name),y=await _crudifysdk2.default.generateSignedUrl({fileName:d,contentType:p.type,visibility:s});if(!y.success||!y.data)throw new Error("Failed to get upload URL");let h=y.data,{uploadUrl:R,s3Key:k,publicUrl:M}=h;if(!R||!k)throw new Error("Incomplete signed URL response");let Y=k.indexOf("/"),Rt=Y>0?k.substring(Y+1):k;D(c.id,{status:"uploading",progress:0}),await new Promise((pe,B)=>{let U=new XMLHttpRequest;U.upload.addEventListener("progress",_=>{if(_.lengthComputable){let Ct=Math.round(_.loaded/_.total*100);D(c.id,{progress:Ct})}}),U.addEventListener("load",()=>{U.status>=200&&U.status<300?pe():B(new Error(`Upload failed with status ${U.status}`))}),U.addEventListener("error",()=>{B(new Error("Network error during upload"))}),U.addEventListener("abort",()=>{B(new Error("Upload cancelled"))}),U.open("PUT",R),U.setRequestHeader("Content-Type",p.type),U.send(p)});let Nt={status:"completed",progress:100,filePath:Rt,visibility:s,publicUrl:s==="public"?M:void 0,file:void 0};m(pe=>{let B=pe.map(_=>_.id===c.id?{..._,...Nt}:_);S(B);let U=B.find(_=>_.id===c.id);return U&&_optionalChain([l, 'optionalCall', _131 => _131(U)]),B})}catch(d){let y=d instanceof Error?d.message:"Unknown error";D(c.id,{status:"error",progress:0,errorMessage:y}),m(h=>{let R=h.find(k=>k.id===c.id);return R&&_optionalChain([o, 'optionalCall', _132 => _132(R,y)]),h})}},[D,l,o,s]),re=_react.useCallback.call(void 0, async c=>{let p=Array.from(c),d=[];m(y=>{if(i!==void 0){let k=y.filter(Y=>Y.status!=="pendingDeletion"&&Y.status!=="error").length,M=i-k;if(M<=0)return _chunkCR5KJUSTjs.a.warn(`File limit of ${i} already reached`),y;p.length>M&&(p=p.slice(0,M),_chunkCR5KJUSTjs.a.warn(`Only ${M} files will be added to not exceed limit`))}let h=[];for(let k of p){let M=Z(k),Y={id:ot(),name:k.name,size:k.size,contentType:k.type,status:M.valid?"pending":"error",progress:0,createdAt:Date.now(),file:M.valid?k:void 0,errorMessage:M.error,isExisting:!1};h.push(Y)}d=h;let R=[...y,...h];return S(R),R}),setTimeout(()=>{let y=d.filter(h=>h.status==="pending"&&h.file);for(let h of y)if(h.file){let R=V(h,h.file);w.current.set(h.id,R),R.finally(()=>{w.current.delete(h.id)})}},0)},[i,Z,V,S]),lt=_react.useCallback.call(void 0, async c=>{let p=T.find(y=>y.id===c);if(!p)return{needsConfirmation:!1,isExisting:!1};let d=p.isExisting===!0;return b==="create"||!d?{needsConfirmation:!0,isExisting:d}:(O(y=>[...y,c]),m(y=>{let h=y.map(k=>k.id===c?{...k,status:"pendingDeletion"}:k),R=h.filter(k=>k.status!=="pendingDeletion");return S(R),h}),{needsConfirmation:!1,isExisting:d})},[T,b,S]),ct=_react.useCallback.call(void 0, async c=>{let p=T.find(d=>d.id===c);if(!p)return{success:!1,error:"File not found"};if(!p.filePath)return m(d=>{let y=d.filter(h=>h.id!==c);return S(y),y}),{success:!0};try{if(!ie.isInitialized())return{success:!1,error:"Crudify not initialized"};let d=ke(p.filePath);return(await _crudifysdk2.default.disableFile({filePath:d})).success?(m(h=>{let R=h.filter(k=>k.id!==c);return S(R),R}),_optionalChain([f, 'optionalCall', _133 => _133(p)]),{success:!0}):{success:!1,error:"Failed to delete file"}}catch(d){return{success:!1,error:d instanceof Error?d.message:"Unknown error"}}},[T,S,f]),ut=_react.useCallback.call(void 0, c=>{let p=T.find(d=>d.id===c);return!p||!p.isExisting?!1:(O(d=>d.filter(y=>y!==c)),m(d=>{let y=d.map(h=>h.id===c?{...h,status:"completed"}:h);return S(y),y}),!0)},[T,S]),dt=_react.useCallback.call(void 0, ()=>{x.length!==0&&(m(c=>{let p=c.map(d=>x.includes(d.id)?{...d,status:"completed"}:d);return S(p),p}),O([]))},[x,S]),ft=_react.useCallback.call(void 0, async()=>{if(x.length===0)return{success:!0,errors:[]};let c=[],p=[];if(!ie.isInitialized())return{success:!1,errors:["Crudify is not initialized. Please wait for the application to finish loading."]};for(let d of x){let y=T.find(h=>h.id===d);if(!_optionalChain([y, 'optionalAccess', _134 => _134.filePath])){p.push(d);continue}try{let h=ke(y.filePath);(await _crudifysdk2.default.disableFile({filePath:h})).success?(p.push(d),_optionalChain([f, 'optionalCall', _135 => _135(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&&(m(d=>d.filter(h=>!p.includes(h.id))),O(d=>d.filter(y=>!p.includes(y)))),{success:c.length===0,errors:c}},[T,x,f]),gt=_react.useCallback.call(void 0, ()=>{m([]),S([])},[S]),pt=_react.useCallback.call(void 0, async c=>{let p=T.find(y=>y.id===c);if(!p||p.status!=="error"||!p.file){_chunkCR5KJUSTjs.a.warn("Cannot retry: file not found or no original file");return}D(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)})},[T,D,V]),mt=_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(()=>{m(d=>{let y=d.filter(h=>h.status==="completed"&&h.filePath).map(h=>h.filePath);return p(y),d})},0)})},[]),yt=c=>{let p=_optionalChain([c, 'access', _136 => _136.split, 'call', _137 => _137("."), 'access', _138 => _138.pop, 'call', _139 => _139(), 'optionalAccess', _140 => _140.toLowerCase, 'call', _141 => _141()])||"";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"},ht=_react.useCallback.call(void 0, (c,p)=>{let d=c.map(y=>{let h=ke(y.filePath,p),R=h.includes("/public/")||h.startsWith("public/")?"public":"private",k=y.contentType||yt(y.name);return{id:ot(),name:y.name,size:y.size||0,contentType:k,status:"completed",progress:100,filePath:h,visibility:R,createdAt:Date.now(),isExisting:!0}});m(d),S(d)},[S]),Et=_react.useCallback.call(void 0, async c=>{let p=T.find(d=>d.id===c);if(!p||!p.filePath)return null;if(p.visibility==="public"&&p.publicUrl)return p.publicUrl;try{if(!ie.isInitialized())return null;let d=await _crudifysdk2.default.getFileUrl({filePath:p.filePath,expiresIn:3600}),y=d.data;return d.success&&_optionalChain([y, 'optionalAccess', _142 => _142.url])?y.url:null}catch (e13){return null}},[T]),Tt=_react.useMemo.call(void 0, ()=>T.some(c=>c.status==="uploading"||c.status==="pending"),[T]),St=_react.useMemo.call(void 0, ()=>T.filter(c=>c.status==="uploading"||c.status==="pending").length,[T]),vt=_react.useMemo.call(void 0, ()=>T.filter(c=>c.status==="completed"&&c.filePath).map(c=>c.filePath),[T]),q=_react.useMemo.call(void 0, ()=>T.filter(c=>c.status!=="pendingDeletion"),[T]),bt=_react.useMemo.call(void 0, ()=>q.filter(c=>c.status==="completed"||c.status==="pending"||c.status==="uploading").length,[q]),{isValid:It,validationError:At,validationErrorKey:kt,validationErrorParams:xt}=_react.useMemo.call(void 0, ()=>{let c=q.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 i!==void 0&&c>i?{isValid:!1,validationError:"file.validation.maxFilesExceeded",validationErrorKey:"file.validation.maxFilesExceeded",validationErrorParams:{count:i}}:q.some(d=>d.status==="error")?{isValid:!1,validationError:"file.validation.filesWithErrors",validationErrorKey:"file.validation.filesWithErrors",validationErrorParams:{}}:{isValid:!0,validationError:null,validationErrorKey:null,validationErrorParams:{}}},[q,n,i]),wt=x.length>0;return{files:T,activeFiles:q,activeFileCount:bt,isUploading:Tt,pendingCount:St,addFiles:re,removeFile:lt,deleteFileImmediately:ct,restoreFile:ut,clearFiles:gt,retryUpload:pt,isValid:It,validationError:At,validationErrorKey:kt,validationErrorParams:xt,waitForUploads:mt,completedFilePaths:vt,initializeFiles:ht,isTouched:I,markAsTouched:F,isSubmitted:A,markAsSubmitted:z,getPreviewUrl:Et,pendingDeletions:x,hasPendingDeletions:wt,commitDeletions:ft,restorePendingDeletions:dt}};exports.a = v; exports.b = ye; exports.c = W; exports.d = ne; exports.e = Ee; exports.f = Te; exports.g = Je; exports.h = le; exports.i = et; exports.j = tt; exports.k = Vr; exports.l = ni; exports.m = $r; exports.n = qr; exports.o = en; exports.p = Ae; exports.q = ie; exports.r = dn;
@@ -0,0 +1 @@
1
+ import{a as n,g as h,h as m,i as p,j as u,k as y,l}from"./chunk-4ILUXVPW.mjs";var c="crudify_login_storage_version",d=2,g="crudify_login_encryption_salt",a=class{constructor(t="sessionStorage"){this.encryptionKey=null;this.salt=null;this.initPromise=null;this.initialized=!1;this.storage=t==="localStorage"?window.localStorage:window.sessionStorage}async ensureInitialized(){if(!(this.initialized&&this.encryptionKey)){if(this.initPromise){await this.initPromise;return}this.initPromise=this.initialize(),await this.initPromise}}async initialize(){try{parseInt(this.storage.getItem(c)||"1")<d&&(this.clearLegacyData(),this.storage.setItem(c,d.toString()));let e=this.storage.getItem(g);e&&l(`v2:x:${e}:x`)?this.salt=this.base64ToUint8Array(e):(this.salt=y(),this.storage.setItem(g,this.uint8ArrayToBase64(this.salt)));let i=await this.generateFingerprint();this.encryptionKey=await m(i,this.salt),this.initialized=!0}catch(t){n.error("SecureStorage initialization failed",t instanceof Error?t:{message:String(t)}),this.initialized=!1}}async generateFingerprint(){let t=[navigator.userAgent,navigator.language,new Date().getTimezoneOffset().toString(),screen.colorDepth.toString(),screen.width.toString(),screen.height.toString(),"crudify-login"].join("|");return h(t)}clearLegacyData(){let t=[];for(let e=0;e<this.storage.length;e++){let i=this.storage.key(e);i&&!i.startsWith(c)&&!i.startsWith(g)&&t.push(i)}t.forEach(e=>this.storage.removeItem(e))}async setItem(t,e,i){try{if(await this.ensureInitialized(),!this.encryptionKey||!this.salt){n.error("SecureStorage not properly initialized");return}let r=await p(e,this.encryptionKey,this.salt);if(this.storage.setItem(t,r),i){let o=Date.now()+i*60*1e3;this.storage.setItem(`${t}_expiry`,o.toString())}}catch(r){n.error("Failed to encrypt and store data",r instanceof Error?r:{message:String(r)})}}async getItem(t){try{await this.ensureInitialized();let e=`${t}_expiry`,i=this.storage.getItem(e);if(i){let f=parseInt(i,10);if(Date.now()>f)return this.removeItem(t),null}let r=this.storage.getItem(t);if(!r)return null;if(!l(r))return this.removeItem(t),null;let o=await this.generateFingerprint(),s=await u(r,o);return s||(n.warn("Failed to decrypt stored data - may be corrupted"),this.removeItem(t),null)}catch(e){return n.error("Failed to decrypt data",e instanceof Error?e:{message:String(e)}),this.removeItem(t),null}}removeItem(t){this.storage.removeItem(t),this.storage.removeItem(`${t}_expiry`)}clear(){this.storage.clear()}async setToken(t){try{let e=t.split(".");if(e.length===3){let i=JSON.parse(atob(e[1]));if(i.exp){let r=i.exp*1e3,o=Date.now(),s=Math.floor((r-o)/(60*1e3));if(s>0){await this.setItem("authToken",t,s);return}}}}catch{n.warn("Failed to parse token expiry, using default expiry")}await this.setItem("authToken",t,1440)}async getToken(){let t=await this.getItem("authToken");if(t)try{let e=t.split(".");if(e.length===3){let i=JSON.parse(atob(e[1]));if(i.exp){let r=Math.floor(Date.now()/1e3);if(i.exp<r)return this.removeItem("authToken"),null}}}catch{return n.warn("Failed to validate token expiry"),this.removeItem("authToken"),null}return t}async hasValidToken(){return await this.getToken()!==null}async migrateFromLocalStorage(t){let e=window.localStorage.getItem(t);e&&(window.localStorage.removeItem(t),t==="authToken"?await this.setToken(e):await this.setItem(t,e))}uint8ArrayToBase64(t){let e="";for(let i=0;i<t.length;i++)e+=String.fromCharCode(t[i]);return btoa(e)}base64ToUint8Array(t){let e=atob(t),i=new Uint8Array(e.length);for(let r=0;r<e.length;r++)i[r]=e.charCodeAt(r);return i}},I=new a("sessionStorage"),T=new a("localStorage");export{I as a,T as b};
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }var _chunkCHDM7KGHjs = require('./chunk-CHDM7KGH.js');var _chunkMFYHD6S5js = require('./chunk-MFYHD6S5.js');var _react = require('react');var _crudifysdk = require('@nocios/crudify-sdk'); var _crudifysdk2 = _interopRequireDefault(_crudifysdk);var J=(w={})=>{let{autoFetch:c=!0,retryOnError:N=!1,maxRetries:g=3}=w,{isAuthenticated:T,isInitialized:I,sessionData:u,tokens:m}=_chunkCHDM7KGHjs.l.call(void 0, ),[R,d]=_react.useState.call(void 0, null),[p,A]=_react.useState.call(void 0, c&&T),[C,E]=_react.useState.call(void 0, null),f=_react.useRef.call(void 0, null),o=_react.useRef.call(void 0, !0),y=_react.useRef.call(void 0, 0),l=_react.useRef.call(void 0, 0),F=_react.useCallback.call(void 0, ()=>{if(!u)return null;let h=u["cognito:username"];return u.email||(typeof h=="string"?h:null)},[u]),L=_react.useCallback.call(void 0, ()=>{d(null),E(null),A(!1),l.current=0},[]),U=_react.useCallback.call(void 0, async()=>{let h=F();if(!h){o.current&&(E("No user email available from session data"),A(!1));return}if(!I){o.current&&(E("Session not initialized"),A(!1));return}f.current&&f.current.abort();let e=new AbortController;f.current=e;let i=++y.current;try{o.current&&(A(!0),E(null));let s=await _crudifysdk2.default.readItems("users",{filter:{email:h},pagination:{limit:1}});if(i===y.current&&o.current&&!e.signal.aborted){let r=null;if(s.success){let t=s.data;if(Array.isArray(t)&&t.length>0)r=t[0];else if(t&&typeof t=="object"&&!Array.isArray(t)&&_optionalChain([t, 'access', _2 => _2.response, 'optionalAccess', _3 => _3.data]))try{let n=t.response.data,a=typeof n=="string"?JSON.parse(n):n;a&&a.items&&Array.isArray(a.items)&&a.items.length>0&&(r=a.items[0])}catch (e2){}else t&&typeof t=="object"&&!Array.isArray(t)&&t.items&&Array.isArray(t.items)&&t.items.length>0&&(r=t.items[0]);if(!r&&t&&typeof t=="object"&&!Array.isArray(t)&&_optionalChain([t, 'access', _4 => _4.data, 'optionalAccess', _5 => _5.response, 'optionalAccess', _6 => _6.data]))try{let n=t.data.response.data,a=typeof n=="string"?JSON.parse(n):n;a&&a.items&&Array.isArray(a.items)&&a.items.length>0&&(r=a.items[0])}catch (e3){}}r?(d(r),E(null),l.current=0):(E("User profile not found in database"),d(null))}}catch(s){if(i===y.current&&o.current){let r=s;if(r.name==="AbortError")return;N&&l.current<g&&(_optionalChain([r, 'access', _7 => _7.message, 'optionalAccess', _8 => _8.includes, 'call', _9 => _9("Network Error")])||_optionalChain([r, 'access', _10 => _10.message, 'optionalAccess', _11 => _11.includes, 'call', _12 => _12("Failed to fetch")]))?(l.current++,setTimeout(()=>{o.current&&U()},1e3*l.current)):(E("Failed to load user profile from database"),d(null))}}finally{i===y.current&&o.current&&A(!1),f.current===e&&(f.current=null)}},[I,F,N,g]);return _react.useEffect.call(void 0, ()=>{c&&T&&I?U():T||L()},[c,T,I,U,L]),_react.useEffect.call(void 0, ()=>(o.current=!0,()=>{o.current=!1,f.current&&(f.current.abort(),f.current=null)}),[]),{user:{session:u,data:R},loading:p,error:C,refreshProfile:U,clearProfile:L}};var te=()=>{let{isAuthenticated:w,isLoading:c,isInitialized:N,tokens:g,error:T,sessionData:I,login:u,logout:m,refreshTokens:R,clearError:d,getTokenInfo:p,isExpiringSoon:A,expiresIn:C,refreshExpiresIn:E}=_chunkCHDM7KGHjs.l.call(void 0, ),f=_react.useCallback.call(void 0, y=>{y?_chunkMFYHD6S5js.a.warn("useAuth.setToken() is deprecated. Use login() method instead for better security."):m()},[m]),o=_optionalChain([g, 'optionalAccess', _13 => _13.expiresAt])?new Date(g.expiresAt):null;return{isAuthenticated:w,loading:c,error:T,token:_optionalChain([g, 'optionalAccess', _14 => _14.accessToken])||null,user:I,tokenExpiration:o,setToken:f,logout:m,refreshToken:R,login:u,isExpiringSoon:A,expiresIn:C,refreshExpiresIn:E,getTokenInfo:p,clearError:d}};var ae=()=>{let{isInitialized:w,isLoading:c,error:N,isAuthenticated:g,login:T}=_chunkCHDM7KGHjs.l.call(void 0, ),I=_react.useCallback.call(void 0, ()=>w&&!c&&!N,[w,c,N]),u=_react.useCallback.call(void 0, async()=>new Promise((o,y)=>{let l=()=>{I()?o():N?y(new Error(N)):setTimeout(l,100)};l()}),[I,N]),m=_react.useCallback.call(void 0, async()=>{if(!I())throw new Error("System not ready. Check isInitialized, isLoading, and error states.")},[I]),R=_react.useCallback.call(void 0, async(o,y,l)=>(await m(),await _crudifysdk2.default.readItems(o,y||{},l)),[m]),d=_react.useCallback.call(void 0, async(o,y,l)=>(await m(),await _crudifysdk2.default.readItem(o,y,l)),[m]),p=_react.useCallback.call(void 0, async(o,y,l)=>(await m(),await _crudifysdk2.default.createItem(o,y,l)),[m]),A=_react.useCallback.call(void 0, async(o,y,l)=>(await m(),await _crudifysdk2.default.updateItem(o,y,l)),[m]),C=_react.useCallback.call(void 0, async(o,y,l)=>(await m(),await _crudifysdk2.default.deleteItem(o,y,l)),[m]),E=_react.useCallback.call(void 0, async(o,y)=>(await m(),await _crudifysdk2.default.transaction(o,y)),[m]),f=_react.useCallback.call(void 0, async(o,y)=>{try{let l=await T(o,y);return l.success?{success:!0,data:l.tokens}:{success:!1,errors:l.error||"Login failed"}}catch(l){return{success:!1,errors:l instanceof Error?l.message:"Login failed"}}},[T]);return{readItems:R,readItem:d,createItem:p,updateItem:A,deleteItem:C,transaction:E,login:f,isInitialized:w,isInitializing:c,initializationError:N,isReady:I,waitForReady:u}};var Y={INVALID_CREDENTIALS:"warning",UNAUTHORIZED:"warning",INVALID_API_KEY:"error",USER_NOT_FOUND:"warning",USER_NOT_ACTIVE:"warning",NO_PERMISSION:"warning",ITEM_NOT_FOUND:"info",NOT_FOUND:"info",IN_USE:"warning",FIELD_ERROR:"warning",BAD_REQUEST:"warning",INTERNAL_SERVER_ERROR:"error",DATABASE_CONNECTION_ERROR:"error",INVALID_CONFIGURATION:"error",UNKNOWN_OPERATION:"error",TOO_MANY_REQUESTS:"warning"},M={INVALID_CREDENTIALS:"errors.auth.INVALID_CREDENTIALS",UNAUTHORIZED:"errors.auth.UNAUTHORIZED",INVALID_API_KEY:"errors.auth.INVALID_API_KEY",USER_NOT_FOUND:"errors.auth.USER_NOT_FOUND",USER_NOT_ACTIVE:"errors.auth.USER_NOT_ACTIVE",NO_PERMISSION:"errors.auth.NO_PERMISSION",ITEM_NOT_FOUND:"errors.data.ITEM_NOT_FOUND",NOT_FOUND:"errors.data.NOT_FOUND",IN_USE:"errors.data.IN_USE",FIELD_ERROR:"errors.data.FIELD_ERROR",BAD_REQUEST:"errors.data.BAD_REQUEST",INTERNAL_SERVER_ERROR:"errors.system.INTERNAL_SERVER_ERROR",DATABASE_CONNECTION_ERROR:"errors.system.DATABASE_CONNECTION_ERROR",INVALID_CONFIGURATION:"errors.system.INVALID_CONFIGURATION",UNKNOWN_OPERATION:"errors.system.UNKNOWN_OPERATION",TOO_MANY_REQUESTS:"errors.system.TOO_MANY_REQUESTS"},de= exports.d =(w={})=>{let{showNotification:c}=_chunkCHDM7KGHjs.g.call(void 0, ),{showSuccessNotifications:N=!1,showErrorNotifications:g=!0,customErrorMessages:T={},defaultErrorMessage:I="Ha ocurrido un error inesperado",autoHideDuration:u=6e3,appStructure:m=[],translateFn:R=e=>e}=w,d=_react.useCallback.call(void 0, e=>{if(!e.success&&e.errors&&(Object.keys(e.errors).some(r=>r!=="_error"&&r!=="_graphql"&&r!=="_transaction")||_optionalChain([e, 'access', _15 => _15.errors, 'access', _16 => _16._transaction, 'optionalAccess', _17 => _17.includes, 'call', _18 => _18("ONE_OR_MORE_OPERATIONS_FAILED")])||_optionalChain([e, 'access', _19 => _19.errors, 'access', _20 => _20._error, 'optionalAccess', _21 => _21.includes, 'call', _22 => _22("TOO_MANY_REQUESTS")])))return!1;let i=e.data;return!(!e.success&&_optionalChain([i, 'optionalAccess', _23 => _23.response, 'optionalAccess', _24 => _24.status])==="TOO_MANY_REQUESTS")},[]),p=_react.useCallback.call(void 0, (e,i)=>{let s=R(e);return s===e?i||R("error.unknown"):s},[R]),A=_react.useCallback.call(void 0, e=>["create","update","delete"].includes(e),[]),C=_react.useCallback.call(void 0, (e,i)=>N?A(e)&&i?!0:m.some(s=>s.key===e):!1,[N,m,A]),E=_react.useCallback.call(void 0, (e,i,s)=>{let r=_optionalChain([s, 'optionalAccess', _25 => _25.key])&&typeof s.key=="string"?s.key:e,t=`action.onSuccess.${r}`,n=p(t);if(n!==R("error.unknown")){if(A(r)&&i){let a=`action.${i}Singular`,O=p(a);if(O!==R("error.unknown"))return R(t,{item:O});{let D=`action.onSuccess.${r}WithoutItem`,x=p(D);return x!==R("error.unknown")?x:n}}return n}return R("base.success.transaction")},[p,R,A]),f=_react.useCallback.call(void 0, e=>{if(e.errorCode&&T[e.errorCode])return T[e.errorCode];if(e.errorCode&&M[e.errorCode])return p(M[e.errorCode]);if(e.errorCode){let i=[`errors.auth.${e.errorCode}`,`errors.data.${e.errorCode}`,`errors.system.${e.errorCode}`,`errors.${e.errorCode}`];for(let s of i){let r=p(s);if(r!==R("error.unknown"))return r}}if(typeof e.data=="string"&&e.data.startsWith("errors.")){let i=p(e.data);if(i!==R("error.unknown"))return i}if(e.errors&&Object.keys(e.errors).length>0){let i=Object.keys(e.errors);if(i.length===1&&i[0]==="_transaction"){let s=e.errors._transaction;if(_optionalChain([s, 'optionalAccess', _26 => _26.includes, 'call', _27 => _27("ONE_OR_MORE_OPERATIONS_FAILED")]))return"";if(Array.isArray(s)&&s.length>0){let r=s[0];if(typeof r=="string"&&r!=="ONE_OR_MORE_OPERATIONS_FAILED")try{let t=JSON.parse(r);if(Array.isArray(t)&&t.length>0){let n=t[0];if(_optionalChain([n, 'optionalAccess', _28 => _28.response, 'optionalAccess', _29 => _29.errorCode])){let a=n.response.errorCode;if(M[a])return p(M[a]);let O=[`errors.auth.${a}`,`errors.data.${a}`,`errors.system.${a}`,`errors.${a}`];for(let D of O){let x=p(D);if(x!==p("error.unknown"))return x}}if(_optionalChain([n, 'optionalAccess', _30 => _30.response, 'optionalAccess', _31 => _31.data]))return n.response.data}if(_optionalChain([t, 'optionalAccess', _32 => _32.response, 'optionalAccess', _33 => _33.message])){let n=t.response.message.toLowerCase();return n.includes("expired")?p("resetPassword.linkExpired","El enlace ha expirado"):n.includes("invalid")?p("resetPassword.invalidCode","C\xF3digo inv\xE1lido"):t.response.message}}catch (e4){return r.toLowerCase().includes("expired")?p("resetPassword.linkExpired","El enlace ha expirado"):r.toLowerCase().includes("invalid")?p("resetPassword.invalidCode","C\xF3digo inv\xE1lido"):r}}return p("error.transaction","Error en la operaci\xF3n")}if(i.length===1&&i[0]==="_error"){let s=e.errors._error;return Array.isArray(s)?s[0]:String(s)}return i.length===1&&i[0]==="_graphql"?p("errors.system.DATABASE_CONNECTION_ERROR"):`${p("errors.data.FIELD_ERROR")}: ${i.join(", ")}`}return I||R("error.unknown")},[T,I,R,p]),o=_react.useCallback.call(void 0, e=>e.errorCode&&Y[e.errorCode]?Y[e.errorCode]:"error",[]),y=_react.useCallback.call(void 0, async(e,i,s)=>{let r=await _crudifysdk2.default.createItem(e,i,s);if(!r.success&&g&&d(r)){let t=f(r),n=o(r);c(t,n,{autoHideDuration:u})}else if(r.success){let t=_optionalChain([s, 'optionalAccess', _34 => _34.actionConfig]),n=_optionalChain([t, 'optionalAccess', _35 => _35.key])||"create",a=_optionalChain([t, 'optionalAccess', _36 => _36.moduleKey])||e;if(C(n,a)){let O=E(n,a,t);c(O,"success",{autoHideDuration:u})}}return r},[g,C,c,f,o,E,u,d]),l=_react.useCallback.call(void 0, async(e,i,s)=>{let r=await _crudifysdk2.default.updateItem(e,i,s),t=_optionalChain([s, 'optionalAccess', _37 => _37.skipNotifications])===!0;if(!t&&!r.success&&g&&d(r)){let n=f(r),a=o(r);c(n,a,{autoHideDuration:u})}else if(!t&&r.success){let n=_optionalChain([s, 'optionalAccess', _38 => _38.actionConfig]),a=_optionalChain([n, 'optionalAccess', _39 => _39.key])||"update",O=_optionalChain([n, 'optionalAccess', _40 => _40.moduleKey])||e;if(C(a,O)){let D=E(a,O,n);c(D,"success",{autoHideDuration:u})}}return r},[g,C,c,f,o,E,u,d]),F=_react.useCallback.call(void 0, async(e,i,s)=>{let r=await _crudifysdk2.default.deleteItem(e,i,s);if(!r.success&&g&&d(r)){let t=f(r),n=o(r);c(t,n,{autoHideDuration:u})}else if(r.success){let t=_optionalChain([s, 'optionalAccess', _41 => _41.actionConfig]),n=_optionalChain([t, 'optionalAccess', _42 => _42.key])||"delete",a=_optionalChain([t, 'optionalAccess', _43 => _43.moduleKey])||e;if(C(n,a)){let O=E(n,a,t);c(O,"success",{autoHideDuration:u})}}return r},[g,C,c,f,o,E,u,d]),L=_react.useCallback.call(void 0, async(e,i,s)=>{let r=await _crudifysdk2.default.readItem(e,i,s);if(!r.success&&g&&d(r)){let t=f(r),n=o(r);c(t,n,{autoHideDuration:u})}return r},[g,c,f,o,u,d]),U=_react.useCallback.call(void 0, async(e,i,s)=>{let r=await _crudifysdk2.default.readItems(e,i,s);if(!r.success&&g&&d(r)){let t=f(r),n=o(r);c(t,n,{autoHideDuration:u})}return r},[g,c,f,o,u,d]),q=_react.useCallback.call(void 0, async(e,i)=>{let s=await _crudifysdk2.default.transaction(e,i),r=_optionalChain([i, 'optionalAccess', _44 => _44.skipNotifications])===!0;if(!r&&!s.success&&g&&d(s)){let t=f(s),n=o(s);c(t,n,{autoHideDuration:u})}else if(!r&&s.success){let t="transaction",n,a=null;if(_optionalChain([i, 'optionalAccess', _45 => _45.actionConfig]))a=i.actionConfig,t=a.key,n=a.moduleKey;else if(Array.isArray(e)&&e.length>0&&"operation"in e[0]&&e[0].operation){t=e[0].operation;let O=m.find(D=>D.key===t);O&&(a=O,n=O.moduleKey)}if(C(t,n)){let O=E(t,n,_nullishCoalesce(a, () => (void 0)));c(O,"success",{autoHideDuration:u})}}return s},[g,C,c,f,o,E,u,d,m]),h=_react.useCallback.call(void 0, (e,i)=>{if(!e.success&&g&&d(e)){let s=f(e),r=o(e);c(s,r,{autoHideDuration:u})}else e.success&&N&&i&&c(i,"success",{autoHideDuration:u});return e},[g,N,c,f,o,u,d,R]);return{createItem:y,updateItem:l,deleteItem:F,readItem:L,readItems:U,transaction:q,handleResponse:h,getErrorMessage:f,getErrorSeverity:o,shouldShowNotification:d}};exports.a = J; exports.b = te; exports.c = ae; exports.d = de;
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 _chunkLK6QVSG4js = require('./chunk-LK6QVSG4.js');var _chunkCR5KJUSTjs = require('./chunk-CR5KJUST.js');var _react = require('react');var _crudifysdk = require('@nocios/crudify-sdk'); var _crudifysdk2 = _interopRequireDefault(_crudifysdk);var J=(w={})=>{let{autoFetch:c=!0,retryOnError:N=!1,maxRetries:g=3}=w,{isAuthenticated:T,isInitialized:I,sessionData:u,tokens:m}=_chunkLK6QVSG4js.l.call(void 0, ),[R,d]=_react.useState.call(void 0, null),[p,A]=_react.useState.call(void 0, c&&T),[C,E]=_react.useState.call(void 0, null),f=_react.useRef.call(void 0, null),o=_react.useRef.call(void 0, !0),y=_react.useRef.call(void 0, 0),l=_react.useRef.call(void 0, 0),F=_react.useCallback.call(void 0, ()=>{if(!u)return null;let h=u["cognito:username"];return u.email||(typeof h=="string"?h:null)},[u]),L=_react.useCallback.call(void 0, ()=>{d(null),E(null),A(!1),l.current=0},[]),U=_react.useCallback.call(void 0, async()=>{let h=F();if(!h){o.current&&(E("No user email available from session data"),A(!1));return}if(!I){o.current&&(E("Session not initialized"),A(!1));return}f.current&&f.current.abort();let e=new AbortController;f.current=e;let i=++y.current;try{o.current&&(A(!0),E(null));let s=await _crudifysdk2.default.readItems("users",{filter:{email:h},pagination:{limit:1}});if(i===y.current&&o.current&&!e.signal.aborted){let r=null;if(s.success){let t=s.data;if(Array.isArray(t)&&t.length>0)r=t[0];else if(t&&typeof t=="object"&&!Array.isArray(t)&&_optionalChain([t, 'access', _2 => _2.response, 'optionalAccess', _3 => _3.data]))try{let n=t.response.data,a=typeof n=="string"?JSON.parse(n):n;a&&a.items&&Array.isArray(a.items)&&a.items.length>0&&(r=a.items[0])}catch (e2){}else t&&typeof t=="object"&&!Array.isArray(t)&&t.items&&Array.isArray(t.items)&&t.items.length>0&&(r=t.items[0]);if(!r&&t&&typeof t=="object"&&!Array.isArray(t)&&_optionalChain([t, 'access', _4 => _4.data, 'optionalAccess', _5 => _5.response, 'optionalAccess', _6 => _6.data]))try{let n=t.data.response.data,a=typeof n=="string"?JSON.parse(n):n;a&&a.items&&Array.isArray(a.items)&&a.items.length>0&&(r=a.items[0])}catch (e3){}}r?(d(r),E(null),l.current=0):(E("User profile not found in database"),d(null))}}catch(s){if(i===y.current&&o.current){let r=s;if(r.name==="AbortError")return;N&&l.current<g&&(_optionalChain([r, 'access', _7 => _7.message, 'optionalAccess', _8 => _8.includes, 'call', _9 => _9("Network Error")])||_optionalChain([r, 'access', _10 => _10.message, 'optionalAccess', _11 => _11.includes, 'call', _12 => _12("Failed to fetch")]))?(l.current++,setTimeout(()=>{o.current&&U()},1e3*l.current)):(E("Failed to load user profile from database"),d(null))}}finally{i===y.current&&o.current&&A(!1),f.current===e&&(f.current=null)}},[I,F,N,g]);return _react.useEffect.call(void 0, ()=>{c&&T&&I?U():T||L()},[c,T,I,U,L]),_react.useEffect.call(void 0, ()=>(o.current=!0,()=>{o.current=!1,f.current&&(f.current.abort(),f.current=null)}),[]),{user:{session:u,data:R},loading:p,error:C,refreshProfile:U,clearProfile:L}};var te=()=>{let{isAuthenticated:w,isLoading:c,isInitialized:N,tokens:g,error:T,sessionData:I,login:u,logout:m,refreshTokens:R,clearError:d,getTokenInfo:p,isExpiringSoon:A,expiresIn:C,refreshExpiresIn:E}=_chunkLK6QVSG4js.l.call(void 0, ),f=_react.useCallback.call(void 0, y=>{y?_chunkCR5KJUSTjs.a.warn("useAuth.setToken() is deprecated. Use login() method instead for better security."):m()},[m]),o=_optionalChain([g, 'optionalAccess', _13 => _13.expiresAt])?new Date(g.expiresAt):null;return{isAuthenticated:w,loading:c,error:T,token:_optionalChain([g, 'optionalAccess', _14 => _14.accessToken])||null,user:I,tokenExpiration:o,setToken:f,logout:m,refreshToken:R,login:u,isExpiringSoon:A,expiresIn:C,refreshExpiresIn:E,getTokenInfo:p,clearError:d}};var ae=()=>{let{isInitialized:w,isLoading:c,error:N,isAuthenticated:g,login:T}=_chunkLK6QVSG4js.l.call(void 0, ),I=_react.useCallback.call(void 0, ()=>w&&!c&&!N,[w,c,N]),u=_react.useCallback.call(void 0, async()=>new Promise((o,y)=>{let l=()=>{I()?o():N?y(new Error(N)):setTimeout(l,100)};l()}),[I,N]),m=_react.useCallback.call(void 0, async()=>{if(!I())throw new Error("System not ready. Check isInitialized, isLoading, and error states.")},[I]),R=_react.useCallback.call(void 0, async(o,y,l)=>(await m(),await _crudifysdk2.default.readItems(o,y||{},l)),[m]),d=_react.useCallback.call(void 0, async(o,y,l)=>(await m(),await _crudifysdk2.default.readItem(o,y,l)),[m]),p=_react.useCallback.call(void 0, async(o,y,l)=>(await m(),await _crudifysdk2.default.createItem(o,y,l)),[m]),A=_react.useCallback.call(void 0, async(o,y,l)=>(await m(),await _crudifysdk2.default.updateItem(o,y,l)),[m]),C=_react.useCallback.call(void 0, async(o,y,l)=>(await m(),await _crudifysdk2.default.deleteItem(o,y,l)),[m]),E=_react.useCallback.call(void 0, async(o,y)=>(await m(),await _crudifysdk2.default.transaction(o,y)),[m]),f=_react.useCallback.call(void 0, async(o,y)=>{try{let l=await T(o,y);return l.success?{success:!0,data:l.tokens}:{success:!1,errors:l.error||"Login failed"}}catch(l){return{success:!1,errors:l instanceof Error?l.message:"Login failed"}}},[T]);return{readItems:R,readItem:d,createItem:p,updateItem:A,deleteItem:C,transaction:E,login:f,isInitialized:w,isInitializing:c,initializationError:N,isReady:I,waitForReady:u}};var Y={INVALID_CREDENTIALS:"warning",UNAUTHORIZED:"warning",INVALID_API_KEY:"error",USER_NOT_FOUND:"warning",USER_NOT_ACTIVE:"warning",NO_PERMISSION:"warning",ITEM_NOT_FOUND:"info",NOT_FOUND:"info",IN_USE:"warning",FIELD_ERROR:"warning",BAD_REQUEST:"warning",INTERNAL_SERVER_ERROR:"error",DATABASE_CONNECTION_ERROR:"error",INVALID_CONFIGURATION:"error",UNKNOWN_OPERATION:"error",TOO_MANY_REQUESTS:"warning"},M={INVALID_CREDENTIALS:"errors.auth.INVALID_CREDENTIALS",UNAUTHORIZED:"errors.auth.UNAUTHORIZED",INVALID_API_KEY:"errors.auth.INVALID_API_KEY",USER_NOT_FOUND:"errors.auth.USER_NOT_FOUND",USER_NOT_ACTIVE:"errors.auth.USER_NOT_ACTIVE",NO_PERMISSION:"errors.auth.NO_PERMISSION",ITEM_NOT_FOUND:"errors.data.ITEM_NOT_FOUND",NOT_FOUND:"errors.data.NOT_FOUND",IN_USE:"errors.data.IN_USE",FIELD_ERROR:"errors.data.FIELD_ERROR",BAD_REQUEST:"errors.data.BAD_REQUEST",INTERNAL_SERVER_ERROR:"errors.system.INTERNAL_SERVER_ERROR",DATABASE_CONNECTION_ERROR:"errors.system.DATABASE_CONNECTION_ERROR",INVALID_CONFIGURATION:"errors.system.INVALID_CONFIGURATION",UNKNOWN_OPERATION:"errors.system.UNKNOWN_OPERATION",TOO_MANY_REQUESTS:"errors.system.TOO_MANY_REQUESTS"},de= exports.d =(w={})=>{let{showNotification:c}=_chunkLK6QVSG4js.g.call(void 0, ),{showSuccessNotifications:N=!1,showErrorNotifications:g=!0,customErrorMessages:T={},defaultErrorMessage:I="Ha ocurrido un error inesperado",autoHideDuration:u=6e3,appStructure:m=[],translateFn:R=e=>e}=w,d=_react.useCallback.call(void 0, e=>{if(!e.success&&e.errors&&(Object.keys(e.errors).some(r=>r!=="_error"&&r!=="_graphql"&&r!=="_transaction")||_optionalChain([e, 'access', _15 => _15.errors, 'access', _16 => _16._transaction, 'optionalAccess', _17 => _17.includes, 'call', _18 => _18("ONE_OR_MORE_OPERATIONS_FAILED")])||_optionalChain([e, 'access', _19 => _19.errors, 'access', _20 => _20._error, 'optionalAccess', _21 => _21.includes, 'call', _22 => _22("TOO_MANY_REQUESTS")])))return!1;let i=e.data;return!(!e.success&&_optionalChain([i, 'optionalAccess', _23 => _23.response, 'optionalAccess', _24 => _24.status])==="TOO_MANY_REQUESTS")},[]),p=_react.useCallback.call(void 0, (e,i)=>{let s=R(e);return s===e?i||R("error.unknown"):s},[R]),A=_react.useCallback.call(void 0, e=>["create","update","delete"].includes(e),[]),C=_react.useCallback.call(void 0, (e,i)=>N?A(e)&&i?!0:m.some(s=>s.key===e):!1,[N,m,A]),E=_react.useCallback.call(void 0, (e,i,s)=>{let r=_optionalChain([s, 'optionalAccess', _25 => _25.key])&&typeof s.key=="string"?s.key:e,t=`action.onSuccess.${r}`,n=p(t);if(n!==R("error.unknown")){if(A(r)&&i){let a=`action.${i}Singular`,O=p(a);if(O!==R("error.unknown"))return R(t,{item:O});{let D=`action.onSuccess.${r}WithoutItem`,x=p(D);return x!==R("error.unknown")?x:n}}return n}return R("base.success.transaction")},[p,R,A]),f=_react.useCallback.call(void 0, e=>{if(e.errorCode&&T[e.errorCode])return T[e.errorCode];if(e.errorCode&&M[e.errorCode])return p(M[e.errorCode]);if(e.errorCode){let i=[`errors.auth.${e.errorCode}`,`errors.data.${e.errorCode}`,`errors.system.${e.errorCode}`,`errors.${e.errorCode}`];for(let s of i){let r=p(s);if(r!==R("error.unknown"))return r}}if(typeof e.data=="string"&&e.data.startsWith("errors.")){let i=p(e.data);if(i!==R("error.unknown"))return i}if(e.errors&&Object.keys(e.errors).length>0){let i=Object.keys(e.errors);if(i.length===1&&i[0]==="_transaction"){let s=e.errors._transaction;if(_optionalChain([s, 'optionalAccess', _26 => _26.includes, 'call', _27 => _27("ONE_OR_MORE_OPERATIONS_FAILED")]))return"";if(Array.isArray(s)&&s.length>0){let r=s[0];if(typeof r=="string"&&r!=="ONE_OR_MORE_OPERATIONS_FAILED")try{let t=JSON.parse(r);if(Array.isArray(t)&&t.length>0){let n=t[0];if(_optionalChain([n, 'optionalAccess', _28 => _28.response, 'optionalAccess', _29 => _29.errorCode])){let a=n.response.errorCode;if(M[a])return p(M[a]);let O=[`errors.auth.${a}`,`errors.data.${a}`,`errors.system.${a}`,`errors.${a}`];for(let D of O){let x=p(D);if(x!==p("error.unknown"))return x}}if(_optionalChain([n, 'optionalAccess', _30 => _30.response, 'optionalAccess', _31 => _31.data]))return n.response.data}if(_optionalChain([t, 'optionalAccess', _32 => _32.response, 'optionalAccess', _33 => _33.message])){let n=t.response.message.toLowerCase();return n.includes("expired")?p("resetPassword.linkExpired","El enlace ha expirado"):n.includes("invalid")?p("resetPassword.invalidCode","C\xF3digo inv\xE1lido"):t.response.message}}catch (e4){return r.toLowerCase().includes("expired")?p("resetPassword.linkExpired","El enlace ha expirado"):r.toLowerCase().includes("invalid")?p("resetPassword.invalidCode","C\xF3digo inv\xE1lido"):r}}return p("error.transaction","Error en la operaci\xF3n")}if(i.length===1&&i[0]==="_error"){let s=e.errors._error;return Array.isArray(s)?s[0]:String(s)}return i.length===1&&i[0]==="_graphql"?p("errors.system.DATABASE_CONNECTION_ERROR"):`${p("errors.data.FIELD_ERROR")}: ${i.join(", ")}`}return I||R("error.unknown")},[T,I,R,p]),o=_react.useCallback.call(void 0, e=>e.errorCode&&Y[e.errorCode]?Y[e.errorCode]:"error",[]),y=_react.useCallback.call(void 0, async(e,i,s)=>{let r=await _crudifysdk2.default.createItem(e,i,s);if(!r.success&&g&&d(r)){let t=f(r),n=o(r);c(t,n,{autoHideDuration:u})}else if(r.success){let t=_optionalChain([s, 'optionalAccess', _34 => _34.actionConfig]),n=_optionalChain([t, 'optionalAccess', _35 => _35.key])||"create",a=_optionalChain([t, 'optionalAccess', _36 => _36.moduleKey])||e;if(C(n,a)){let O=E(n,a,t);c(O,"success",{autoHideDuration:u})}}return r},[g,C,c,f,o,E,u,d]),l=_react.useCallback.call(void 0, async(e,i,s)=>{let r=await _crudifysdk2.default.updateItem(e,i,s),t=_optionalChain([s, 'optionalAccess', _37 => _37.skipNotifications])===!0;if(!t&&!r.success&&g&&d(r)){let n=f(r),a=o(r);c(n,a,{autoHideDuration:u})}else if(!t&&r.success){let n=_optionalChain([s, 'optionalAccess', _38 => _38.actionConfig]),a=_optionalChain([n, 'optionalAccess', _39 => _39.key])||"update",O=_optionalChain([n, 'optionalAccess', _40 => _40.moduleKey])||e;if(C(a,O)){let D=E(a,O,n);c(D,"success",{autoHideDuration:u})}}return r},[g,C,c,f,o,E,u,d]),F=_react.useCallback.call(void 0, async(e,i,s)=>{let r=await _crudifysdk2.default.deleteItem(e,i,s);if(!r.success&&g&&d(r)){let t=f(r),n=o(r);c(t,n,{autoHideDuration:u})}else if(r.success){let t=_optionalChain([s, 'optionalAccess', _41 => _41.actionConfig]),n=_optionalChain([t, 'optionalAccess', _42 => _42.key])||"delete",a=_optionalChain([t, 'optionalAccess', _43 => _43.moduleKey])||e;if(C(n,a)){let O=E(n,a,t);c(O,"success",{autoHideDuration:u})}}return r},[g,C,c,f,o,E,u,d]),L=_react.useCallback.call(void 0, async(e,i,s)=>{let r=await _crudifysdk2.default.readItem(e,i,s);if(!r.success&&g&&d(r)){let t=f(r),n=o(r);c(t,n,{autoHideDuration:u})}return r},[g,c,f,o,u,d]),U=_react.useCallback.call(void 0, async(e,i,s)=>{let r=await _crudifysdk2.default.readItems(e,i,s);if(!r.success&&g&&d(r)){let t=f(r),n=o(r);c(t,n,{autoHideDuration:u})}return r},[g,c,f,o,u,d]),q=_react.useCallback.call(void 0, async(e,i)=>{let s=await _crudifysdk2.default.transaction(e,i),r=_optionalChain([i, 'optionalAccess', _44 => _44.skipNotifications])===!0;if(!r&&!s.success&&g&&d(s)){let t=f(s),n=o(s);c(t,n,{autoHideDuration:u})}else if(!r&&s.success){let t="transaction",n,a=null;if(_optionalChain([i, 'optionalAccess', _45 => _45.actionConfig]))a=i.actionConfig,t=a.key,n=a.moduleKey;else if(Array.isArray(e)&&e.length>0&&"operation"in e[0]&&e[0].operation){t=e[0].operation;let O=m.find(D=>D.key===t);O&&(a=O,n=O.moduleKey)}if(C(t,n)){let O=E(t,n,_nullishCoalesce(a, () => (void 0)));c(O,"success",{autoHideDuration:u})}}return s},[g,C,c,f,o,E,u,d,m]),h=_react.useCallback.call(void 0, (e,i)=>{if(!e.success&&g&&d(e)){let s=f(e),r=o(e);c(s,r,{autoHideDuration:u})}else e.success&&N&&i&&c(i,"success",{autoHideDuration:u});return e},[g,N,c,f,o,u,d,R]);return{createItem:y,updateItem:l,deleteItem:F,readItem:L,readItems:U,transaction:q,handleResponse:h,getErrorMessage:f,getErrorSeverity:o,shouldShowNotification:d}};exports.a = J; exports.b = te; exports.c = ae; exports.d = de;
@@ -1 +1 @@
1
- import{g as $,l as k}from"./chunk-NBQH6QOU.mjs";import{a as V}from"./chunk-MGJZTOEM.mjs";import{useState as K,useEffect as z,useCallback as j,useRef as v}from"react";import Q from"@nocios/crudify-sdk";var J=(w={})=>{let{autoFetch:c=!0,retryOnError:N=!1,maxRetries:g=3}=w,{isAuthenticated:T,isInitialized:I,sessionData:u,tokens:m}=k(),[R,d]=K(null),[p,A]=K(c&&T),[C,E]=K(null),f=v(null),o=v(!0),y=v(0),l=v(0),F=j(()=>{if(!u)return null;let h=u["cognito:username"];return u.email||(typeof h=="string"?h:null)},[u]),L=j(()=>{d(null),E(null),A(!1),l.current=0},[]),U=j(async()=>{let h=F();if(!h){o.current&&(E("No user email available from session data"),A(!1));return}if(!I){o.current&&(E("Session not initialized"),A(!1));return}f.current&&f.current.abort();let e=new AbortController;f.current=e;let i=++y.current;try{o.current&&(A(!0),E(null));let s=await Q.readItems("users",{filter:{email:h},pagination:{limit:1}});if(i===y.current&&o.current&&!e.signal.aborted){let r=null;if(s.success){let t=s.data;if(Array.isArray(t)&&t.length>0)r=t[0];else if(t&&typeof t=="object"&&!Array.isArray(t)&&t.response?.data)try{let n=t.response.data,a=typeof n=="string"?JSON.parse(n):n;a&&a.items&&Array.isArray(a.items)&&a.items.length>0&&(r=a.items[0])}catch{}else t&&typeof t=="object"&&!Array.isArray(t)&&t.items&&Array.isArray(t.items)&&t.items.length>0&&(r=t.items[0]);if(!r&&t&&typeof t=="object"&&!Array.isArray(t)&&t.data?.response?.data)try{let n=t.data.response.data,a=typeof n=="string"?JSON.parse(n):n;a&&a.items&&Array.isArray(a.items)&&a.items.length>0&&(r=a.items[0])}catch{}}r?(d(r),E(null),l.current=0):(E("User profile not found in database"),d(null))}}catch(s){if(i===y.current&&o.current){let r=s;if(r.name==="AbortError")return;N&&l.current<g&&(r.message?.includes("Network Error")||r.message?.includes("Failed to fetch"))?(l.current++,setTimeout(()=>{o.current&&U()},1e3*l.current)):(E("Failed to load user profile from database"),d(null))}}finally{i===y.current&&o.current&&A(!1),f.current===e&&(f.current=null)}},[I,F,N,g]);return z(()=>{c&&T&&I?U():T||L()},[c,T,I,U,L]),z(()=>(o.current=!0,()=>{o.current=!1,f.current&&(f.current.abort(),f.current=null)}),[]),{user:{session:u,data:R},loading:p,error:C,refreshProfile:U,clearProfile:L}};import{useCallback as W}from"react";var te=()=>{let{isAuthenticated:w,isLoading:c,isInitialized:N,tokens:g,error:T,sessionData:I,login:u,logout:m,refreshTokens:R,clearError:d,getTokenInfo:p,isExpiringSoon:A,expiresIn:C,refreshExpiresIn:E}=k(),f=W(y=>{y?V.warn("useAuth.setToken() is deprecated. Use login() method instead for better security."):m()},[m]),o=g?.expiresAt?new Date(g.expiresAt):null;return{isAuthenticated:w,loading:c,error:T,token:g?.accessToken||null,user:I,tokenExpiration:o,setToken:f,logout:m,refreshToken:R,login:u,isExpiringSoon:A,expiresIn:C,refreshExpiresIn:E,getTokenInfo:p,clearError:d}};import{useCallback as S}from"react";import b from"@nocios/crudify-sdk";var ae=()=>{let{isInitialized:w,isLoading:c,error:N,isAuthenticated:g,login:T}=k(),I=S(()=>w&&!c&&!N,[w,c,N]),u=S(async()=>new Promise((o,y)=>{let l=()=>{I()?o():N?y(new Error(N)):setTimeout(l,100)};l()}),[I,N]),m=S(async()=>{if(!I())throw new Error("System not ready. Check isInitialized, isLoading, and error states.")},[I]),R=S(async(o,y,l)=>(await m(),await b.readItems(o,y||{},l)),[m]),d=S(async(o,y,l)=>(await m(),await b.readItem(o,y,l)),[m]),p=S(async(o,y,l)=>(await m(),await b.createItem(o,y,l)),[m]),A=S(async(o,y,l)=>(await m(),await b.updateItem(o,y,l)),[m]),C=S(async(o,y,l)=>(await m(),await b.deleteItem(o,y,l)),[m]),E=S(async(o,y)=>(await m(),await b.transaction(o,y)),[m]),f=S(async(o,y)=>{try{let l=await T(o,y);return l.success?{success:!0,data:l.tokens}:{success:!1,errors:l.error||"Login failed"}}catch(l){return{success:!1,errors:l instanceof Error?l.message:"Login failed"}}},[T]);return{readItems:R,readItem:d,createItem:p,updateItem:A,deleteItem:C,transaction:E,login:f,isInitialized:w,isInitializing:c,initializationError:N,isReady:I,waitForReady:u}};import{useCallback as _}from"react";import P from"@nocios/crudify-sdk";var Y={INVALID_CREDENTIALS:"warning",UNAUTHORIZED:"warning",INVALID_API_KEY:"error",USER_NOT_FOUND:"warning",USER_NOT_ACTIVE:"warning",NO_PERMISSION:"warning",ITEM_NOT_FOUND:"info",NOT_FOUND:"info",IN_USE:"warning",FIELD_ERROR:"warning",BAD_REQUEST:"warning",INTERNAL_SERVER_ERROR:"error",DATABASE_CONNECTION_ERROR:"error",INVALID_CONFIGURATION:"error",UNKNOWN_OPERATION:"error",TOO_MANY_REQUESTS:"warning"},M={INVALID_CREDENTIALS:"errors.auth.INVALID_CREDENTIALS",UNAUTHORIZED:"errors.auth.UNAUTHORIZED",INVALID_API_KEY:"errors.auth.INVALID_API_KEY",USER_NOT_FOUND:"errors.auth.USER_NOT_FOUND",USER_NOT_ACTIVE:"errors.auth.USER_NOT_ACTIVE",NO_PERMISSION:"errors.auth.NO_PERMISSION",ITEM_NOT_FOUND:"errors.data.ITEM_NOT_FOUND",NOT_FOUND:"errors.data.NOT_FOUND",IN_USE:"errors.data.IN_USE",FIELD_ERROR:"errors.data.FIELD_ERROR",BAD_REQUEST:"errors.data.BAD_REQUEST",INTERNAL_SERVER_ERROR:"errors.system.INTERNAL_SERVER_ERROR",DATABASE_CONNECTION_ERROR:"errors.system.DATABASE_CONNECTION_ERROR",INVALID_CONFIGURATION:"errors.system.INVALID_CONFIGURATION",UNKNOWN_OPERATION:"errors.system.UNKNOWN_OPERATION",TOO_MANY_REQUESTS:"errors.system.TOO_MANY_REQUESTS"},de=(w={})=>{let{showNotification:c}=$(),{showSuccessNotifications:N=!1,showErrorNotifications:g=!0,customErrorMessages:T={},defaultErrorMessage:I="Ha ocurrido un error inesperado",autoHideDuration:u=6e3,appStructure:m=[],translateFn:R=e=>e}=w,d=_(e=>{if(!e.success&&e.errors&&(Object.keys(e.errors).some(r=>r!=="_error"&&r!=="_graphql"&&r!=="_transaction")||e.errors._transaction?.includes("ONE_OR_MORE_OPERATIONS_FAILED")||e.errors._error?.includes("TOO_MANY_REQUESTS")))return!1;let i=e.data;return!(!e.success&&i?.response?.status==="TOO_MANY_REQUESTS")},[]),p=_((e,i)=>{let s=R(e);return s===e?i||R("error.unknown"):s},[R]),A=_(e=>["create","update","delete"].includes(e),[]),C=_((e,i)=>N?A(e)&&i?!0:m.some(s=>s.key===e):!1,[N,m,A]),E=_((e,i,s)=>{let r=s?.key&&typeof s.key=="string"?s.key:e,t=`action.onSuccess.${r}`,n=p(t);if(n!==R("error.unknown")){if(A(r)&&i){let a=`action.${i}Singular`,O=p(a);if(O!==R("error.unknown"))return R(t,{item:O});{let D=`action.onSuccess.${r}WithoutItem`,x=p(D);return x!==R("error.unknown")?x:n}}return n}return R("base.success.transaction")},[p,R,A]),f=_(e=>{if(e.errorCode&&T[e.errorCode])return T[e.errorCode];if(e.errorCode&&M[e.errorCode])return p(M[e.errorCode]);if(e.errorCode){let i=[`errors.auth.${e.errorCode}`,`errors.data.${e.errorCode}`,`errors.system.${e.errorCode}`,`errors.${e.errorCode}`];for(let s of i){let r=p(s);if(r!==R("error.unknown"))return r}}if(typeof e.data=="string"&&e.data.startsWith("errors.")){let i=p(e.data);if(i!==R("error.unknown"))return i}if(e.errors&&Object.keys(e.errors).length>0){let i=Object.keys(e.errors);if(i.length===1&&i[0]==="_transaction"){let s=e.errors._transaction;if(s?.includes("ONE_OR_MORE_OPERATIONS_FAILED"))return"";if(Array.isArray(s)&&s.length>0){let r=s[0];if(typeof r=="string"&&r!=="ONE_OR_MORE_OPERATIONS_FAILED")try{let t=JSON.parse(r);if(Array.isArray(t)&&t.length>0){let n=t[0];if(n?.response?.errorCode){let a=n.response.errorCode;if(M[a])return p(M[a]);let O=[`errors.auth.${a}`,`errors.data.${a}`,`errors.system.${a}`,`errors.${a}`];for(let D of O){let x=p(D);if(x!==p("error.unknown"))return x}}if(n?.response?.data)return n.response.data}if(t?.response?.message){let n=t.response.message.toLowerCase();return n.includes("expired")?p("resetPassword.linkExpired","El enlace ha expirado"):n.includes("invalid")?p("resetPassword.invalidCode","C\xF3digo inv\xE1lido"):t.response.message}}catch{return r.toLowerCase().includes("expired")?p("resetPassword.linkExpired","El enlace ha expirado"):r.toLowerCase().includes("invalid")?p("resetPassword.invalidCode","C\xF3digo inv\xE1lido"):r}}return p("error.transaction","Error en la operaci\xF3n")}if(i.length===1&&i[0]==="_error"){let s=e.errors._error;return Array.isArray(s)?s[0]:String(s)}return i.length===1&&i[0]==="_graphql"?p("errors.system.DATABASE_CONNECTION_ERROR"):`${p("errors.data.FIELD_ERROR")}: ${i.join(", ")}`}return I||R("error.unknown")},[T,I,R,p]),o=_(e=>e.errorCode&&Y[e.errorCode]?Y[e.errorCode]:"error",[]),y=_(async(e,i,s)=>{let r=await P.createItem(e,i,s);if(!r.success&&g&&d(r)){let t=f(r),n=o(r);c(t,n,{autoHideDuration:u})}else if(r.success){let t=s?.actionConfig,n=t?.key||"create",a=t?.moduleKey||e;if(C(n,a)){let O=E(n,a,t);c(O,"success",{autoHideDuration:u})}}return r},[g,C,c,f,o,E,u,d]),l=_(async(e,i,s)=>{let r=await P.updateItem(e,i,s),t=s?.skipNotifications===!0;if(!t&&!r.success&&g&&d(r)){let n=f(r),a=o(r);c(n,a,{autoHideDuration:u})}else if(!t&&r.success){let n=s?.actionConfig,a=n?.key||"update",O=n?.moduleKey||e;if(C(a,O)){let D=E(a,O,n);c(D,"success",{autoHideDuration:u})}}return r},[g,C,c,f,o,E,u,d]),F=_(async(e,i,s)=>{let r=await P.deleteItem(e,i,s);if(!r.success&&g&&d(r)){let t=f(r),n=o(r);c(t,n,{autoHideDuration:u})}else if(r.success){let t=s?.actionConfig,n=t?.key||"delete",a=t?.moduleKey||e;if(C(n,a)){let O=E(n,a,t);c(O,"success",{autoHideDuration:u})}}return r},[g,C,c,f,o,E,u,d]),L=_(async(e,i,s)=>{let r=await P.readItem(e,i,s);if(!r.success&&g&&d(r)){let t=f(r),n=o(r);c(t,n,{autoHideDuration:u})}return r},[g,c,f,o,u,d]),U=_(async(e,i,s)=>{let r=await P.readItems(e,i,s);if(!r.success&&g&&d(r)){let t=f(r),n=o(r);c(t,n,{autoHideDuration:u})}return r},[g,c,f,o,u,d]),q=_(async(e,i)=>{let s=await P.transaction(e,i),r=i?.skipNotifications===!0;if(!r&&!s.success&&g&&d(s)){let t=f(s),n=o(s);c(t,n,{autoHideDuration:u})}else if(!r&&s.success){let t="transaction",n,a=null;if(i?.actionConfig)a=i.actionConfig,t=a.key,n=a.moduleKey;else if(Array.isArray(e)&&e.length>0&&"operation"in e[0]&&e[0].operation){t=e[0].operation;let O=m.find(D=>D.key===t);O&&(a=O,n=O.moduleKey)}if(C(t,n)){let O=E(t,n,a??void 0);c(O,"success",{autoHideDuration:u})}}return s},[g,C,c,f,o,E,u,d,m]),h=_((e,i)=>{if(!e.success&&g&&d(e)){let s=f(e),r=o(e);c(s,r,{autoHideDuration:u})}else e.success&&N&&i&&c(i,"success",{autoHideDuration:u});return e},[g,N,c,f,o,u,d,R]);return{createItem:y,updateItem:l,deleteItem:F,readItem:L,readItems:U,transaction:q,handleResponse:h,getErrorMessage:f,getErrorSeverity:o,shouldShowNotification:d}};export{J as a,te as b,ae as c,de as d};
1
+ import{g as $,l as k}from"./chunk-GT7B57S5.mjs";import{a as V}from"./chunk-4ILUXVPW.mjs";import{useState as K,useEffect as z,useCallback as j,useRef as v}from"react";import Q from"@nocios/crudify-sdk";var J=(w={})=>{let{autoFetch:c=!0,retryOnError:N=!1,maxRetries:g=3}=w,{isAuthenticated:T,isInitialized:I,sessionData:u,tokens:m}=k(),[R,d]=K(null),[p,A]=K(c&&T),[C,E]=K(null),f=v(null),o=v(!0),y=v(0),l=v(0),F=j(()=>{if(!u)return null;let h=u["cognito:username"];return u.email||(typeof h=="string"?h:null)},[u]),L=j(()=>{d(null),E(null),A(!1),l.current=0},[]),U=j(async()=>{let h=F();if(!h){o.current&&(E("No user email available from session data"),A(!1));return}if(!I){o.current&&(E("Session not initialized"),A(!1));return}f.current&&f.current.abort();let e=new AbortController;f.current=e;let i=++y.current;try{o.current&&(A(!0),E(null));let s=await Q.readItems("users",{filter:{email:h},pagination:{limit:1}});if(i===y.current&&o.current&&!e.signal.aborted){let r=null;if(s.success){let t=s.data;if(Array.isArray(t)&&t.length>0)r=t[0];else if(t&&typeof t=="object"&&!Array.isArray(t)&&t.response?.data)try{let n=t.response.data,a=typeof n=="string"?JSON.parse(n):n;a&&a.items&&Array.isArray(a.items)&&a.items.length>0&&(r=a.items[0])}catch{}else t&&typeof t=="object"&&!Array.isArray(t)&&t.items&&Array.isArray(t.items)&&t.items.length>0&&(r=t.items[0]);if(!r&&t&&typeof t=="object"&&!Array.isArray(t)&&t.data?.response?.data)try{let n=t.data.response.data,a=typeof n=="string"?JSON.parse(n):n;a&&a.items&&Array.isArray(a.items)&&a.items.length>0&&(r=a.items[0])}catch{}}r?(d(r),E(null),l.current=0):(E("User profile not found in database"),d(null))}}catch(s){if(i===y.current&&o.current){let r=s;if(r.name==="AbortError")return;N&&l.current<g&&(r.message?.includes("Network Error")||r.message?.includes("Failed to fetch"))?(l.current++,setTimeout(()=>{o.current&&U()},1e3*l.current)):(E("Failed to load user profile from database"),d(null))}}finally{i===y.current&&o.current&&A(!1),f.current===e&&(f.current=null)}},[I,F,N,g]);return z(()=>{c&&T&&I?U():T||L()},[c,T,I,U,L]),z(()=>(o.current=!0,()=>{o.current=!1,f.current&&(f.current.abort(),f.current=null)}),[]),{user:{session:u,data:R},loading:p,error:C,refreshProfile:U,clearProfile:L}};import{useCallback as W}from"react";var te=()=>{let{isAuthenticated:w,isLoading:c,isInitialized:N,tokens:g,error:T,sessionData:I,login:u,logout:m,refreshTokens:R,clearError:d,getTokenInfo:p,isExpiringSoon:A,expiresIn:C,refreshExpiresIn:E}=k(),f=W(y=>{y?V.warn("useAuth.setToken() is deprecated. Use login() method instead for better security."):m()},[m]),o=g?.expiresAt?new Date(g.expiresAt):null;return{isAuthenticated:w,loading:c,error:T,token:g?.accessToken||null,user:I,tokenExpiration:o,setToken:f,logout:m,refreshToken:R,login:u,isExpiringSoon:A,expiresIn:C,refreshExpiresIn:E,getTokenInfo:p,clearError:d}};import{useCallback as S}from"react";import b from"@nocios/crudify-sdk";var ae=()=>{let{isInitialized:w,isLoading:c,error:N,isAuthenticated:g,login:T}=k(),I=S(()=>w&&!c&&!N,[w,c,N]),u=S(async()=>new Promise((o,y)=>{let l=()=>{I()?o():N?y(new Error(N)):setTimeout(l,100)};l()}),[I,N]),m=S(async()=>{if(!I())throw new Error("System not ready. Check isInitialized, isLoading, and error states.")},[I]),R=S(async(o,y,l)=>(await m(),await b.readItems(o,y||{},l)),[m]),d=S(async(o,y,l)=>(await m(),await b.readItem(o,y,l)),[m]),p=S(async(o,y,l)=>(await m(),await b.createItem(o,y,l)),[m]),A=S(async(o,y,l)=>(await m(),await b.updateItem(o,y,l)),[m]),C=S(async(o,y,l)=>(await m(),await b.deleteItem(o,y,l)),[m]),E=S(async(o,y)=>(await m(),await b.transaction(o,y)),[m]),f=S(async(o,y)=>{try{let l=await T(o,y);return l.success?{success:!0,data:l.tokens}:{success:!1,errors:l.error||"Login failed"}}catch(l){return{success:!1,errors:l instanceof Error?l.message:"Login failed"}}},[T]);return{readItems:R,readItem:d,createItem:p,updateItem:A,deleteItem:C,transaction:E,login:f,isInitialized:w,isInitializing:c,initializationError:N,isReady:I,waitForReady:u}};import{useCallback as _}from"react";import P from"@nocios/crudify-sdk";var Y={INVALID_CREDENTIALS:"warning",UNAUTHORIZED:"warning",INVALID_API_KEY:"error",USER_NOT_FOUND:"warning",USER_NOT_ACTIVE:"warning",NO_PERMISSION:"warning",ITEM_NOT_FOUND:"info",NOT_FOUND:"info",IN_USE:"warning",FIELD_ERROR:"warning",BAD_REQUEST:"warning",INTERNAL_SERVER_ERROR:"error",DATABASE_CONNECTION_ERROR:"error",INVALID_CONFIGURATION:"error",UNKNOWN_OPERATION:"error",TOO_MANY_REQUESTS:"warning"},M={INVALID_CREDENTIALS:"errors.auth.INVALID_CREDENTIALS",UNAUTHORIZED:"errors.auth.UNAUTHORIZED",INVALID_API_KEY:"errors.auth.INVALID_API_KEY",USER_NOT_FOUND:"errors.auth.USER_NOT_FOUND",USER_NOT_ACTIVE:"errors.auth.USER_NOT_ACTIVE",NO_PERMISSION:"errors.auth.NO_PERMISSION",ITEM_NOT_FOUND:"errors.data.ITEM_NOT_FOUND",NOT_FOUND:"errors.data.NOT_FOUND",IN_USE:"errors.data.IN_USE",FIELD_ERROR:"errors.data.FIELD_ERROR",BAD_REQUEST:"errors.data.BAD_REQUEST",INTERNAL_SERVER_ERROR:"errors.system.INTERNAL_SERVER_ERROR",DATABASE_CONNECTION_ERROR:"errors.system.DATABASE_CONNECTION_ERROR",INVALID_CONFIGURATION:"errors.system.INVALID_CONFIGURATION",UNKNOWN_OPERATION:"errors.system.UNKNOWN_OPERATION",TOO_MANY_REQUESTS:"errors.system.TOO_MANY_REQUESTS"},de=(w={})=>{let{showNotification:c}=$(),{showSuccessNotifications:N=!1,showErrorNotifications:g=!0,customErrorMessages:T={},defaultErrorMessage:I="Ha ocurrido un error inesperado",autoHideDuration:u=6e3,appStructure:m=[],translateFn:R=e=>e}=w,d=_(e=>{if(!e.success&&e.errors&&(Object.keys(e.errors).some(r=>r!=="_error"&&r!=="_graphql"&&r!=="_transaction")||e.errors._transaction?.includes("ONE_OR_MORE_OPERATIONS_FAILED")||e.errors._error?.includes("TOO_MANY_REQUESTS")))return!1;let i=e.data;return!(!e.success&&i?.response?.status==="TOO_MANY_REQUESTS")},[]),p=_((e,i)=>{let s=R(e);return s===e?i||R("error.unknown"):s},[R]),A=_(e=>["create","update","delete"].includes(e),[]),C=_((e,i)=>N?A(e)&&i?!0:m.some(s=>s.key===e):!1,[N,m,A]),E=_((e,i,s)=>{let r=s?.key&&typeof s.key=="string"?s.key:e,t=`action.onSuccess.${r}`,n=p(t);if(n!==R("error.unknown")){if(A(r)&&i){let a=`action.${i}Singular`,O=p(a);if(O!==R("error.unknown"))return R(t,{item:O});{let D=`action.onSuccess.${r}WithoutItem`,x=p(D);return x!==R("error.unknown")?x:n}}return n}return R("base.success.transaction")},[p,R,A]),f=_(e=>{if(e.errorCode&&T[e.errorCode])return T[e.errorCode];if(e.errorCode&&M[e.errorCode])return p(M[e.errorCode]);if(e.errorCode){let i=[`errors.auth.${e.errorCode}`,`errors.data.${e.errorCode}`,`errors.system.${e.errorCode}`,`errors.${e.errorCode}`];for(let s of i){let r=p(s);if(r!==R("error.unknown"))return r}}if(typeof e.data=="string"&&e.data.startsWith("errors.")){let i=p(e.data);if(i!==R("error.unknown"))return i}if(e.errors&&Object.keys(e.errors).length>0){let i=Object.keys(e.errors);if(i.length===1&&i[0]==="_transaction"){let s=e.errors._transaction;if(s?.includes("ONE_OR_MORE_OPERATIONS_FAILED"))return"";if(Array.isArray(s)&&s.length>0){let r=s[0];if(typeof r=="string"&&r!=="ONE_OR_MORE_OPERATIONS_FAILED")try{let t=JSON.parse(r);if(Array.isArray(t)&&t.length>0){let n=t[0];if(n?.response?.errorCode){let a=n.response.errorCode;if(M[a])return p(M[a]);let O=[`errors.auth.${a}`,`errors.data.${a}`,`errors.system.${a}`,`errors.${a}`];for(let D of O){let x=p(D);if(x!==p("error.unknown"))return x}}if(n?.response?.data)return n.response.data}if(t?.response?.message){let n=t.response.message.toLowerCase();return n.includes("expired")?p("resetPassword.linkExpired","El enlace ha expirado"):n.includes("invalid")?p("resetPassword.invalidCode","C\xF3digo inv\xE1lido"):t.response.message}}catch{return r.toLowerCase().includes("expired")?p("resetPassword.linkExpired","El enlace ha expirado"):r.toLowerCase().includes("invalid")?p("resetPassword.invalidCode","C\xF3digo inv\xE1lido"):r}}return p("error.transaction","Error en la operaci\xF3n")}if(i.length===1&&i[0]==="_error"){let s=e.errors._error;return Array.isArray(s)?s[0]:String(s)}return i.length===1&&i[0]==="_graphql"?p("errors.system.DATABASE_CONNECTION_ERROR"):`${p("errors.data.FIELD_ERROR")}: ${i.join(", ")}`}return I||R("error.unknown")},[T,I,R,p]),o=_(e=>e.errorCode&&Y[e.errorCode]?Y[e.errorCode]:"error",[]),y=_(async(e,i,s)=>{let r=await P.createItem(e,i,s);if(!r.success&&g&&d(r)){let t=f(r),n=o(r);c(t,n,{autoHideDuration:u})}else if(r.success){let t=s?.actionConfig,n=t?.key||"create",a=t?.moduleKey||e;if(C(n,a)){let O=E(n,a,t);c(O,"success",{autoHideDuration:u})}}return r},[g,C,c,f,o,E,u,d]),l=_(async(e,i,s)=>{let r=await P.updateItem(e,i,s),t=s?.skipNotifications===!0;if(!t&&!r.success&&g&&d(r)){let n=f(r),a=o(r);c(n,a,{autoHideDuration:u})}else if(!t&&r.success){let n=s?.actionConfig,a=n?.key||"update",O=n?.moduleKey||e;if(C(a,O)){let D=E(a,O,n);c(D,"success",{autoHideDuration:u})}}return r},[g,C,c,f,o,E,u,d]),F=_(async(e,i,s)=>{let r=await P.deleteItem(e,i,s);if(!r.success&&g&&d(r)){let t=f(r),n=o(r);c(t,n,{autoHideDuration:u})}else if(r.success){let t=s?.actionConfig,n=t?.key||"delete",a=t?.moduleKey||e;if(C(n,a)){let O=E(n,a,t);c(O,"success",{autoHideDuration:u})}}return r},[g,C,c,f,o,E,u,d]),L=_(async(e,i,s)=>{let r=await P.readItem(e,i,s);if(!r.success&&g&&d(r)){let t=f(r),n=o(r);c(t,n,{autoHideDuration:u})}return r},[g,c,f,o,u,d]),U=_(async(e,i,s)=>{let r=await P.readItems(e,i,s);if(!r.success&&g&&d(r)){let t=f(r),n=o(r);c(t,n,{autoHideDuration:u})}return r},[g,c,f,o,u,d]),q=_(async(e,i)=>{let s=await P.transaction(e,i),r=i?.skipNotifications===!0;if(!r&&!s.success&&g&&d(s)){let t=f(s),n=o(s);c(t,n,{autoHideDuration:u})}else if(!r&&s.success){let t="transaction",n,a=null;if(i?.actionConfig)a=i.actionConfig,t=a.key,n=a.moduleKey;else if(Array.isArray(e)&&e.length>0&&"operation"in e[0]&&e[0].operation){t=e[0].operation;let O=m.find(D=>D.key===t);O&&(a=O,n=O.moduleKey)}if(C(t,n)){let O=E(t,n,a??void 0);c(O,"success",{autoHideDuration:u})}}return s},[g,C,c,f,o,E,u,d,m]),h=_((e,i)=>{if(!e.success&&g&&d(e)){let s=f(e),r=o(e);c(s,r,{autoHideDuration:u})}else e.success&&N&&i&&c(i,"success",{autoHideDuration:u});return e},[g,N,c,f,o,u,d,R]);return{createItem:y,updateItem:l,deleteItem:F,readItem:L,readItems:U,transaction:q,handleResponse:h,getErrorMessage:f,getErrorSeverity:o,shouldShowNotification:d}};export{J as a,te as b,ae as c,de as d};
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true});var _chunkPNI3ZBZVjs = require('./chunk-PNI3ZBZV.js');var _chunkCHDM7KGHjs = require('./chunk-CHDM7KGH.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}=_chunkCHDM7KGHjs.e.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 = _chunkPNI3ZBZVjs.s; exports.CrudiaFileField = _chunkPNI3ZBZVjs.t; exports.CrudiaMarkdownField = _chunkPNI3ZBZVjs.u; exports.CrudifyLogin = _chunkPNI3ZBZVjs.l; exports.GlobalNotificationProvider = _chunkCHDM7KGHjs.f; exports.LoginComponent = _chunkPNI3ZBZVjs.q; exports.Policies = _chunkPNI3ZBZVjs.p; exports.SessionStatus = _chunkPNI3ZBZVjs.r; exports.SessionTimeIndicator = z; exports.UserProfileDisplay = _chunkPNI3ZBZVjs.m; exports.useGlobalNotification = _chunkCHDM7KGHjs.g;
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true});var _chunkAOPB3KXBjs = require('./chunk-AOPB3KXB.js');var _chunkLK6QVSG4js = require('./chunk-LK6QVSG4.js');require('./chunk-NSV6ECYO.js');require('./chunk-CR5KJUST.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}=_chunkLK6QVSG4js.e.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 = _chunkAOPB3KXBjs.s; exports.CrudiaFileField = _chunkAOPB3KXBjs.t; exports.CrudiaMarkdownField = _chunkAOPB3KXBjs.u; exports.CrudifyLogin = _chunkAOPB3KXBjs.l; exports.GlobalNotificationProvider = _chunkLK6QVSG4js.f; exports.LoginComponent = _chunkAOPB3KXBjs.q; exports.Policies = _chunkAOPB3KXBjs.p; exports.SessionStatus = _chunkAOPB3KXBjs.r; exports.SessionTimeIndicator = z; exports.UserProfileDisplay = _chunkAOPB3KXBjs.m; exports.useGlobalNotification = _chunkLK6QVSG4js.g;
@@ -1 +1 @@
1
- import{l as N,m as T,p as M,q as k,r as G,s as L,t as A,u as R}from"./chunk-HVTRRU4W.mjs";import{e as d,f as F,g as I}from"./chunk-NBQH6QOU.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};
1
+ import{l as N,m as T,p as M,q as k,r as G,s as L,t as A,u as R}from"./chunk-7ORHVSWL.mjs";import{e as d,f as F,g as I}from"./chunk-GT7B57S5.mjs";import"./chunk-JAPL7EZJ.mjs";import"./chunk-4ILUXVPW.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};