@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.
- package/coverage/coverage-final.json +13 -13
- package/coverage/index.html +48 -48
- package/dist/chunk-4ILUXVPW.mjs +1 -0
- package/dist/{chunk-5HFI5CZ5.js → chunk-4VN5YRYZ.js} +1 -1
- package/dist/chunk-7ORHVSWL.mjs +1 -0
- package/dist/chunk-AOPB3KXB.js +1 -0
- package/dist/chunk-CR5KJUST.js +1 -0
- package/dist/{chunk-NBQH6QOU.mjs → chunk-GT7B57S5.mjs} +1 -1
- package/dist/{chunk-CHDM7KGH.js → chunk-LK6QVSG4.js} +1 -1
- package/dist/chunk-RJBX4MWF.mjs +1 -0
- package/dist/{chunk-2XOTIEKS.js → chunk-RORGWKHP.js} +1 -1
- package/dist/{chunk-U4RS66TB.mjs → chunk-XZ6OGRJR.mjs} +1 -1
- package/dist/components.js +1 -1
- package/dist/components.mjs +1 -1
- package/dist/errorTranslation-By5Av0tL.d.ts +335 -0
- package/dist/errorTranslation-DeeDj7Vt.d.mts +335 -0
- package/dist/hooks.js +1 -1
- package/dist/hooks.mjs +1 -1
- package/dist/index.d.mts +9 -8
- package/dist/index.d.ts +9 -8
- package/dist/index.js +2 -2
- package/dist/index.mjs +2 -2
- package/dist/utils.d.mts +2 -48
- package/dist/utils.d.ts +2 -48
- package/dist/utils.js +1 -1
- package/dist/utils.mjs +1 -1
- package/package.json +2 -2
- package/dist/chunk-HVTRRU4W.mjs +0 -1
- package/dist/chunk-JNEWPO2J.mjs +0 -1
- package/dist/chunk-MFYHD6S5.js +0 -1
- package/dist/chunk-MGJZTOEM.mjs +0 -1
- package/dist/chunk-PNI3ZBZV.js +0 -1
- package/dist/errorTranslation-DGdrMidg.d.ts +0 -143
- package/dist/errorTranslation-qwwQTvCO.d.mts +0 -143
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as u,c as me,e as H,f as xe,g as we,h as Re,i as Ne,j as Ce,k as Pe,l as De,p as Le,q as Oe,r as Fe}from"./chunk-MGJZTOEM.mjs";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 we(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 u.error("Crudify: Failed to initialize encryption after retries",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()),u.info("Crudify: Storage upgraded to v2, tokens cleared for security")}}catch{}}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{}let t=Ce();try{let e="";for(let i=0;i<t.length;i++)e+=String.fromCharCode(t[i]);localStorage.setItem(a.SALT_KEY,btoa(e))}catch{u.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{}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 xe(e);try{localStorage.setItem(a.ENCRYPTION_KEY_STORAGE,i)}catch{u.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{return!1}}static getStorage(){return a.storageType==="none"?null:a.isStorageAvailable(a.storageType)?window[a.storageType]:(u.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 Re(t,a.encryptionKey,a.salt)}static async decryptData(t){if(await a.initialize(),!a.fingerprint)throw new Error("Encryption not initialized");return Pe(t)?Ne(t,a.fingerprint):(u.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),u.debug("Crudify: Tokens saved successfully")}catch(i){u.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 u.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?(u.warn("Crudify: Incomplete token data found, clearing storage"),await a.clearTokens(),null):Date.now()>=n.refreshExpiresAt?(u.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 u.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),u.debug("Crudify: Tokens cleared from storage")}catch(e){u.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{}u.info("Crudify: Encryption key rotated successfully")}catch(t){u.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){u.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=a.getStorage()?.getItem(a.TOKEN_KEY);if(l!==null&&l!=="")return}let n=i.oldValue!==null&&i.oldValue!=="";if(i.newValue===null){u.debug("Crudify: Tokens removed in another tab"),t(null,a.SYNC_EVENTS.TOKENS_CLEARED,n);return}if(i.newValue){u.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=()=>{u.warn("Crudify: CrossTabSync message error")},u.debug("Crudify: CrossTabSync initialized with BroadcastChannel")):u.debug("Crudify: BroadcastChannel not available, using localStorage fallback"),this.isInitialized=!0}catch(t){u.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),u.debug(`Crudify: CrossTab broadcast ${t.type}`))}catch(e){u.warn("Crudify: Failed to broadcast cross-tab message",{message:e instanceof Error?e.message:String(e)})}}handleMessage(t){t.tabId!==this.tabId&&(u.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){u.error("Crudify: CrossTab listener error",{message:i instanceof Error?i.message:String(i)})}}))}};K.instance=null;var ye=K,W=ye.getInstance();import L from"@nocios/crudify-sdk";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(),L.setTokenInvalidationCallback(()=>{this.log("Tokens invalidated by crudify-core"),H.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 L.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:n?.apiEndpointAdmin||this.config.apiEndpointAdmin,apiKeyEndpointAdmin:n?.apiKeyEndpointAdmin||this.config.apiKeyEndpointAdmin};return await v.saveTokens(l),v.markSuccessfulLogin(),this.lastActivityTime=Date.now(),W.notifyLogin(),this.config.onLoginSuccess?.(l),{success:!0,tokens:l,data:s}}catch(i){return u.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..."),H.emit("LOGOUT",{message:"User logged out",source:"SessionManager.logout"}),await L.logout(),await v.clearTokens(),W.notifyLogout(),this.log("Logout successful"),this.config.onLogout?.()}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(L.setTokens({accessToken:t.accessToken,refreshToken:t.refreshToken,expiresAt:t.expiresAt,refreshExpiresAt:t.refreshExpiresAt}),L.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&&this.config.onSessionRestored?.(n),!0}return await v.clearTokens(),await L.logout(),!1}return this.log("Session restored successfully"),this.lastActivityTime=Date.now(),this.config.onSessionRestored?.(t),!0}catch(t){return this.log("Session restore error",{error:t instanceof Error?t.message:String(t)}),await v.clearTokens(),await L.logout(),!1}}async isAuthenticated(){return L.isLogin()||await v.hasValidTokens()}async getTokenInfo(){let t=L.getTokenData(),e=await v.getExpirationInfo(),i=await v.getTokens();return{isLoggedIn:await this.isAuthenticated(),crudifyTokens:t,storageInfo:e,hasValidTokens:await v.hasValidTokens(),apiEndpointAdmin:i?.apiEndpointAdmin,apiKeyEndpointAdmin:i?.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 L.refreshAccessToken();if(!t.success)return this.log("Token refresh failed",{errors:t.errors}),await v.clearTokens(),this.config.showNotification?.(this.getSessionExpiredMessage(),"warning"),this.config.onSessionExpired?.(),!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(),this.config.showNotification?.(this.getSessionExpiredMessage(),"warning"),this.config.onSessionExpired?.(),!1}}isRefreshing(){return this.isRefreshingLocally}setupResponseInterceptor(){L.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"),H.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"),H.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"),H.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=L.getTokenData();if(t&&t.endpoint){this.log("Crudify already initialized by another service"),this.crudifyInitialized=!0;return}let e=this.config.env||"stg";L.config(e);let i=this.config.publicApiKey,n=this.config.enableLogging?"debug":"none",s=await L.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 u.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"||n.message?.includes("Unauthorized")||n.message?.includes("Not Authorized")||n.message?.includes("NOT_AUTHORIZED")||n.message?.includes("Token")||n.message?.includes("TOKEN")||n.message?.includes("Authentication")||n.message?.includes("UNAUTHENTICATED")||n.extensions?.code==="UNAUTHENTICATED"||n.extensions?.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.",(i.message?.includes("TOKEN")||i.message?.includes("Token"))&&(e.isTokenExpired=!0),i.extensions?.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&&t.data?.response?.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&&t.data?.response?.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{}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 L.logout(),this.lastActivityTime=0,this.log("Session cleared completely")}getSessionExpiredMessage(){return this.config.translateFn?De("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&&u.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"}};import{useEffect as Kt,useCallback as j}from"react";import{useState as Pt,useCallback as Q}from"react";var Ke={isAuthenticated:!1,isLoading:!0,isLoggingOut:!1,isInitialized:!1,tokens:null,error:null};function Me(){let[r,t]=Pt(Ke),e=Q(o=>{t(f=>({...f,isLoading:o}))},[]),i=Q((o,f)=>{t(E=>({...E,isAuthenticated:o,tokens:f,error:o?null:E.error}))},[]),n=Q(o=>{t(f=>({...f,isLoggingOut:o}))},[]),s=Q(o=>{t(f=>({...f,error:o}))},[]),l=Q(o=>{t(f=>({...f,isInitialized:o}))},[]);return{state:r,setState:t,setLoading:e,setAuthenticated:i,setLoggingOut:n,setError:s,setInitialized:l}}import{useCallback as oe}from"react";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=oe(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";u.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=oe(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=oe(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=oe(()=>{e.setError(null)},[e]);return{login:i,logout:n,refreshTokens:s,clearError:l}}import{useEffect as Ot,useCallback as Ft}from"react";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=Ft(()=>{i.updateLastActivity()},[i]);Ot(()=>{if(!t||!e)return;let b=Le.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])}import{useEffect as Ut}from"react";function Be(r){let{sessionManager:t,onTokensUpdated:e,onSessionExpired:i,onSetLoading:n,onSetError:s}=r;Ut(()=>{let l=H.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 H.emit("SESSION_EXPIRED",{message:"Failed to refresh token after detecting expiration",source:"useSession.TOKEN_EXPIRED handler"})}catch(f){H.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(o.details?.message?.toString()||"Session expired"),i())});return()=>l()},[t,e,i,n,s])}import{useEffect as We}from"react";function Xe(r){let{isAuthenticated:t,onTokensUpdated:e,onSessionExpired:i}=r;We(()=>{let n=async l=>{switch(l.type){case"SESSION_STARTED":case"TOKEN_REFRESHED":try{await v.ensureInitialized();let o=await v.getTokens();o&&(u.debug(`[useCrossTabSync] Syncing ${l.type} from tab ${l.tabId}`),e(o))}catch(o){u.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()||(u.debug(`[useCrossTabSync] Syncing SESSION_ENDED from tab ${l.tabId}`),e(null),t&&i())}catch(o){u.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]),We(()=>{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:e.autoRestore??!0,enableLogging: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"})),e.onSessionExpired?.()},onSessionRestored:o=>{i.setState(f=>({...f,isAuthenticated:!0,tokens:o,error:null})),e.onSessionRestored?.(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";u.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=j(g=>{e.setAuthenticated(!!g,g)},[e]),E=j(()=>{e.setAuthenticated(!1,null),r.onSessionExpired?.()},[e,r.onSessionExpired]),b=j(g=>{e.setLoading(g)},[e]),T=j(g=>{e.setError(g)},[e]);Kt(()=>{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=j(()=>{t.updateLastActivity()},[t]),I=j(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)}}import{useState as qe,createContext as Mt,useContext as Ht,useCallback as ae,useEffect as Gt}from"react";import{Snackbar as _t,Alert as Vt,Box as $t,Portal as Yt}from"@mui/material";import{v4 as Bt}from"uuid";import Wt from"dompurify";import{jsx as X,jsxs as qt}from"react/jsx-runtime";var je=Mt(null),Xt=r=>Wt.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=({children:r,maxNotifications:t=5,defaultAutoHideDuration:e=6e3,position:i={vertical:"top",horizontal:"right"},enabled:n=!1,allowHtml:s=!1})=>{let[l,o]=qe([]),f=ae((m,I="info",g)=>{if(!n)return"";if(!m||typeof m!="string")return u.warn("GlobalNotificationProvider: Invalid message provided"),"";m.length>1e3&&(u.warn("GlobalNotificationProvider: Message too long, truncating"),m=m.substring(0,1e3)+"...");let A=Bt(),N={id:A,message:m,severity:I,autoHideDuration:g?.autoHideDuration??e,persistent:g?.persistent??!1,allowHtml:g?.allowHtml??s};return o(x=>[...x.length>=t?x.slice(-(t-1)):x,N]),A},[t,e,n,s]),E=ae(m=>{o(I=>I.filter(g=>g.id!==m))},[]),b=ae(()=>{o([])},[]),T={showNotification:f,hideNotification:E,clearAllNotifications:b};return qt(je.Provider,{value:T,children:[r,n&&X(Yt,{children:X($t,{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=>X(Zt,{notification:m,onClose:()=>E(m.id)},m.id))})})]})},Zt=({notification:r,onClose:t})=>{let[e,i]=qe(!0),n=ae((s,l)=>{l!=="clickaway"&&(i(!1),setTimeout(t,300))},[t]);return Gt(()=>{if(!r.persistent&&r.autoHideDuration){let s=setTimeout(()=>{n()},r.autoHideDuration);return()=>clearTimeout(s)}},[r.autoHideDuration,r.persistent,n]),X(_t,{open:e,onClose:n,sx:{position:"relative","& .MuiSnackbarContent-root":{minWidth:"auto"}},TransitionProps:{enter:!0,exit:!0},children:X(Vt,{variant:"filled",severity:r.severity,onClose:n,sx:{width:"100%",minWidth:"280px",maxWidth:"400px",wordBreak:"break-word"},children:r.allowHtml?X("span",{dangerouslySetInnerHTML:{__html:Xt(r.message)}}):X("span",{children:r.message})})})},Je=()=>{let r=Ht(je);if(!r)throw new Error("useGlobalNotification debe ser usado dentro de un GlobalNotificationProvider");return r};import{createContext as jt,useContext as Jt,useEffect as Qt,useState as ee}from"react";import te from"@nocios/crudify-sdk";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){u.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=Se.getInstance();import{jsx as ei}from"react/jsx-runtime";var Qe=jt(void 0),et=({config:r,children:t})=>{let[e,i]=ee(!0),[n,s]=ee(null),[l,o]=ee(!1),[f,E]=ee(""),[b,T]=ee();Qt(()=>{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{te.config(r.env||"prod");let A=await te.init(r.publicApiKey,"none");if(T(A),typeof te.transaction=="function"&&typeof te.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";u.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?te:null,isLoading:e,error:n,isInitialized:l,adminCredentials:b};return ei(Qe.Provider,{value:m,children:t})},tt=()=>{let r=Jt(Qe);if(r===void 0)throw new Error("useCrudify must be used within a CrudifyProvider");return r};import ti,{createContext as ii,useContext as ri,useMemo as ve}from"react";import{Fragment as si,jsx as P,jsxs as G}from"react/jsx-runtime";var rt=ii(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{}let l={};try{let g=tt();g.isInitialized&&g.adminCredentials&&(l=g.adminCredentials)}catch{}let o=ve(()=>{let g=me({publicApiKey:e?.publicApiKey,env:e?.env,enableDebug:t?.enableLogging});return{publicApiKey:g.publicApiKey,env:g.env||"prod"}},[e,t?.enableLogging]),f=ti.useMemo(()=>({...t,showNotification:s,apiEndpointAdmin:l.apiEndpointAdmin,apiKeyEndpointAdmin:l.apiKeyEndpointAdmin,publicApiKey:o.publicApiKey,env:o.env,onSessionExpired:()=>{t.onSessionExpired?.()}}),[t,s,l.apiEndpointAdmin,l.apiKeyEndpointAdmin,o]),E=Ee(f),b=ve(()=>{let g=me({publicApiKey:e?.publicApiKey,env:e?.env,appName:e?.appName,logo:e?.logo,loginActions:e?.loginActions,enableDebug:t?.enableLogging});return{publicApiKey:g.publicApiKey,env:g.env,appName:g.appName,loginActions:g.loginActions,logo:g.logo}},[e,t?.enableLogging]),T=ve(()=>{if(!E.tokens?.accessToken||!E.isAuthenticated)return null;try{let g=Oe(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){u.error("Error decoding JWT token for sessionData",g instanceof Error?g:{message:String(g)})}return null},[E.tokens?.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 P(rt.Provider,{value:m,children:r})}function Vr(r){let t={enabled:r.showNotifications,maxNotifications:r.notificationOptions?.maxNotifications||5,defaultAutoHideDuration:r.notificationOptions?.defaultAutoHideDuration||6e3,position:r.notificationOptions?.position||{vertical:"top",horizontal:"right"},allowHtml:r.notificationOptions?.allowHtml||!1};return r.config?.publicApiKey?P(et,{config:{publicApiKey:r.config.publicApiKey,env:r.config.env||"prod",appName:r.config.appName,loginActions:r.config.loginActions,logo:r.config.logo},children:P(Te,{...t,children:P(it,{...r})})}):P(Te,{...t,children:P(it,{...r})})}function ni(){let r=ri(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?G("div",{style:{padding:"10px",margin:"10px",border:"1px solid #ccc",borderRadius:"4px",fontSize:"12px",fontFamily:"monospace"},children:[P("h4",{children:"Session Debug Info"}),G("div",{children:[P("strong",{children:"Authenticated:"})," ",r.isAuthenticated?"Yes":"No"]}),G("div",{children:[P("strong",{children:"Loading:"})," ",r.isLoading?"Yes":"No"]}),G("div",{children:[P("strong",{children:"Error:"})," ",r.error||"None"]}),r.tokens&&G(si,{children:[G("div",{children:[P("strong",{children:"Access Token:"})," ",r.tokens.accessToken.substring(0,20),"..."]}),G("div",{children:[P("strong",{children:"Refresh Token:"})," ",r.tokens.refreshToken.substring(0,20),"..."]}),G("div",{children:[P("strong",{children:"Access Expires In:"})," ",Math.round(r.expiresIn/1e3/60)," minutes"]}),G("div",{children:[P("strong",{children:"Refresh Expires In:"})," ",Math.round(r.refreshExpiresIn/1e3/60/60)," hours"]}),G("div",{children:[P("strong",{children:"Expiring Soon:"})," ",r.isExpiringSoon?"Yes":"No"]})]})]}):P("div",{children:"Session not initialized"})}import{useState as ce,useEffect as nt,useCallback as st,useRef as ue}from"react";import oi from"@nocios/crudify-sdk";var qr=(r={})=>{let{autoFetch:t=!0,retryOnError:e=!1,maxRetries:i=3}=r,[n,s]=ce(null),[l,o]=ce(!1),[f,E]=ce(null),[b,T]=ce({}),m=ue(null),I=ue(!0),g=ue(0),A=ue(0),N=st(()=>{s(null),E(null),o(!1),T({})},[]),x=st(async()=>{let O=Fe();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 oi.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&&(D.message?.includes("Network Error")||D.message?.includes("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 nt(()=>{t&&x()},[t,x]),nt(()=>(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}};import{useState as be,useEffect as ai,useCallback as de,useRef as li}from"react";import ci from"@nocios/crudify-sdk";var en=(r,t={})=>{let{autoFetch:e=!0,onSuccess:i,onError:n}=t,{prefix:s,padding:l=0,separator:o=""}=r,[f,E]=be(""),[b,T]=be(!1),[m,I]=be(null),g=li(!1),A=de(w=>{let F=String(w).padStart(l,"0");return`${s}${o}${F}`},[s,l,o]),N=de(async()=>{T(!0),I(null);try{let w=await ci.getNextSequence(s),F=w.data;if(w.success&&F?.value){let z=A(F.value);E(z),i?.(z)}else{let z=w.errors?._error?.[0]||"Failed to generate code";I(z),n?.(z)}}catch(w){let F=w instanceof Error?w.message:"Unknown error";I(F),n?.(F)}finally{T(!1)}},[s,A,i,n]),x=de(async()=>{await N()},[N]),O=de(()=>{I(null)},[]);return ai(()=>{e&&!f&&!g.current&&(g.current=!0,N())},[e,f,N]),{value:f,loading:b,error:m,regenerate:x,clearError:O}};import Ie from"@nocios/crudify-sdk";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&&u.warn(`[CrudifyInitialization] ${l} attempted to initialize with different key. Already initialized with key: ${this.state.publicApiKey?.slice(0,10)}... by ${this.state.initializedBy}`);return}if(this.initializationPromise)return s&&u.debug(`[CrudifyInitialization] ${l} waiting for ongoing initialization...`),this.initializationPromise;if(e==="LOW"&&this.highPriorityInitializerPresent&&this.state.status==="UNINITIALIZED"){if(s&&u.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&&u.debug(`[CrudifyInitialization] ${l} found initialization completed by HIGH priority`);return}s&&u.warn(`[CrudifyInitialization] ${l} timeout waiting for HIGH priority, initializing with LOW priority`)}e==="HIGH"&&this.state.status==="INITIALIZING"&&this.state.priority==="LOW"&&(u.warn(`[CrudifyInitialization] HIGH priority request from ${l} interrupting LOW priority initialization by ${this.state.initializedBy}`),this.state.status="UNINITIALIZED",this.initializationPromise=null),s&&u.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&&u.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,u.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&&u.debug(`[CrudifyInitialization] Timeout waiting for HIGH priority (${this.HIGH_PRIORITY_WAIT_TIMEOUT}ms)`),e())},10)})}async performInitialization(t,e,i){let n=Ie.getTokenData();if(n&&n.endpoint){i&&u.debug("[CrudifyInitialization] SDK already initialized externally");return}Ie.config(e);let s=i?"debug":"none",l=await Ie.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=Ae.getInstance();import{useState as fe,useCallback as C,useRef as ui,useMemo as J}from"react";import ge from"@nocios/crudify-sdk";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{if(t&&r.startsWith(t))return r.substring(t.length)}return t&&r.startsWith(t)?r.substring(t.length):r},dn=(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]=fe([]),[I,g]=fe(!1),[A,N]=fe(!1),[x,O]=fe([]),w=ui(new Map),F=C(()=>{g(!0)},[]),z=C(()=>{N(!0),g(!0)},[]),D=C((c,p)=>{m(d=>d.map(h=>h.id===c?{...h,...p}:h))},[]),S=C(c=>{E?.(c)},[E]),Z=C(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=C(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 ge.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&&l?.(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&&o?.(R,y),h})}},[D,l,o,s]),re=C(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 u.warn(`File limit of ${i} already reached`),y;p.length>M&&(p=p.slice(0,M),u.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=C(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=C(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 ge.disableFile({filePath:d})).success?(m(h=>{let R=h.filter(k=>k.id!==c);return S(R),R}),f?.(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=C(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=C(()=>{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=C(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(!y?.filePath){p.push(d);continue}try{let h=ke(y.filePath);(await ge.disableFile({filePath:h})).success?(p.push(d),f?.(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=C(()=>{m([]),S([])},[S]),pt=C(async c=>{let p=T.find(y=>y.id===c);if(!p||p.status!=="error"||!p.file){u.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=C(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=c.split(".").pop()?.toLowerCase()||"";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=C((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=C(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 ge.getFileUrl({filePath:p.filePath,expiresIn:3600}),y=d.data;return d.success&&y?.url?y.url:null}catch{return null}},[T]),Tt=J(()=>T.some(c=>c.status==="uploading"||c.status==="pending"),[T]),St=J(()=>T.filter(c=>c.status==="uploading"||c.status==="pending").length,[T]),vt=J(()=>T.filter(c=>c.status==="completed"&&c.filePath).map(c=>c.filePath),[T]),q=J(()=>T.filter(c=>c.status!=="pendingDeletion"),[T]),bt=J(()=>q.filter(c=>c.status==="completed"||c.status==="pending"||c.status==="uploading").length,[q]),{isValid:It,validationError:At,validationErrorKey:kt,validationErrorParams:xt}=J(()=>{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}};export{v as a,ye as b,W as c,ne as d,Ee as e,Te as f,Je as g,le as h,et as i,tt as j,Vr as k,ni as l,$r as m,qr as n,en as o,Ae as p,ie as q,dn as r};
|
|
1
|
+
import{a as u,d as me,f as H,g as xe,h as we,i as Re,j as Ne,k as Ce,l as Pe,m as De,q as Le,r as Oe,s as Fe}from"./chunk-4ILUXVPW.mjs";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 we(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 u.error("Crudify: Failed to initialize encryption after retries",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()),u.info("Crudify: Storage upgraded to v2, tokens cleared for security")}}catch{}}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{}let t=Ce();try{let e="";for(let i=0;i<t.length;i++)e+=String.fromCharCode(t[i]);localStorage.setItem(a.SALT_KEY,btoa(e))}catch{u.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{}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 xe(e);try{localStorage.setItem(a.ENCRYPTION_KEY_STORAGE,i)}catch{u.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{return!1}}static getStorage(){return a.storageType==="none"?null:a.isStorageAvailable(a.storageType)?window[a.storageType]:(u.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 Re(t,a.encryptionKey,a.salt)}static async decryptData(t){if(await a.initialize(),!a.fingerprint)throw new Error("Encryption not initialized");return Pe(t)?Ne(t,a.fingerprint):(u.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),u.debug("Crudify: Tokens saved successfully")}catch(i){u.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 u.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?(u.warn("Crudify: Incomplete token data found, clearing storage"),await a.clearTokens(),null):Date.now()>=n.refreshExpiresAt?(u.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 u.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),u.debug("Crudify: Tokens cleared from storage")}catch(e){u.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{}u.info("Crudify: Encryption key rotated successfully")}catch(t){u.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){u.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=a.getStorage()?.getItem(a.TOKEN_KEY);if(l!==null&&l!=="")return}let n=i.oldValue!==null&&i.oldValue!=="";if(i.newValue===null){u.debug("Crudify: Tokens removed in another tab"),t(null,a.SYNC_EVENTS.TOKENS_CLEARED,n);return}if(i.newValue){u.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=()=>{u.warn("Crudify: CrossTabSync message error")},u.debug("Crudify: CrossTabSync initialized with BroadcastChannel")):u.debug("Crudify: BroadcastChannel not available, using localStorage fallback"),this.isInitialized=!0}catch(t){u.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),u.debug(`Crudify: CrossTab broadcast ${t.type}`))}catch(e){u.warn("Crudify: Failed to broadcast cross-tab message",{message:e instanceof Error?e.message:String(e)})}}handleMessage(t){t.tabId!==this.tabId&&(u.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){u.error("Crudify: CrossTab listener error",{message:i instanceof Error?i.message:String(i)})}}))}};K.instance=null;var ye=K,W=ye.getInstance();import L from"@nocios/crudify-sdk";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(),L.setTokenInvalidationCallback(()=>{this.log("Tokens invalidated by crudify-core"),H.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 L.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:n?.apiEndpointAdmin||this.config.apiEndpointAdmin,apiKeyEndpointAdmin:n?.apiKeyEndpointAdmin||this.config.apiKeyEndpointAdmin};return await v.saveTokens(l),v.markSuccessfulLogin(),this.lastActivityTime=Date.now(),W.notifyLogin(),this.config.onLoginSuccess?.(l),{success:!0,tokens:l,data:s}}catch(i){return u.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..."),H.emit("LOGOUT",{message:"User logged out",source:"SessionManager.logout"}),await L.logout(),await v.clearTokens(),W.notifyLogout(),this.log("Logout successful"),this.config.onLogout?.()}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(L.setTokens({accessToken:t.accessToken,refreshToken:t.refreshToken,expiresAt:t.expiresAt,refreshExpiresAt:t.refreshExpiresAt}),L.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&&this.config.onSessionRestored?.(n),!0}return await v.clearTokens(),await L.logout(),!1}return this.log("Session restored successfully"),this.lastActivityTime=Date.now(),this.config.onSessionRestored?.(t),!0}catch(t){return this.log("Session restore error",{error:t instanceof Error?t.message:String(t)}),await v.clearTokens(),await L.logout(),!1}}async isAuthenticated(){return L.isLogin()||await v.hasValidTokens()}async getTokenInfo(){let t=L.getTokenData(),e=await v.getExpirationInfo(),i=await v.getTokens();return{isLoggedIn:await this.isAuthenticated(),crudifyTokens:t,storageInfo:e,hasValidTokens:await v.hasValidTokens(),apiEndpointAdmin:i?.apiEndpointAdmin,apiKeyEndpointAdmin:i?.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 L.refreshAccessToken();if(!t.success)return this.log("Token refresh failed",{errors:t.errors}),await v.clearTokens(),this.config.showNotification?.(this.getSessionExpiredMessage(),"warning"),this.config.onSessionExpired?.(),!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(),this.config.showNotification?.(this.getSessionExpiredMessage(),"warning"),this.config.onSessionExpired?.(),!1}}isRefreshing(){return this.isRefreshingLocally}setupResponseInterceptor(){L.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"),H.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"),H.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"),H.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=L.getTokenData();if(t&&t.endpoint){this.log("Crudify already initialized by another service"),this.crudifyInitialized=!0;return}let e=this.config.env||"stg";L.config(e);let i=this.config.publicApiKey,n=this.config.enableLogging?"debug":"none",s=await L.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 u.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"||n.message?.includes("Unauthorized")||n.message?.includes("Not Authorized")||n.message?.includes("NOT_AUTHORIZED")||n.message?.includes("Token")||n.message?.includes("TOKEN")||n.message?.includes("Authentication")||n.message?.includes("UNAUTHENTICATED")||n.extensions?.code==="UNAUTHENTICATED"||n.extensions?.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.",(i.message?.includes("TOKEN")||i.message?.includes("Token"))&&(e.isTokenExpired=!0),i.extensions?.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&&t.data?.response?.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&&t.data?.response?.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{}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 L.logout(),this.lastActivityTime=0,this.log("Session cleared completely")}getSessionExpiredMessage(){return this.config.translateFn?De("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&&u.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"}};import{useEffect as Kt,useCallback as j}from"react";import{useState as Pt,useCallback as Q}from"react";var Ke={isAuthenticated:!1,isLoading:!0,isLoggingOut:!1,isInitialized:!1,tokens:null,error:null};function Me(){let[r,t]=Pt(Ke),e=Q(o=>{t(f=>({...f,isLoading:o}))},[]),i=Q((o,f)=>{t(E=>({...E,isAuthenticated:o,tokens:f,error:o?null:E.error}))},[]),n=Q(o=>{t(f=>({...f,isLoggingOut:o}))},[]),s=Q(o=>{t(f=>({...f,error:o}))},[]),l=Q(o=>{t(f=>({...f,isInitialized:o}))},[]);return{state:r,setState:t,setLoading:e,setAuthenticated:i,setLoggingOut:n,setError:s,setInitialized:l}}import{useCallback as oe}from"react";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=oe(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";u.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=oe(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=oe(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=oe(()=>{e.setError(null)},[e]);return{login:i,logout:n,refreshTokens:s,clearError:l}}import{useEffect as Ot,useCallback as Ft}from"react";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=Ft(()=>{i.updateLastActivity()},[i]);Ot(()=>{if(!t||!e)return;let b=Le.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])}import{useEffect as Ut}from"react";function Be(r){let{sessionManager:t,onTokensUpdated:e,onSessionExpired:i,onSetLoading:n,onSetError:s}=r;Ut(()=>{let l=H.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 H.emit("SESSION_EXPIRED",{message:"Failed to refresh token after detecting expiration",source:"useSession.TOKEN_EXPIRED handler"})}catch(f){H.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(o.details?.message?.toString()||"Session expired"),i())});return()=>l()},[t,e,i,n,s])}import{useEffect as We}from"react";function Xe(r){let{isAuthenticated:t,onTokensUpdated:e,onSessionExpired:i}=r;We(()=>{let n=async l=>{switch(l.type){case"SESSION_STARTED":case"TOKEN_REFRESHED":try{await v.ensureInitialized();let o=await v.getTokens();o&&(u.debug(`[useCrossTabSync] Syncing ${l.type} from tab ${l.tabId}`),e(o))}catch(o){u.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()||(u.debug(`[useCrossTabSync] Syncing SESSION_ENDED from tab ${l.tabId}`),e(null),t&&i())}catch(o){u.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]),We(()=>{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:e.autoRestore??!0,enableLogging: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"})),e.onSessionExpired?.()},onSessionRestored:o=>{i.setState(f=>({...f,isAuthenticated:!0,tokens:o,error:null})),e.onSessionRestored?.(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";u.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=j(g=>{e.setAuthenticated(!!g,g)},[e]),E=j(()=>{e.setAuthenticated(!1,null),r.onSessionExpired?.()},[e,r.onSessionExpired]),b=j(g=>{e.setLoading(g)},[e]),T=j(g=>{e.setError(g)},[e]);Kt(()=>{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=j(()=>{t.updateLastActivity()},[t]),I=j(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)}}import{useState as qe,createContext as Mt,useContext as Ht,useCallback as ae,useEffect as Gt}from"react";import{Snackbar as _t,Alert as Vt,Box as $t,Portal as Yt}from"@mui/material";import{v4 as Bt}from"uuid";import Wt from"dompurify";import{jsx as X,jsxs as qt}from"react/jsx-runtime";var je=Mt(null),Xt=r=>Wt.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=({children:r,maxNotifications:t=5,defaultAutoHideDuration:e=6e3,position:i={vertical:"top",horizontal:"right"},enabled:n=!1,allowHtml:s=!1})=>{let[l,o]=qe([]),f=ae((m,I="info",g)=>{if(!n)return"";if(!m||typeof m!="string")return u.warn("GlobalNotificationProvider: Invalid message provided"),"";m.length>1e3&&(u.warn("GlobalNotificationProvider: Message too long, truncating"),m=m.substring(0,1e3)+"...");let A=Bt(),N={id:A,message:m,severity:I,autoHideDuration:g?.autoHideDuration??e,persistent:g?.persistent??!1,allowHtml:g?.allowHtml??s};return o(x=>[...x.length>=t?x.slice(-(t-1)):x,N]),A},[t,e,n,s]),E=ae(m=>{o(I=>I.filter(g=>g.id!==m))},[]),b=ae(()=>{o([])},[]),T={showNotification:f,hideNotification:E,clearAllNotifications:b};return qt(je.Provider,{value:T,children:[r,n&&X(Yt,{children:X($t,{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=>X(Zt,{notification:m,onClose:()=>E(m.id)},m.id))})})]})},Zt=({notification:r,onClose:t})=>{let[e,i]=qe(!0),n=ae((s,l)=>{l!=="clickaway"&&(i(!1),setTimeout(t,300))},[t]);return Gt(()=>{if(!r.persistent&&r.autoHideDuration){let s=setTimeout(()=>{n()},r.autoHideDuration);return()=>clearTimeout(s)}},[r.autoHideDuration,r.persistent,n]),X(_t,{open:e,onClose:n,sx:{position:"relative","& .MuiSnackbarContent-root":{minWidth:"auto"}},TransitionProps:{enter:!0,exit:!0},children:X(Vt,{variant:"filled",severity:r.severity,onClose:n,sx:{width:"100%",minWidth:"280px",maxWidth:"400px",wordBreak:"break-word"},children:r.allowHtml?X("span",{dangerouslySetInnerHTML:{__html:Xt(r.message)}}):X("span",{children:r.message})})})},Je=()=>{let r=Ht(je);if(!r)throw new Error("useGlobalNotification debe ser usado dentro de un GlobalNotificationProvider");return r};import{createContext as jt,useContext as Jt,useEffect as Qt,useState as ee}from"react";import te from"@nocios/crudify-sdk";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){u.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=Se.getInstance();import{jsx as ei}from"react/jsx-runtime";var Qe=jt(void 0),et=({config:r,children:t})=>{let[e,i]=ee(!0),[n,s]=ee(null),[l,o]=ee(!1),[f,E]=ee(""),[b,T]=ee();Qt(()=>{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{te.config(r.env||"prod");let A=await te.init(r.publicApiKey,"none");if(T(A),typeof te.transaction=="function"&&typeof te.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";u.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?te:null,isLoading:e,error:n,isInitialized:l,adminCredentials:b};return ei(Qe.Provider,{value:m,children:t})},tt=()=>{let r=Jt(Qe);if(r===void 0)throw new Error("useCrudify must be used within a CrudifyProvider");return r};import ti,{createContext as ii,useContext as ri,useMemo as ve}from"react";import{Fragment as si,jsx as P,jsxs as G}from"react/jsx-runtime";var rt=ii(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{}let l={};try{let g=tt();g.isInitialized&&g.adminCredentials&&(l=g.adminCredentials)}catch{}let o=ve(()=>{let g=me({publicApiKey:e?.publicApiKey,env:e?.env,enableDebug:t?.enableLogging});return{publicApiKey:g.publicApiKey,env:g.env||"prod"}},[e,t?.enableLogging]),f=ti.useMemo(()=>({...t,showNotification:s,apiEndpointAdmin:l.apiEndpointAdmin,apiKeyEndpointAdmin:l.apiKeyEndpointAdmin,publicApiKey:o.publicApiKey,env:o.env,onSessionExpired:()=>{t.onSessionExpired?.()}}),[t,s,l.apiEndpointAdmin,l.apiKeyEndpointAdmin,o]),E=Ee(f),b=ve(()=>{let g=me({publicApiKey:e?.publicApiKey,env:e?.env,appName:e?.appName,logo:e?.logo,loginActions:e?.loginActions,enableDebug:t?.enableLogging});return{publicApiKey:g.publicApiKey,env:g.env,appName:g.appName,loginActions:g.loginActions,logo:g.logo}},[e,t?.enableLogging]),T=ve(()=>{if(!E.tokens?.accessToken||!E.isAuthenticated)return null;try{let g=Oe(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){u.error("Error decoding JWT token for sessionData",g instanceof Error?g:{message:String(g)})}return null},[E.tokens?.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 P(rt.Provider,{value:m,children:r})}function Vr(r){let t={enabled:r.showNotifications,maxNotifications:r.notificationOptions?.maxNotifications||5,defaultAutoHideDuration:r.notificationOptions?.defaultAutoHideDuration||6e3,position:r.notificationOptions?.position||{vertical:"top",horizontal:"right"},allowHtml:r.notificationOptions?.allowHtml||!1};return r.config?.publicApiKey?P(et,{config:{publicApiKey:r.config.publicApiKey,env:r.config.env||"prod",appName:r.config.appName,loginActions:r.config.loginActions,logo:r.config.logo},children:P(Te,{...t,children:P(it,{...r})})}):P(Te,{...t,children:P(it,{...r})})}function ni(){let r=ri(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?G("div",{style:{padding:"10px",margin:"10px",border:"1px solid #ccc",borderRadius:"4px",fontSize:"12px",fontFamily:"monospace"},children:[P("h4",{children:"Session Debug Info"}),G("div",{children:[P("strong",{children:"Authenticated:"})," ",r.isAuthenticated?"Yes":"No"]}),G("div",{children:[P("strong",{children:"Loading:"})," ",r.isLoading?"Yes":"No"]}),G("div",{children:[P("strong",{children:"Error:"})," ",r.error||"None"]}),r.tokens&&G(si,{children:[G("div",{children:[P("strong",{children:"Access Token:"})," ",r.tokens.accessToken.substring(0,20),"..."]}),G("div",{children:[P("strong",{children:"Refresh Token:"})," ",r.tokens.refreshToken.substring(0,20),"..."]}),G("div",{children:[P("strong",{children:"Access Expires In:"})," ",Math.round(r.expiresIn/1e3/60)," minutes"]}),G("div",{children:[P("strong",{children:"Refresh Expires In:"})," ",Math.round(r.refreshExpiresIn/1e3/60/60)," hours"]}),G("div",{children:[P("strong",{children:"Expiring Soon:"})," ",r.isExpiringSoon?"Yes":"No"]})]})]}):P("div",{children:"Session not initialized"})}import{useState as ce,useEffect as nt,useCallback as st,useRef as ue}from"react";import oi from"@nocios/crudify-sdk";var qr=(r={})=>{let{autoFetch:t=!0,retryOnError:e=!1,maxRetries:i=3}=r,[n,s]=ce(null),[l,o]=ce(!1),[f,E]=ce(null),[b,T]=ce({}),m=ue(null),I=ue(!0),g=ue(0),A=ue(0),N=st(()=>{s(null),E(null),o(!1),T({})},[]),x=st(async()=>{let O=Fe();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 oi.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&&(D.message?.includes("Network Error")||D.message?.includes("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 nt(()=>{t&&x()},[t,x]),nt(()=>(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}};import{useState as be,useEffect as ai,useCallback as de,useRef as li}from"react";import ci from"@nocios/crudify-sdk";var en=(r,t={})=>{let{autoFetch:e=!0,onSuccess:i,onError:n}=t,{prefix:s,padding:l=0,separator:o=""}=r,[f,E]=be(""),[b,T]=be(!1),[m,I]=be(null),g=li(!1),A=de(w=>{let F=String(w).padStart(l,"0");return`${s}${o}${F}`},[s,l,o]),N=de(async()=>{T(!0),I(null);try{let w=await ci.getNextSequence(s),F=w.data;if(w.success&&F?.value){let z=A(F.value);E(z),i?.(z)}else{let z=w.errors?._error?.[0]||"Failed to generate code";I(z),n?.(z)}}catch(w){let F=w instanceof Error?w.message:"Unknown error";I(F),n?.(F)}finally{T(!1)}},[s,A,i,n]),x=de(async()=>{await N()},[N]),O=de(()=>{I(null)},[]);return ai(()=>{e&&!f&&!g.current&&(g.current=!0,N())},[e,f,N]),{value:f,loading:b,error:m,regenerate:x,clearError:O}};import Ie from"@nocios/crudify-sdk";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&&u.warn(`[CrudifyInitialization] ${l} attempted to initialize with different key. Already initialized with key: ${this.state.publicApiKey?.slice(0,10)}... by ${this.state.initializedBy}`);return}if(this.initializationPromise)return s&&u.debug(`[CrudifyInitialization] ${l} waiting for ongoing initialization...`),this.initializationPromise;if(e==="LOW"&&this.highPriorityInitializerPresent&&this.state.status==="UNINITIALIZED"){if(s&&u.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&&u.debug(`[CrudifyInitialization] ${l} found initialization completed by HIGH priority`);return}s&&u.warn(`[CrudifyInitialization] ${l} timeout waiting for HIGH priority, initializing with LOW priority`)}e==="HIGH"&&this.state.status==="INITIALIZING"&&this.state.priority==="LOW"&&(u.warn(`[CrudifyInitialization] HIGH priority request from ${l} interrupting LOW priority initialization by ${this.state.initializedBy}`),this.state.status="UNINITIALIZED",this.initializationPromise=null),s&&u.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&&u.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,u.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&&u.debug(`[CrudifyInitialization] Timeout waiting for HIGH priority (${this.HIGH_PRIORITY_WAIT_TIMEOUT}ms)`),e())},10)})}async performInitialization(t,e,i){let n=Ie.getTokenData();if(n&&n.endpoint){i&&u.debug("[CrudifyInitialization] SDK already initialized externally");return}Ie.config(e);let s=i?"debug":"none",l=await Ie.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=Ae.getInstance();import{useState as fe,useCallback as C,useRef as ui,useMemo as J}from"react";import ge from"@nocios/crudify-sdk";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{if(t&&r.startsWith(t))return r.substring(t.length)}return t&&r.startsWith(t)?r.substring(t.length):r},dn=(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]=fe([]),[I,g]=fe(!1),[A,N]=fe(!1),[x,O]=fe([]),w=ui(new Map),F=C(()=>{g(!0)},[]),z=C(()=>{N(!0),g(!0)},[]),D=C((c,p)=>{m(d=>d.map(h=>h.id===c?{...h,...p}:h))},[]),S=C(c=>{E?.(c)},[E]),Z=C(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=C(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 ge.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&&l?.(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&&o?.(R,y),h})}},[D,l,o,s]),re=C(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 u.warn(`File limit of ${i} already reached`),y;p.length>M&&(p=p.slice(0,M),u.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=C(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=C(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 ge.disableFile({filePath:d})).success?(m(h=>{let R=h.filter(k=>k.id!==c);return S(R),R}),f?.(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=C(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=C(()=>{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=C(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(!y?.filePath){p.push(d);continue}try{let h=ke(y.filePath);(await ge.disableFile({filePath:h})).success?(p.push(d),f?.(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=C(()=>{m([]),S([])},[S]),pt=C(async c=>{let p=T.find(y=>y.id===c);if(!p||p.status!=="error"||!p.file){u.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=C(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=c.split(".").pop()?.toLowerCase()||"";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=C((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=C(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 ge.getFileUrl({filePath:p.filePath,expiresIn:3600}),y=d.data;return d.success&&y?.url?y.url:null}catch{return null}},[T]),Tt=J(()=>T.some(c=>c.status==="uploading"||c.status==="pending"),[T]),St=J(()=>T.filter(c=>c.status==="uploading"||c.status==="pending").length,[T]),vt=J(()=>T.filter(c=>c.status==="completed"&&c.filePath).map(c=>c.filePath),[T]),q=J(()=>T.filter(c=>c.status!=="pendingDeletion"),[T]),bt=J(()=>q.filter(c=>c.status==="completed"||c.status==="pending"||c.status==="uploading").length,[q]),{isValid:It,validationError:At,validationErrorKey:kt,validationErrorParams:xt}=J(()=>{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}};export{v as a,ye as b,W as c,ne as d,Ee as e,Te as f,Je as g,le as h,et as i,tt as j,Vr as k,ni as l,$r as m,qr as n,en as o,Ae as p,ie as q,dn as r};
|