@nocios/crudify-ui 4.4.50 → 4.4.54

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +0,0 @@
1
- import{b as se,d as he,h as K,i as me,j as Ee,k as Te}from"./chunk-6GPSBDW6.mjs";import{createContext as He,useContext as Me,useEffect as Ge,useState as X}from"react";import Y from"@nocios/crudify-browser";var ae=class r{constructor(){this.listeners=[];this.credentials=null;this.isReady=!1}static getInstance(){return r.instance||(r.instance=new r),r.instance}notifyCredentialsReady(i){this.credentials=i,this.isReady=!0,this.listeners.forEach(e=>{try{e(i)}catch(t){console.error("[CredentialsEventBus] Error in listener:",t)}}),this.listeners=[]}waitForCredentials(){return this.isReady&&this.credentials?Promise.resolve(this.credentials):new Promise(i=>{this.listeners.push(i)})}reset(){this.credentials=null,this.isReady=!1,this.listeners=[]}areCredentialsReady(){return this.isReady&&this.credentials!==null}},Z=ae.getInstance();import{jsx as $e}from"react/jsx-runtime";var ve=He(void 0),Ae=({config:r,children:i})=>{let[e,t]=X(!0),[n,s]=X(null),[d,h]=X(!1),[S,I]=X(""),[m,c]=X();Ge(()=>{if(!r.publicApiKey){s("No publicApiKey provided"),t(!1),h(!1);return}let l=`${r.publicApiKey}-${r.env}`;if(l===S&&d){t(!1);return}(async()=>{t(!0),s(null),h(!1);try{Y.config(r.env||"prod");let p=await Y.init(r.publicApiKey,"none");if(c(p),typeof Y.transaction=="function"&&typeof Y.login=="function")h(!0),I(l),p.apiEndpointAdmin&&p.apiKeyEndpointAdmin&&Z.notifyCredentialsReady({apiUrl:p.apiEndpointAdmin,apiKey:p.apiKeyEndpointAdmin});else throw new Error("Crudify methods not properly initialized")}catch(p){let E=p instanceof Error?p.message:"Failed to initialize Crudify";console.error("[CrudifyProvider] Initialization error:",p),s(E),h(!1)}finally{t(!1)}})()},[r.publicApiKey,r.env,S,d]);let a={crudify:d?Y:null,isLoading:e,error:n,isInitialized:d,adminCredentials:m};return $e(ve.Provider,{value:a,children:i})},Ie=()=>{let r=Me(ve);if(r===void 0)throw new Error("useCrudify must be used within a CrudifyProvider");return r};import W from"crypto-js";var f=class f{static setStorageType(i){f.storageType=i}static generateEncryptionKey(){let i=[navigator.userAgent,navigator.language,navigator.platform,screen.width,screen.height,Date.now().toString(),Math.random().toString(36)].join("|");return W.SHA256(i).toString()}static getEncryptionKey(){if(f.encryptionKey)return f.encryptionKey;let i=window.localStorage;if(!i)return f.encryptionKey=f.generateEncryptionKey(),f.encryptionKey;try{let e=i.getItem(f.ENCRYPTION_KEY_STORAGE);return(!e||e.length<32)&&(e=f.generateEncryptionKey(),i.setItem(f.ENCRYPTION_KEY_STORAGE,e)),f.encryptionKey=e,e}catch{return console.warn("Crudify: Cannot persist encryption key, using temporary key"),f.encryptionKey=f.generateEncryptionKey(),f.encryptionKey}}static isStorageAvailable(i){try{let e=window[i],t="__storage_test__";return e.setItem(t,"test"),e.removeItem(t),!0}catch{return!1}}static getStorage(){return f.storageType==="none"?null:f.isStorageAvailable(f.storageType)?window[f.storageType]:(console.warn(`Crudify: ${f.storageType} not available, tokens won't persist`),null)}static encrypt(i){try{let e=f.getEncryptionKey();return W.AES.encrypt(i,e).toString()}catch(e){return console.error("Crudify: Encryption failed",e),i}}static decrypt(i){try{let e=f.getEncryptionKey();return W.AES.decrypt(i,e).toString(W.enc.Utf8)||i}catch(e){return console.error("Crudify: Decryption failed",e),i}}static saveTokens(i){let e=f.getStorage();if(e)try{let t={accessToken:i.accessToken,refreshToken:i.refreshToken,expiresAt:i.expiresAt,refreshExpiresAt:i.refreshExpiresAt,savedAt:Date.now()},n=f.encrypt(JSON.stringify(t));e.setItem(f.TOKEN_KEY,n),console.debug("Crudify: Tokens saved successfully")}catch(t){console.error("Crudify: Failed to save tokens",t)}}static getTokens(){let i=f.getStorage();if(!i)return null;try{let e=i.getItem(f.TOKEN_KEY);if(!e)return null;let t=f.decrypt(e),n=JSON.parse(t);return!n.accessToken||!n.refreshToken||!n.expiresAt||!n.refreshExpiresAt?(console.warn("Crudify: Incomplete token data found, clearing storage"),f.clearTokens(),null):Date.now()>=n.refreshExpiresAt?(console.info("Crudify: Refresh token expired, clearing storage"),f.clearTokens(),null):{accessToken:n.accessToken,refreshToken:n.refreshToken,expiresAt:n.expiresAt,refreshExpiresAt:n.refreshExpiresAt}}catch(e){return console.error("Crudify: Failed to retrieve tokens",e),f.clearTokens(),null}}static clearTokens(){let i=f.getStorage();if(i)try{i.removeItem(f.TOKEN_KEY),console.debug("Crudify: Tokens cleared from storage")}catch(e){console.error("Crudify: Failed to clear tokens",e)}}static rotateEncryptionKey(){try{f.clearTokens(),f.encryptionKey=null;let i=window.localStorage;i&&i.removeItem(f.ENCRYPTION_KEY_STORAGE),console.info("Crudify: Encryption key rotated successfully")}catch(i){console.error("Crudify: Failed to rotate encryption key",i)}}static hasValidTokens(){return f.getTokens()!==null}static getExpirationInfo(){let i=f.getTokens();if(!i)return null;let e=Date.now();return{accessExpired:e>=i.expiresAt,refreshExpired:e>=i.refreshExpiresAt,accessExpiresIn:Math.max(0,i.expiresAt-e),refreshExpiresIn:Math.max(0,i.refreshExpiresAt-e)}}static updateAccessToken(i,e){let t=f.getTokens();if(!t){console.warn("Crudify: Cannot update access token, no existing tokens found");return}f.saveTokens({...t,accessToken:i,expiresAt:e})}static subscribeToChanges(i){let e=t=>{if(t.key===f.TOKEN_KEY){if(t.newValue===null){console.debug("Crudify: Tokens removed in another tab"),i(null);return}if(t.newValue){console.debug("Crudify: Tokens updated in another tab");let n=f.getTokens();i(n)}}};return window.addEventListener("storage",e),()=>{window.removeEventListener("storage",e)}}};f.TOKEN_KEY="crudify_tokens",f.ENCRYPTION_KEY_STORAGE="crudify_enc_key",f.encryptionKey=null,f.storageType="localStorage";var A=f;import R from"@nocios/crudify-browser";var q=class r{constructor(){this.config={};this.initialized=!1;this.crudifyInitialized=!1;this.lastActivityTime=0;this.isRefreshingLocally=!1;this.refreshPromise=null}static getInstance(){return r.instance||(r.instance=new r),r.instance}async initialize(i={}){if(!this.initialized){if(this.config={storageType:"localStorage",autoRestore:!0,enableLogging:!1,env:"stg",...i},A.setStorageType(this.config.storageType||"localStorage"),this.config.publicApiKey&&!this.crudifyInitialized&&await this.ensureCrudifyInitialized(),R.setTokenInvalidationCallback(()=>{this.log("Tokens invalidated by crudify-core"),K.emit("SESSION_EXPIRED",{message:"Your session has expired. Please log in again.",source:"crudify-core.clearTokensAndRefreshState"})}),this.config.apiEndpointAdmin&&this.config.apiKeyEndpointAdmin){let e=A.getTokens();e?A.saveTokens({...e,apiEndpointAdmin:this.config.apiEndpointAdmin,apiKeyEndpointAdmin:this.config.apiKeyEndpointAdmin}):A.saveTokens({accessToken:"",refreshToken:"",expiresAt:0,refreshExpiresAt:0,apiEndpointAdmin:this.config.apiEndpointAdmin,apiKeyEndpointAdmin:this.config.apiKeyEndpointAdmin})}this.config.autoRestore&&await this.restoreSession(),this.initialized=!0}}async login(i,e){try{let t=await R.login(i,e);if(!t.success)return{success:!1,error:this.formatError(t.errors),rawResponse:t};let n=A.getTokens(),s={accessToken:t.data.token,refreshToken:t.data.refreshToken,expiresAt:t.data.expiresAt,refreshExpiresAt:t.data.refreshExpiresAt,apiEndpointAdmin:n?.apiEndpointAdmin||this.config.apiEndpointAdmin,apiKeyEndpointAdmin:n?.apiKeyEndpointAdmin||this.config.apiKeyEndpointAdmin};return A.saveTokens(s),this.lastActivityTime=Date.now(),this.config.onLoginSuccess?.(s),{success:!0,tokens:s,data:t.data}}catch(t){return console.error("[SessionManager] Login error:",t),{success:!1,error:t instanceof Error?t.message:"Unknown error"}}}async logout(){try{this.log("Logging out..."),await R.logout(),A.clearTokens(),this.log("Logout successful"),this.config.onLogout?.()}catch(i){this.log("Logout error:",i),A.clearTokens()}}async restoreSession(){try{this.log("Attempting to restore session...");let i=A.getTokens();if(!i)return this.log("No valid tokens found in storage"),!1;if(Date.now()>=i.refreshExpiresAt)return this.log("Refresh token expired, clearing storage"),A.clearTokens(),!1;if(R.setTokens({accessToken:i.accessToken,refreshToken:i.refreshToken,expiresAt:i.expiresAt,refreshExpiresAt:i.refreshExpiresAt}),R.getTokenData().isValid===!1){if(this.log("Restored access token is invalid or expired"),Date.now()<i.refreshExpiresAt&&(this.log("Access token expired but refresh is valid, attempting refresh..."),await this.refreshTokens())){this.log("Session restored successfully via token refresh");let n=A.getTokens();return n&&this.config.onSessionRestored?.(n),!0}return A.clearTokens(),await R.logout(),!1}return this.log("Session restored successfully"),this.lastActivityTime=Date.now(),this.config.onSessionRestored?.(i),!0}catch(i){return this.log("Session restore error:",i),A.clearTokens(),await R.logout(),!1}}isAuthenticated(){return R.isLogin()||A.hasValidTokens()}getTokenInfo(){let i=R.getTokenData(),e=A.getExpirationInfo(),t=A.getTokens();return{isLoggedIn:this.isAuthenticated(),crudifyTokens:i,storageInfo:e,hasValidTokens:A.hasValidTokens(),apiEndpointAdmin:t?.apiEndpointAdmin,apiKeyEndpointAdmin:t?.apiKeyEndpointAdmin}}async refreshTokens(){if(this.isRefreshingLocally&&this.refreshPromise)return this.log("Refresh already in progress, waiting for existing promise..."),this.refreshPromise;this.isRefreshingLocally=!0,this.refreshPromise=this._performRefresh();try{return await this.refreshPromise}finally{this.isRefreshingLocally=!1,this.refreshPromise=null}}async _performRefresh(){try{this.log("Starting token refresh...");let i=await R.refreshAccessToken();if(!i.success)return this.log("Token refresh failed:",i.errors),A.clearTokens(),this.config.showNotification?.(this.getSessionExpiredMessage(),"warning"),this.config.onSessionExpired?.(),!1;let e={accessToken:i.data.token,refreshToken:i.data.refreshToken,expiresAt:i.data.expiresAt,refreshExpiresAt:i.data.refreshExpiresAt};return A.saveTokens(e),this.log("Tokens refreshed and saved successfully"),this.lastActivityTime=Date.now(),!0}catch(i){return this.log("Token refresh error:",i),A.clearTokens(),this.config.showNotification?.(this.getSessionExpiredMessage(),"warning"),this.config.onSessionExpired?.(),!1}}isRefreshing(){return this.isRefreshingLocally}setupResponseInterceptor(){R.setResponseInterceptor(async i=>{this.updateLastActivity();let e=this.detectAuthorizationError(i);if(e.isAuthError){if(this.log("\u{1F6A8} Authorization error detected:",{errorType:e.errorType,shouldLogout:e.shouldTriggerLogout}),e.isRefreshTokenInvalid||e.isTokenRefreshFailed)return this.log("Refresh token invalid, emitting TOKEN_REFRESH_FAILED event"),K.emit("TOKEN_REFRESH_FAILED",{message:e.userFriendlyMessage,error:e.errorDetails,source:"SessionManager.setupResponseInterceptor"}),i;e.shouldTriggerLogout&&(A.hasValidTokens()&&!e.isIrrecoverable?(this.log("Access token expired, emitting TOKEN_EXPIRED event"),K.emit("TOKEN_EXPIRED",{message:"Access token expired, refresh needed",error:e.errorDetails,source:"SessionManager.setupResponseInterceptor"})):(this.log("No valid tokens or irrecoverable error, emitting SESSION_EXPIRED event"),K.emit("SESSION_EXPIRED",{message:e.userFriendlyMessage,error:e.errorDetails,source:"SessionManager.setupResponseInterceptor"})))}return i}),this.log("Response interceptor configured (non-blocking mode)")}async ensureCrudifyInitialized(){if(!this.crudifyInitialized)try{this.log("Initializing crudify SDK...");let i=R.getTokenData();if(i&&i.endpoint){this.log("Crudify already initialized by another service"),this.crudifyInitialized=!0;return}let e=this.config.env||"stg";R.config(e);let t=this.config.publicApiKey,n=this.config.enableLogging?"debug":"none",s=await R.init(t,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(i){throw console.error("[SessionManager] Failed to initialize crudify:",i),i}}detectAuthorizationError(i){let e={isAuthError:!1,isRefreshTokenInvalid:!1,isTokenRefreshFailed:!1,isTokenExpired:!1,isUnauthorized:!1,isIrrecoverable:!1,shouldTriggerLogout:!1,errorType:"",errorDetails:null,userFriendlyMessage:""};if(i.errors&&Array.isArray(i.errors)){let t=i.errors.find(n=>n.errorType==="Unauthorized"||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");t&&(e.isAuthError=!0,e.errorType="GraphQL Array",e.errorDetails=t,e.shouldTriggerLogout=!0,e.userFriendlyMessage="Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente.",(t.message?.includes("TOKEN")||t.message?.includes("Token"))&&(e.isTokenExpired=!0),t.extensions?.code==="UNAUTHENTICATED"&&(e.isUnauthorized=!0))}if(!e.isAuthError&&i.errors&&typeof i.errors=="object"&&!Array.isArray(i.errors)){let n=Object.values(i.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=i.errors,e.shouldTriggerLogout=!0,n.includes("TOKEN_REFRESH_FAILED")?(e.isTokenRefreshFailed=!0,e.isRefreshTokenInvalid=!0,e.isIrrecoverable=!0,e.userFriendlyMessage="Tu sesi\xF3n ha caducado. Por favor, inicia sesi\xF3n nuevamente."):n.includes("TOKEN_HAS_EXPIRED")||n.includes("SESSION_EXPIRED")?(e.isTokenExpired=!0,e.userFriendlyMessage="Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente."):n.includes("INVALID_TOKEN")?(e.isTokenExpired=!0,e.isIrrecoverable=!0,e.userFriendlyMessage="Token inv\xE1lido. Por favor, inicia sesi\xF3n nuevamente."):e.userFriendlyMessage="Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente.")}if(!e.isAuthError&&i.data?.response?.status){let t=i.data.response.status.toUpperCase();(t==="UNAUTHORIZED"||t==="UNAUTHENTICATED")&&(e.isAuthError=!0,e.errorType="Status",e.errorDetails=i.data.response,e.isUnauthorized=!0,e.shouldTriggerLogout=!0,e.isIrrecoverable=!0,e.userFriendlyMessage="Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente.")}if(!e.isAuthError&&i.data?.response?.data)try{let t=typeof i.data.response.data=="string"?JSON.parse(i.data.response.data):i.data.response.data;(t.error==="REFRESH_TOKEN_INVALID"||t.error==="TOKEN_EXPIRED"||t.error==="INVALID_TOKEN")&&(e.isAuthError=!0,e.errorType="Parsed Data",e.errorDetails=t,e.shouldTriggerLogout=!0,e.isIrrecoverable=!0,t.error==="REFRESH_TOKEN_INVALID"?(e.isRefreshTokenInvalid=!0,e.isTokenRefreshFailed=!0,e.userFriendlyMessage="Tu sesi\xF3n ha caducado. Por favor, inicia sesi\xF3n nuevamente."):(e.isTokenExpired=!0,e.userFriendlyMessage="Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente."))}catch{}if(!e.isAuthError&&i.errorCode){let t=i.errorCode.toUpperCase();(t==="UNAUTHORIZED"||t==="UNAUTHENTICATED"||t==="TOKEN_EXPIRED"||t==="INVALID_TOKEN")&&(e.isAuthError=!0,e.errorType="Error Code",e.errorDetails={errorCode:t},e.shouldTriggerLogout=!0,t==="TOKEN_EXPIRED"?e.isTokenExpired=!0:e.isUnauthorized=!0,e.userFriendlyMessage="Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente.")}return e}updateLastActivity(){this.lastActivityTime=Date.now(),this.log("Last activity updated")}getTimeSinceLastActivity(){return this.lastActivityTime===0?0:Date.now()-this.lastActivityTime}checkInactivity(){let i=this.getTimeSinceLastActivity();if(this.lastActivityTime===0)return"none";let e=1800*1e3;return i>e?(this.log(`Inactivity timeout: ${Math.floor(i/6e4)} minutes since last activity`),"logout"):"none"}clearSession(){A.clearTokens(),R.logout(),this.lastActivityTime=0,this.log("Session cleared completely")}getSessionExpiredMessage(){return this.config.translateFn?he("SESSION_EXPIRED",{translateFn:this.config.translateFn,enableDebug:this.config.enableLogging}):"Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente."}log(i,...e){this.config.enableLogging&&console.log(`[SessionManager] ${i}`,...e)}formatError(i){return i?typeof i=="string"?i:typeof i=="object"?Object.values(i).flat().join(", "):"Authentication failed":"Unknown error"}};import{useState as _e,useEffect as J,useCallback as $}from"react";function be(r={}){let[i,e]=_e({isAuthenticated:!1,isLoading:!0,isInitialized:!1,tokens:null,error:null}),t=q.getInstance(),n=$(async()=>{console.log("\u{1F535} [useSession] initialize() CALLED"),console.log("\u{1F50D} [useSession] options received:",{autoRestore:r.autoRestore,enableLogging:r.enableLogging,apiEndpointAdmin:r.apiEndpointAdmin,apiKeyEndpointAdmin:r.apiKeyEndpointAdmin});try{e(o=>({...o,isLoading:!0,error:null}));let c={autoRestore:r.autoRestore??!0,enableLogging:r.enableLogging??!1,showNotification:r.showNotification,translateFn:r.translateFn,apiEndpointAdmin:r.apiEndpointAdmin,apiKeyEndpointAdmin:r.apiKeyEndpointAdmin,publicApiKey:r.publicApiKey,env:r.env||"stg",onSessionExpired:()=>{e(o=>({...o,isAuthenticated:!1,tokens:null,error:"Session expired"})),r.onSessionExpired?.()},onSessionRestored:o=>{e(p=>({...p,isAuthenticated:!0,tokens:o,error:null})),r.onSessionRestored?.(o)},onLoginSuccess:o=>{e(p=>({...p,isAuthenticated:!0,tokens:o,error:null}))},onLogout:()=>{e(o=>({...o,isAuthenticated:!1,tokens:null,error:null}))}};console.log("\u{1F50D} [useSession] Calling sessionManager.initialize() with config:",c),await t.initialize(c),console.log("\u2705 [useSession] sessionManager.initialize() completed"),t.setupResponseInterceptor();let a=t.isAuthenticated(),l=t.getTokenInfo();console.log("\u{1F50D} [useSession] After initialize, isAuth:",a),console.log("\u{1F50D} [useSession] After initialize, tokenInfo:",l),e(o=>({...o,isAuthenticated:a,isInitialized:!0,isLoading:!1,tokens:l.crudifyTokens.accessToken?{accessToken:l.crudifyTokens.accessToken,refreshToken:l.crudifyTokens.refreshToken,expiresAt:l.crudifyTokens.expiresAt,refreshExpiresAt:l.crudifyTokens.refreshExpiresAt}:null}))}catch(c){let a=c instanceof Error?c.message:"Initialization failed";e(l=>({...l,isLoading:!1,isInitialized:!0,error:a}))}},[r.autoRestore,r.enableLogging,r.onSessionExpired,r.onSessionRestored]),s=$(async(c,a)=>{e(l=>({...l,isLoading:!0,error:null}));try{let l=await t.login(c,a);return l.success&&l.tokens?e(o=>({...o,isAuthenticated:!0,tokens:l.tokens,isLoading:!1,error:null})):e(o=>({...o,isAuthenticated:!1,tokens:null,isLoading:!1,error:null})),l}catch(l){let o=l instanceof Error?l.message:"Login failed",p=o.includes("INVALID_CREDENTIALS")||o.includes("Invalid email")||o.includes("Invalid password")||o.includes("credentials");return e(E=>({...E,isAuthenticated:!1,tokens:null,isLoading:!1,error:p?null:o})),{success:!1,error:o}}},[t]),d=$(async()=>{e(c=>({...c,isLoading:!0}));try{await t.logout(),e(c=>({...c,isAuthenticated:!1,tokens:null,isLoading:!1,error:null}))}catch(c){e(a=>({...a,isAuthenticated:!1,tokens:null,isLoading:!1,error:c instanceof Error?c.message:"Logout error"}))}},[t]),h=$(async()=>{try{let c=await t.refreshTokens();if(c){let a=t.getTokenInfo();e(l=>({...l,tokens:a.crudifyTokens.accessToken?{accessToken:a.crudifyTokens.accessToken,refreshToken:a.crudifyTokens.refreshToken,expiresAt:a.crudifyTokens.expiresAt,refreshExpiresAt:a.crudifyTokens.refreshExpiresAt}:null,error:null}))}else e(a=>({...a,isAuthenticated:!1,tokens:null,error:"Token refresh failed"}));return c}catch(c){return e(a=>({...a,isAuthenticated:!1,tokens:null,error:c instanceof Error?c.message:"Token refresh failed"})),!1}},[t]),S=$(()=>{e(c=>({...c,error:null}))},[]),I=$(()=>t.getTokenInfo(),[t]);J(()=>{n()},[n]),J(()=>{if(!i.isAuthenticated||!i.tokens)return;let c=me.getInstance(),a=()=>{t.updateLastActivity(),r.enableLogging&&console.log("\u{1F4CD} User navigating - activity updated")},l=c.subscribe(a);window.addEventListener("popstate",a);let o=()=>{let C=t.getTokenInfo().crudifyTokens.expiresIn||0;return C<300*1e3?30*1e3:C<1800*1e3?60*1e3:120*1e3},p,E=()=>{let k=o();p=setTimeout(async()=>{if(t.isRefreshing()){r.enableLogging&&console.log("\u23F8\uFE0F Refresh in progress, rescheduling check"),E();return}let C=t.getTokenInfo(),b=C.crudifyTokens.expiresIn||0,z=(C.crudifyTokens.expiresAt||0)-(Date.now()-b),v=z*.5;if(b>0&&b<=v){let B=Math.round(b/z*100);if(r.enableLogging&&console.log(`\u{1F504} Token at ${B}% of TTL (${Math.round(b/6e4)}min remaining), refreshing...`),e(F=>({...F,isLoading:!0})),await t.refreshTokens()){let F=t.getTokenInfo();e(ne=>({...ne,isLoading:!1,tokens:F.crudifyTokens.accessToken?{accessToken:F.crudifyTokens.accessToken,refreshToken:F.crudifyTokens.refreshToken,expiresAt:F.crudifyTokens.expiresAt,refreshExpiresAt:F.crudifyTokens.refreshExpiresAt}:null}))}else e(F=>({...F,isLoading:!1,isAuthenticated:!1,tokens:null}))}let V=t.getTimeSinceLastActivity(),H=1800*1e3;V>H?(r.enableLogging&&console.log("\u23F1\uFE0F Inactivity timeout (30min) - logging out"),await d()):E()},k)};return E(),()=>{clearTimeout(p),window.removeEventListener("popstate",a),l()}},[i.isAuthenticated,i.tokens,t,r.enableLogging,d]),J(()=>{let c=K.subscribe(async a=>{if(r.enableLogging&&console.log(`\u{1F4E2} useSession: Received auth event: ${a.type}`),a.type==="TOKEN_EXPIRED"){if(t.isRefreshing()){r.enableLogging&&console.log("\u23F8\uFE0F Refresh already in progress, skipping TOKEN_EXPIRED handler");return}r.enableLogging&&console.log("\u{1F504} Token expired, attempting refresh..."),e(l=>({...l,isLoading:!0}));try{if(await t.refreshTokens()){r.enableLogging&&console.log("\u2705 Token refreshed successfully");let o=t.getTokenInfo();e(p=>({...p,isLoading:!1,tokens:o.crudifyTokens.accessToken?{accessToken:o.crudifyTokens.accessToken,refreshToken:o.crudifyTokens.refreshToken,expiresAt:o.crudifyTokens.expiresAt,refreshExpiresAt:o.crudifyTokens.refreshExpiresAt}:null}))}else r.enableLogging&&console.log("\u274C Token refresh failed, session expired"),K.emit("SESSION_EXPIRED",{message:"Failed to refresh token after detecting expiration",source:"useSession.TOKEN_EXPIRED handler"})}catch(l){r.enableLogging&&console.error("\u274C Error during token refresh:",l),K.emit("SESSION_EXPIRED",{message:l instanceof Error?l.message:"Unknown error during refresh",source:"useSession.TOKEN_EXPIRED handler (error)"})}}(a.type==="SESSION_EXPIRED"||a.type==="TOKEN_REFRESH_FAILED")&&(r.enableLogging&&console.log(`\u{1F534} Session expired (${a.type}), logging out...`),e(l=>({...l,isAuthenticated:!1,tokens:null,isLoading:!1,error:a.details?.message||"Session expired"})),r.onSessionExpired?.())});return()=>c()},[r.enableLogging,r.onSessionExpired,t]),J(()=>{let c=A.subscribeToChanges(a=>{a?(r.enableLogging&&console.log("\u{1F504} Tokens updated in another tab"),e(l=>({...l,tokens:a,isAuthenticated:!0}))):(r.enableLogging&&console.log("\u{1F504} Logout detected in another tab"),e(l=>({...l,isAuthenticated:!1,tokens:null})),K.emit("SESSION_EXPIRED",{message:"Sesi\xF3n cerrada en otra pesta\xF1a",source:"CrossTabSync"}))});return()=>c()},[r.enableLogging]);let m=$(()=>{t.updateLastActivity()},[t]);return{...i,login:s,logout:d,refreshTokens:h,clearError:S,getTokenInfo:I,updateActivity:m,isExpiringSoon:i.tokens?i.tokens.expiresAt-Date.now()<300*1e3:!1,expiresIn:i.tokens?Math.max(0,i.tokens.expiresAt-Date.now()):0,refreshExpiresIn:i.tokens?Math.max(0,i.tokens.refreshExpiresAt-Date.now()):0}}import{useState as ke,createContext as Ve,useContext as Be,useCallback as j,useEffect as Xe}from"react";import{Snackbar as Ye,Alert as Ze,Box as We,Portal as qe}from"@mui/material";import{v4 as Je}from"uuid";import je from"dompurify";import{jsx as _,jsxs as ii}from"react/jsx-runtime";var xe=Ve(null),Qe=r=>je.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}),le=({children:r,maxNotifications:i=5,defaultAutoHideDuration:e=6e3,position:t={vertical:"top",horizontal:"right"},enabled:n=!1,allowHtml:s=!1})=>{let[d,h]=ke([]),S=j((a,l="info",o)=>{if(!n)return"";if(!a||typeof a!="string")return console.warn("\u26A0\uFE0F GlobalNotificationProvider: Invalid message provided"),"";a.length>1e3&&(console.warn("\u26A0\uFE0F GlobalNotificationProvider: Message too long, truncating"),a=a.substring(0,1e3)+"...");let p=Je(),E={id:p,message:a,severity:l,autoHideDuration:o?.autoHideDuration??e,persistent:o?.persistent??!1,allowHtml:o?.allowHtml??s};return h(k=>[...k.length>=i?k.slice(-(i-1)):k,E]),p},[i,e,n,s]),I=j(a=>{h(l=>l.filter(o=>o.id!==a))},[]),m=j(()=>{h([])},[]),c={showNotification:S,hideNotification:I,clearAllNotifications:m};return ii(xe.Provider,{value:c,children:[r,n&&_(qe,{children:_(We,{sx:{position:"fixed",zIndex:9999,[t.vertical]:(t.vertical==="top",24),[t.horizontal]:t.horizontal==="right"||t.horizontal==="left"?24:"50%",...t.horizontal==="center"&&{transform:"translateX(-50%)"},display:"flex",flexDirection:t.vertical==="top"?"column":"column-reverse",gap:1,maxWidth:"400px",width:"auto"},children:d.map(a=>_(ei,{notification:a,onClose:()=>I(a.id)},a.id))})})]})},ei=({notification:r,onClose:i})=>{let[e,t]=ke(!0),n=j((s,d)=>{d!=="clickaway"&&(t(!1),setTimeout(i,300))},[i]);return Xe(()=>{if(!r.persistent&&r.autoHideDuration){let s=setTimeout(()=>{n()},r.autoHideDuration);return()=>clearTimeout(s)}},[r.autoHideDuration,r.persistent,n]),_(Ye,{open:e,onClose:n,sx:{position:"relative","& .MuiSnackbarContent-root":{minWidth:"auto"}},TransitionProps:{enter:!0,exit:!0},children:_(Ze,{variant:"filled",severity:r.severity,onClose:n,sx:{width:"100%",minWidth:"280px",maxWidth:"400px",wordBreak:"break-word"},children:r.allowHtml?_("span",{dangerouslySetInnerHTML:{__html:Qe(r.message)}}):_("span",{children:r.message})})})},Se=()=>{let r=Be(xe);if(!r)throw new Error("useGlobalNotification debe ser usado dentro de un GlobalNotificationProvider");return r};import ti,{createContext as ri,useContext as ni,useMemo as ce}from"react";import{Fragment as si,jsx as w,jsxs as U}from"react/jsx-runtime";var Ne=ri(void 0);function Pe({children:r,options:i={},config:e,showNotifications:t=!1,notificationOptions:n={}}){let s;try{let{showNotification:o}=Se();s=o}catch{}let d={};try{let o=Ie();o.isInitialized&&o.adminCredentials&&(d=o.adminCredentials)}catch{}let h=ce(()=>{let o=se({publicApiKey:e?.publicApiKey,env:e?.env,enableDebug:i?.enableLogging});return{publicApiKey:o.publicApiKey,env:o.env||"prod"}},[e,i?.enableLogging]),S=ti.useMemo(()=>({...i,showNotification:s,apiEndpointAdmin:d.apiEndpointAdmin,apiKeyEndpointAdmin:d.apiKeyEndpointAdmin,publicApiKey:h.publicApiKey,env:h.env,onSessionExpired:()=>{i.onSessionExpired?.()}}),[i,s,d.apiEndpointAdmin,d.apiKeyEndpointAdmin,h]),I=be(S),m=ce(()=>{let o=se({publicApiKey:e?.publicApiKey,env:e?.env,appName:e?.appName,logo:e?.logo,loginActions:e?.loginActions,enableDebug:i?.enableLogging});return{publicApiKey:o.publicApiKey,env:o.env,appName:o.appName,loginActions:o.loginActions,logo:o.logo}},[e,i?.enableLogging]),c=ce(()=>{if(!I.tokens?.accessToken||!I.isAuthenticated)return null;try{let o=Ee(I.tokens.accessToken);if(o&&o.sub&&o.email&&o.subscriber){let p={_id:o.sub,email:o.email,subscriberKey:o.subscriber};return Object.keys(o).forEach(E=>{["sub","email","subscriber"].includes(E)||(p[E]=o[E])}),p}}catch(o){console.error("Error decoding JWT token for sessionData:",o)}return null},[I.tokens?.accessToken,I.isAuthenticated]),a={...I,sessionData:c,config:m},l={enabled:t,maxNotifications:n.maxNotifications||5,defaultAutoHideDuration:n.defaultAutoHideDuration||6e3,position:n.position||{vertical:"top",horizontal:"right"}};return w(Ne.Provider,{value:a,children:r})}function et(r){let i={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?w(Ae,{config:{publicApiKey:r.config.publicApiKey,env:r.config.env||"prod",appName:r.config.appName,loginActions:r.config.loginActions,logo:r.config.logo},children:w(le,{...i,children:w(Pe,{...r})})}):w(le,{...i,children:w(Pe,{...r})})}function oi(){let r=ni(Ne);if(r===void 0)throw new Error("useSessionContext must be used within a SessionProvider");return r}function it(){let r=oi();return r.isInitialized?U("div",{style:{padding:"10px",margin:"10px",border:"1px solid #ccc",borderRadius:"4px",fontSize:"12px",fontFamily:"monospace"},children:[w("h4",{children:"Session Debug Info"}),U("div",{children:[w("strong",{children:"Authenticated:"})," ",r.isAuthenticated?"Yes":"No"]}),U("div",{children:[w("strong",{children:"Loading:"})," ",r.isLoading?"Yes":"No"]}),U("div",{children:[w("strong",{children:"Error:"})," ",r.error||"None"]}),r.tokens&&U(si,{children:[U("div",{children:[w("strong",{children:"Access Token:"})," ",r.tokens.accessToken.substring(0,20),"..."]}),U("div",{children:[w("strong",{children:"Refresh Token:"})," ",r.tokens.refreshToken.substring(0,20),"..."]}),U("div",{children:[w("strong",{children:"Access Expires In:"})," ",Math.round(r.expiresIn/1e3/60)," minutes"]}),U("div",{children:[w("strong",{children:"Refresh Expires In:"})," ",Math.round(r.refreshExpiresIn/1e3/60/60)," hours"]}),U("div",{children:[w("strong",{children:"Expiring Soon:"})," ",r.isExpiringSoon?"Yes":"No"]})]})]}):w("div",{children:"Session not initialized"})}import{useState as Q,useEffect as we,useCallback as Re,useRef as ee}from"react";import ai from"@nocios/crudify-browser";var at=(r={})=>{let{autoFetch:i=!0,retryOnError:e=!1,maxRetries:t=3}=r,[n,s]=Q(null),[d,h]=Q(!1),[S,I]=Q(null),[m,c]=Q({}),a=ee(null),l=ee(!0),o=ee(0),p=ee(0),E=Re(()=>{s(null),I(null),h(!1),c({})},[]),k=Re(async()=>{let C=Te();if(!C){l.current&&(I("No user email available"),h(!1));return}a.current&&a.current.abort();let b=new AbortController;a.current=b;let P=++o.current;try{l.current&&(h(!0),I(null));let z=await ai.readItems("users",{filter:{email:C},pagination:{limit:1}});if(P===o.current&&l.current&&!b.signal.aborted)if(z.success&&z.data&&z.data.length>0){let v=z.data[0];s(v);let V={fullProfile:v,totalFields:Object.keys(v).length,displayData:{id:v.id,email:v.email,username:v.username,firstName:v.firstName,lastName:v.lastName,fullName:v.fullName||`${v.firstName||""} ${v.lastName||""}`.trim(),role:v.role,permissions:v.permissions||[],isActive:v.isActive,lastLogin:v.lastLogin,createdAt:v.createdAt,updatedAt:v.updatedAt,...Object.keys(v).filter(H=>!["id","email","username","firstName","lastName","fullName","role","permissions","isActive","lastLogin","createdAt","updatedAt"].includes(H)).reduce((H,B)=>({...H,[B]:v[B]}),{})}};c(V),I(null),p.current=0}else I("User profile not found"),s(null),c({})}catch(z){if(P===o.current&&l.current){let v=z;if(v.name==="AbortError")return;e&&p.current<t&&(v.message?.includes("Network Error")||v.message?.includes("Failed to fetch"))?(p.current++,setTimeout(()=>{l.current&&k()},1e3*p.current)):(I("Failed to load user profile"),s(null),c({}))}}finally{P===o.current&&l.current&&h(!1),a.current===b&&(a.current=null)}},[e,t]);return we(()=>{i&&k()},[i,k]),we(()=>(l.current=!0,()=>{l.current=!1,a.current&&(a.current.abort(),a.current=null)}),[]),{userProfile:n,loading:d,error:S,extendedData:m,refreshProfile:k,clearProfile:E}};import{useState as ue,useEffect as li,useCallback as ie,useRef as ci}from"react";import ui from"@nocios/crudify-browser";var dt=(r,i={})=>{let{autoFetch:e=!0,onSuccess:t,onError:n}=i,{prefix:s,padding:d=0,separator:h=""}=r,[S,I]=ue(""),[m,c]=ue(!1),[a,l]=ue(null),o=ci(!1),p=ie(b=>{let P=String(b).padStart(d,"0");return`${s}${h}${P}`},[s,d,h]),E=ie(async()=>{c(!0),l(null);try{let b=await ui.getNextSequence(s);if(b.success&&b.data?.value){let P=p(b.data.value);I(P),t?.(P)}else{let P=b.errors?._error?.[0]||"Failed to generate code";l(P),n?.(P)}}catch(b){let P=b instanceof Error?b.message:"Unknown error";l(P),n?.(P)}finally{c(!1)}},[s,p,t,n]),k=ie(async()=>{await E()},[E]),C=ie(()=>{l(null)},[]);return li(()=>{e&&!S&&!o.current&&(o.current=!0,E())},[e,S,E]),{value:S,loading:m,error:a,regenerate:k,clearError:C}};import de from"@nocios/crudify-browser";var fe=class r{constructor(){this.state={status:"UNINITIALIZED",priority:null,publicApiKey:null,env:null,error:null,initializedBy:null};this.initializationPromise=null;this.highPriorityInitializerPresent=!1;this.waitingForHighPriority=new Set;this.HIGH_PRIORITY_WAIT_TIMEOUT=100}static getInstance(){return r.instance||(r.instance=new r),r.instance}registerHighPriorityInitializer(){this.highPriorityInitializerPresent=!0}isHighPriorityInitializerPresent(){return this.highPriorityInitializerPresent}getState(){return{...this.state}}async initialize(i){let{priority:e,publicApiKey:t,env:n,enableLogging:s,requestedBy:d}=i;if(this.state.status==="INITIALIZED"){this.state.publicApiKey!==t&&console.warn(`[CrudifyInitialization] ${d} 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&&console.log(`[CrudifyInitialization] ${d} waiting for ongoing initialization...`),this.initializationPromise;if(e==="LOW"&&this.highPriorityInitializerPresent&&this.state.status==="UNINITIALIZED"){if(s&&console.log(`[CrudifyInitialization] ${d} (LOW priority) waiting for HIGH priority initializer...`),this.waitingForHighPriority.add(d),await this.waitForHighPriorityOrTimeout(s),this.waitingForHighPriority.delete(d),this.getState().status==="INITIALIZED"){s&&console.log(`[CrudifyInitialization] ${d} found initialization completed by HIGH priority`);return}s&&console.warn(`[CrudifyInitialization] ${d} timeout waiting for HIGH priority, initializing with LOW priority`)}e==="HIGH"&&this.state.status==="INITIALIZING"&&this.state.priority==="LOW"&&(console.warn(`[CrudifyInitialization] HIGH priority request from ${d} interrupting LOW priority initialization by ${this.state.initializedBy}`),this.state.status="UNINITIALIZED",this.initializationPromise=null),s&&console.log(`[CrudifyInitialization] ${d} starting initialization (${e} priority)...`),this.state.status="INITIALIZING",this.state.priority=e,this.state.initializedBy=d,this.initializationPromise=this.performInitialization(t,n,s);try{await this.initializationPromise,this.state.status="INITIALIZED",this.state.publicApiKey=t,this.state.env=n,this.state.error=null,s&&console.log(`[CrudifyInitialization] \u2705 Successfully initialized by ${d} (${e} priority)`)}catch(h){throw this.state.status="ERROR",this.state.error=h instanceof Error?h:new Error(String(h)),this.initializationPromise=null,console.error(`[CrudifyInitialization] \u274C Initialization failed for ${d}:`,h),h}}async waitForHighPriorityOrTimeout(i){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),i&&console.log(`[CrudifyInitialization] Timeout waiting for HIGH priority (${this.HIGH_PRIORITY_WAIT_TIMEOUT}ms)`),e())},10)})}async performInitialization(i,e,t){let n=de.getTokenData();if(n&&n.endpoint){t&&console.log("[CrudifyInitialization] SDK already initialized externally");return}de.config(e);let s=t?"debug":"none",d=await de.init(i,s);if(d.success===!1)throw new Error(`Crudify initialization failed: ${JSON.stringify(d.errors||"Unknown error")}`);d.apiEndpointAdmin&&d.apiKeyEndpointAdmin&&Z.notifyCredentialsReady({apiUrl:d.apiEndpointAdmin,apiKey:d.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}}},te=fe.getInstance();import{useState as Ce,useCallback as D,useRef as di,useMemo as re}from"react";import ge from"@nocios/crudify-browser";var Le=()=>`file_${Date.now()}_${Math.random().toString(36).substring(2,9)}`,fi=r=>{let i=r.lastIndexOf("."),e=i>0?r.substring(i):"",t=Date.now(),n=Math.random().toString(36).substring(2,8);return`${t}_${n}${e}`},Tt=(r={})=>{let{acceptedTypes:i,maxFileSize:e=10*1024*1024,maxFiles:t,minFiles:n=0,visibility:s="private",onUploadComplete:d,onUploadError:h,onFileRemoved:S,onFilesChange:I}=r,[m,c]=Ce([]),[a,l]=Ce(!1),o=di(new Map),p=D(()=>{l(!0)},[]),E=D((u,y)=>{c(g=>g.map(T=>T.id===u?{...T,...y}:T))},[]),k=D(u=>{I?.(u)},[I]),C=D(u=>i&&i.length>0&&!i.includes(u.type)?{valid:!1,error:`File type not allowed: ${u.type}`}:u.size>e?{valid:!1,error:`File exceeds maximum size of ${(e/1048576).toFixed(1)}MB`}:{valid:!0},[i,e]),b=D(async(u,y)=>{try{if(!te.isInitialized())throw new Error("Crudify is not initialized. Please wait for the application to finish loading.");let g=fi(y.name),N=await ge.generateSignedUrl({fileName:g,contentType:y.type,visibility:s});if(!N.success||!N.data)throw new Error("Failed to get upload URL");let{uploadUrl:T,s3Key:x,publicUrl:M}=N.data;if(!T||!x)throw new Error("Incomplete signed URL response");let ye=x.indexOf("/"),Ke=ye>0?x.substring(ye+1):x;E(u.id,{status:"uploading",progress:0}),await new Promise((oe,G)=>{let L=new XMLHttpRequest;L.upload.addEventListener("progress",O=>{if(O.lengthComputable){let Oe=Math.round(O.loaded/O.total*100);E(u.id,{progress:Oe})}}),L.addEventListener("load",()=>{L.status>=200&&L.status<300?oe():G(new Error(`Upload failed with status ${L.status}`))}),L.addEventListener("error",()=>{G(new Error("Network error during upload"))}),L.addEventListener("abort",()=>{G(new Error("Upload cancelled"))}),L.open("PUT",T),L.setRequestHeader("Content-Type",y.type),L.send(y)});let Ue={status:"completed",progress:100,filePath:Ke,visibility:s,publicUrl:s==="public"?M:void 0,file:void 0};c(oe=>{let G=oe.map(O=>O.id===u.id?{...O,...Ue}:O);k(G);let L=G.find(O=>O.id===u.id);return L&&d?.(L),G})}catch(g){let N=g instanceof Error?g.message:"Unknown error";E(u.id,{status:"error",progress:0,errorMessage:N}),c(T=>{let x=T.find(M=>M.id===u.id);return x&&h?.(x,N),T})}},[E,d,h,s]),P=D(async u=>{let y=Array.from(u);if(t!==void 0){let T=m.filter(M=>M.status!=="error").length,x=t-T;if(x<=0){console.warn(`File limit of ${t} already reached`);return}y.length>x&&(y.splice(x),console.warn(`Only ${x} files will be added to not exceed limit`))}let g=[];for(let T of y){let x=C(T),M={id:Le(),name:T.name,size:T.size,contentType:T.type,status:x.valid?"pending":"error",progress:0,createdAt:Date.now(),file:x.valid?T:void 0,errorMessage:x.error};g.push(M)}c(T=>{let x=[...T,...g];return k(x),x});let N=g.filter(T=>T.status==="pending"&&T.file);for(let T of N)if(T.file){let x=b(T,T.file);o.current.set(T.id,x),x.finally(()=>{o.current.delete(T.id)})}},[m,t,C,b,k]),z=D(async u=>{let y=m.find(g=>g.id===u);if(!y)return!1;E(u,{status:"removing"});try{if(y.filePath){if(!te.isInitialized())throw new Error("Crudify is not initialized. Please wait for the application to finish loading.");if(!(await ge.disableFile({filePath:y.filePath})).success)throw new Error("Failed to remove file from server")}return c(g=>{let N=g.filter(T=>T.id!==u);return k(N),N}),S?.(y),!0}catch(g){return E(u,{status:y.filePath?"completed":"error",errorMessage:g instanceof Error?g.message:"Error removing file"}),!1}},[m,E,k,S]),v=D(()=>{c([]),k([])},[k]),V=D(async u=>{let y=m.find(N=>N.id===u);if(!y||y.status!=="error"||!y.file){console.warn("Cannot retry: file not found or no original file");return}E(u,{status:"pending",progress:0,errorMessage:void 0});let g=b(y,y.file);o.current.set(u,g),g.finally(()=>{o.current.delete(u)})},[m,E,b]),H=D(async()=>{let u=Array.from(o.current.values());u.length>0&&await Promise.allSettled(u)},[]),B=D(u=>{let y=u.map(g=>{let N=g.filePath.startsWith("public/")?"public":"private";return{id:Le(),name:g.name,size:g.size||0,contentType:g.contentType||"application/octet-stream",status:"completed",progress:100,filePath:g.filePath,visibility:N,createdAt:Date.now()}});c(y),k(y)},[k]),pe=D(async u=>{let y=m.find(g=>g.id===u);if(!y||!y.filePath)return null;if(y.visibility==="public"&&y.publicUrl)return y.publicUrl;try{if(!te.isInitialized())return null;let g=await ge.getFileUrl({filePath:y.filePath,expiresIn:3600});return g.success&&g.data?.url?g.data.url:null}catch{return null}},[m]),F=re(()=>m.some(u=>u.status==="uploading"||u.status==="pending"),[m]),ne=re(()=>m.filter(u=>u.status==="uploading"||u.status==="pending").length,[m]),De=re(()=>m.filter(u=>u.status==="completed"&&u.filePath).map(u=>u.filePath),[m]),{isValid:ze,validationError:Fe}=re(()=>{let u=m.filter(g=>g.status==="completed").length;return u<n?{isValid:!1,validationError:n===1?"At least one file is required":`At least ${n} files are required`}:t!==void 0&&u>t?{isValid:!1,validationError:`Maximum ${t} files allowed`}:m.some(g=>g.status==="error")?{isValid:!1,validationError:"Some files have errors"}:{isValid:!0,validationError:null}},[m,n,t]);return{files:m,isUploading:F,pendingCount:ne,addFiles:P,removeFile:z,clearFiles:v,retryUpload:V,isValid:ze,validationError:Fe,waitForUploads:H,completedFilePaths:De,initializeFiles:B,isTouched:a,markAsTouched:p,getPreviewUrl:pe}};export{Z as a,Ae as b,Ie as c,A as d,q as e,be as f,le as g,Se as h,et as i,oi as j,it as k,at as l,dt as m,fe as n,te as o,Tt as p};