@nocios/crudify-ui 4.4.34 → 4.4.38
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{CrudiaFileField-D5zDp_Y1.d.mts → CrudiaFileField-8ArxOo5y.d.mts} +13 -13
- package/dist/{CrudiaFileField-CXyBfgOd.d.ts → CrudiaFileField-DA-kEoTA.d.ts} +13 -13
- package/dist/{chunk-SOGHYUM2.mjs → chunk-GFSDL6HT.mjs} +1 -1
- package/dist/{chunk-3OZPBGVW.mjs → chunk-GWQVH4G4.mjs} +1 -1
- package/dist/{chunk-5T4X67GW.js → chunk-J4K6MZHY.js} +1 -1
- package/dist/{chunk-WIWNROEA.js → chunk-PDFLD5FF.js} +1 -1
- package/dist/{chunk-VHWM5MV6.js → chunk-URTGOZMJ.js} +1 -1
- package/dist/{chunk-R4PHVWCE.mjs → chunk-YRS5XYAB.mjs} +1 -1
- package/dist/components.d.mts +1 -1
- package/dist/components.d.ts +1 -1
- package/dist/components.js +1 -1
- package/dist/components.mjs +1 -1
- package/dist/hooks.d.mts +1 -1
- package/dist/hooks.d.ts +1 -1
- package/dist/hooks.js +1 -1
- package/dist/hooks.mjs +1 -1
- package/dist/{index-BicpdTC_.d.ts → index-BVT7flO5.d.ts} +57 -49
- package/dist/{index-wi46iw-x.d.mts → index-CQnAzvOE.d.mts} +57 -49
- package/dist/index.d.mts +4 -4
- package/dist/index.d.ts +4 -4
- package/dist/index.js +2 -2
- package/dist/index.mjs +1 -1
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
import{b as oe,d as ye,h as K,i as he,j as me,k as ve}from"./chunk-6GPSBDW6.mjs";import{createContext as He,useContext as Me,useEffect as Ge,useState as B}from"react";import X from"@nocios/crudify-browser";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(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}},Te=se.getInstance();import{jsx as $e}from"react/jsx-runtime";var Ee=He(void 0),Ae=({config:r,children:i})=>{let[e,t]=B(!0),[n,s]=B(null),[f,h]=B(!1),[S,I]=B(""),[m,c]=B();Ge(()=>{if(!r.publicApiKey){s("No publicApiKey provided"),t(!1),h(!1);return}let l=`${r.publicApiKey}-${r.env}`;if(l===S&&f){t(!1);return}(async()=>{t(!0),s(null),h(!1);try{X.config(r.env||"prod");let p=await X.init(r.publicApiKey,"none");if(c(p),typeof X.transaction=="function"&&typeof X.login=="function")h(!0),I(l),p.apiEndpointAdmin&&p.apiKeyEndpointAdmin&&Te.notifyCredentialsReady({apiUrl:p.apiEndpointAdmin,apiKey:p.apiKeyEndpointAdmin});else throw new Error("Crudify methods not properly initialized")}catch(p){let v=p instanceof Error?p.message:"Failed to initialize Crudify";console.error("[CrudifyProvider] Initialization error:",p),s(v),h(!1)}finally{t(!1)}})()},[r.publicApiKey,r.env,S,f]);let a={crudify:f?X:null,isLoading:e,error:n,isInitialized:f,adminCredentials:m};return $e(Ee.Provider,{value:a,children:i})},Ie=()=>{let r=Me(Ee);if(r===void 0)throw new Error("useCrudify must be used within a CrudifyProvider");return r};import Z from"crypto-js";var d=class d{static setStorageType(i){d.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 Z.SHA256(i).toString()}static getEncryptionKey(){if(d.encryptionKey)return d.encryptionKey;let i=window.localStorage;if(!i)return d.encryptionKey=d.generateEncryptionKey(),d.encryptionKey;try{let e=i.getItem(d.ENCRYPTION_KEY_STORAGE);return(!e||e.length<32)&&(e=d.generateEncryptionKey(),i.setItem(d.ENCRYPTION_KEY_STORAGE,e)),d.encryptionKey=e,e}catch{return console.warn("Crudify: Cannot persist encryption key, using temporary key"),d.encryptionKey=d.generateEncryptionKey(),d.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 d.storageType==="none"?null:d.isStorageAvailable(d.storageType)?window[d.storageType]:(console.warn(`Crudify: ${d.storageType} not available, tokens won't persist`),null)}static encrypt(i){try{let e=d.getEncryptionKey();return Z.AES.encrypt(i,e).toString()}catch(e){return console.error("Crudify: Encryption failed",e),i}}static decrypt(i){try{let e=d.getEncryptionKey();return Z.AES.decrypt(i,e).toString(Z.enc.Utf8)||i}catch(e){return console.error("Crudify: Decryption failed",e),i}}static saveTokens(i){let e=d.getStorage();if(e)try{let t={accessToken:i.accessToken,refreshToken:i.refreshToken,expiresAt:i.expiresAt,refreshExpiresAt:i.refreshExpiresAt,savedAt:Date.now()},n=d.encrypt(JSON.stringify(t));e.setItem(d.TOKEN_KEY,n),console.debug("Crudify: Tokens saved successfully")}catch(t){console.error("Crudify: Failed to save tokens",t)}}static getTokens(){let i=d.getStorage();if(!i)return null;try{let e=i.getItem(d.TOKEN_KEY);if(!e)return null;let t=d.decrypt(e),n=JSON.parse(t);return!n.accessToken||!n.refreshToken||!n.expiresAt||!n.refreshExpiresAt?(console.warn("Crudify: Incomplete token data found, clearing storage"),d.clearTokens(),null):Date.now()>=n.refreshExpiresAt?(console.info("Crudify: Refresh token expired, clearing storage"),d.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),d.clearTokens(),null}}static clearTokens(){let i=d.getStorage();if(i)try{i.removeItem(d.TOKEN_KEY),console.debug("Crudify: Tokens cleared from storage")}catch(e){console.error("Crudify: Failed to clear tokens",e)}}static rotateEncryptionKey(){try{d.clearTokens(),d.encryptionKey=null;let i=window.localStorage;i&&i.removeItem(d.ENCRYPTION_KEY_STORAGE),console.info("Crudify: Encryption key rotated successfully")}catch(i){console.error("Crudify: Failed to rotate encryption key",i)}}static hasValidTokens(){return d.getTokens()!==null}static getExpirationInfo(){let i=d.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=d.getTokens();if(!t){console.warn("Crudify: Cannot update access token, no existing tokens found");return}d.saveTokens({...t,accessToken:i,expiresAt:e})}static subscribeToChanges(i){let e=t=>{if(t.key===d.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=d.getTokens();i(n)}}};return window.addEventListener("storage",e),()=>{window.removeEventListener("storage",e)}}};d.TOKEN_KEY="crudify_tokens",d.ENCRYPTION_KEY_STORAGE="crudify_enc_key",d.encryptionKey=null,d.storageType="localStorage";var A=d;import w from"@nocios/crudify-browser";var W=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(),w.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 w.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 w.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(w.setTokens({accessToken:i.accessToken,refreshToken:i.refreshToken,expiresAt:i.expiresAt,refreshExpiresAt:i.refreshExpiresAt}),w.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 w.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 w.logout(),!1}}isAuthenticated(){return w.isLogin()||A.hasValidTokens()}getTokenInfo(){let i=w.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 w.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(){w.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=w.getTokenData();if(i&&i.endpoint){this.log("Crudify already initialized by another service"),this.crudifyInitialized=!0;return}let e=this.config.env||"stg";w.config(e);let t=this.config.publicApiKey,n=this.config.enableLogging?"debug":"none",s=await w.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(),w.logout(),this.lastActivityTime=0,this.log("Session cleared completely")}getSessionExpiredMessage(){return this.config.translateFn?ye("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 q,useCallback as $}from"react";function be(r={}){let[i,e]=_e({isAuthenticated:!1,isLoading:!0,isInitialized:!1,tokens:null,error:null}),t=W.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(v=>({...v,isAuthenticated:!1,tokens:null,isLoading:!1,error:p?null:o})),{success:!1,error:o}}},[t]),f=$(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]);q(()=>{n()},[n]),q(()=>{if(!i.isAuthenticated||!i.tokens)return;let c=he.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,v=()=>{let k=o();p=setTimeout(async()=>{if(t.isRefreshing()){r.enableLogging&&console.log("\u23F8\uFE0F Refresh in progress, rescheduling check"),v();return}let C=t.getTokenInfo(),b=C.crudifyTokens.expiresIn||0,z=(C.crudifyTokens.expiresAt||0)-(Date.now()-b),E=z*.5;if(b>0&&b<=E){let Y=Math.round(b/z*100);if(r.enableLogging&&console.log(`\u{1F504} Token at ${Y}% of TTL (${Math.round(b/6e4)}min remaining), refreshing...`),e(F=>({...F,isLoading:!0})),await t.refreshTokens()){let F=t.getTokenInfo();e(re=>({...re,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 f()):v()},k)};return v(),()=>{clearTimeout(p),window.removeEventListener("popstate",a),l()}},[i.isAuthenticated,i.tokens,t,r.enableLogging,f]),q(()=>{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]),q(()=>{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:f,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 Ye,useCallback as J,useEffect as Be}from"react";import{Snackbar as Xe,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}),ae=({children:r,maxNotifications:i=5,defaultAutoHideDuration:e=6e3,position:t={vertical:"top",horizontal:"right"},enabled:n=!1,allowHtml:s=!1})=>{let[f,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(),v={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,v]),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:f.map(a=>_(ei,{notification:a,onClose:()=>I(a.id)},a.id))})})]})},ei=({notification:r,onClose:i})=>{let[e,t]=ke(!0),n=J((s,f)=>{f!=="clickaway"&&(t(!1),setTimeout(i,300))},[i]);return Be(()=>{if(!r.persistent&&r.autoHideDuration){let s=setTimeout(()=>{n()},r.autoHideDuration);return()=>clearTimeout(s)}},[r.autoHideDuration,r.persistent,n]),_(Xe,{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=Ye(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 le}from"react";import{Fragment as si,jsx as R,jsxs as O}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 f={};try{let o=Ie();o.isInitialized&&o.adminCredentials&&(f=o.adminCredentials)}catch{}let h=le(()=>{let o=oe({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:f.apiEndpointAdmin,apiKeyEndpointAdmin:f.apiKeyEndpointAdmin,publicApiKey:h.publicApiKey,env:h.env,onSessionExpired:()=>{i.onSessionExpired?.()}}),[i,s,f.apiEndpointAdmin,f.apiKeyEndpointAdmin,h]),I=be(S),m=le(()=>{let o=oe({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=le(()=>{if(!I.tokens?.accessToken||!I.isAuthenticated)return null;try{let o=me(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(v=>{["sub","email","subscriber"].includes(v)||(p[v]=o[v])}),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 R(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?R(Ae,{config:{publicApiKey:r.config.publicApiKey,env:r.config.env||"prod",appName:r.config.appName,loginActions:r.config.loginActions,logo:r.config.logo},children:R(ae,{...i,children:R(Pe,{...r})})}):R(ae,{...i,children:R(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?O("div",{style:{padding:"10px",margin:"10px",border:"1px solid #ccc",borderRadius:"4px",fontSize:"12px",fontFamily:"monospace"},children:[R("h4",{children:"Session Debug Info"}),O("div",{children:[R("strong",{children:"Authenticated:"})," ",r.isAuthenticated?"Yes":"No"]}),O("div",{children:[R("strong",{children:"Loading:"})," ",r.isLoading?"Yes":"No"]}),O("div",{children:[R("strong",{children:"Error:"})," ",r.error||"None"]}),r.tokens&&O(si,{children:[O("div",{children:[R("strong",{children:"Access Token:"})," ",r.tokens.accessToken.substring(0,20),"..."]}),O("div",{children:[R("strong",{children:"Refresh Token:"})," ",r.tokens.refreshToken.substring(0,20),"..."]}),O("div",{children:[R("strong",{children:"Access Expires In:"})," ",Math.round(r.expiresIn/1e3/60)," minutes"]}),O("div",{children:[R("strong",{children:"Refresh Expires In:"})," ",Math.round(r.refreshExpiresIn/1e3/60/60)," hours"]}),O("div",{children:[R("strong",{children:"Expiring Soon:"})," ",r.isExpiringSoon?"Yes":"No"]})]})]}):R("div",{children:"Session not initialized"})}import{useState as j,useEffect as Re,useCallback as we,useRef as Q}from"react";import ai from"@nocios/crudify-browser";var at=(r={})=>{let{autoFetch:i=!0,retryOnError:e=!1,maxRetries:t=3}=r,[n,s]=j(null),[f,h]=j(!1),[S,I]=j(null),[m,c]=j({}),a=Q(null),l=Q(!0),o=Q(0),p=Q(0),v=we(()=>{s(null),I(null),h(!1),c({})},[]),k=we(async()=>{let C=ve();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 E=z.data[0];s(E);let V={fullProfile:E,totalFields:Object.keys(E).length,displayData:{id:E.id,email:E.email,username:E.username,firstName:E.firstName,lastName:E.lastName,fullName:E.fullName||`${E.firstName||""} ${E.lastName||""}`.trim(),role:E.role,permissions:E.permissions||[],isActive:E.isActive,lastLogin:E.lastLogin,createdAt:E.createdAt,updatedAt:E.updatedAt,...Object.keys(E).filter(H=>!["id","email","username","firstName","lastName","fullName","role","permissions","isActive","lastLogin","createdAt","updatedAt"].includes(H)).reduce((H,Y)=>({...H,[Y]:E[Y]}),{})}};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 E=z;if(E.name==="AbortError")return;e&&p.current<t&&(E.message?.includes("Network Error")||E.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 Re(()=>{i&&k()},[i,k]),Re(()=>(l.current=!0,()=>{l.current=!1,a.current&&(a.current.abort(),a.current=null)}),[]),{userProfile:n,loading:f,error:S,extendedData:m,refreshProfile:k,clearProfile:v}};import{useState as ce,useEffect as li,useCallback as ee,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:f=0,separator:h=""}=r,[S,I]=ce(""),[m,c]=ce(!1),[a,l]=ce(null),o=ci(!1),p=ee(b=>{let P=String(b).padStart(f,"0");return`${s}${h}${P}`},[s,f,h]),v=ee(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=ee(async()=>{await v()},[v]),C=ee(()=>{l(null)},[]);return li(()=>{e&&!S&&!o.current&&(o.current=!0,v())},[e,S,v]),{value:S,loading:m,error:a,regenerate:k,clearError:C}};import ue from"@nocios/crudify-browser";var de=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:f}=i;if(this.state.status==="INITIALIZED"){this.state.publicApiKey!==t&&console.warn(`[CrudifyInitialization] ${f} 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] ${f} waiting for ongoing initialization...`),this.initializationPromise;if(e==="LOW"&&this.highPriorityInitializerPresent&&this.state.status==="UNINITIALIZED"){if(s&&console.log(`[CrudifyInitialization] ${f} (LOW priority) waiting for HIGH priority initializer...`),this.waitingForHighPriority.add(f),await this.waitForHighPriorityOrTimeout(s),this.waitingForHighPriority.delete(f),this.getState().status==="INITIALIZED"){s&&console.log(`[CrudifyInitialization] ${f} found initialization completed by HIGH priority`);return}s&&console.warn(`[CrudifyInitialization] ${f} 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 ${f} interrupting LOW priority initialization by ${this.state.initializedBy}`),this.state.status="UNINITIALIZED",this.initializationPromise=null),s&&console.log(`[CrudifyInitialization] ${f} starting initialization (${e} priority)...`),this.state.status="INITIALIZING",this.state.priority=e,this.state.initializedBy=f,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 ${f} (${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 ${f}:`,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=ue.getTokenData();if(n&&n.endpoint){t&&console.log("[CrudifyInitialization] SDK already initialized externally");return}ue.config(e);let s=t?"debug":"none",f=await ue.init(i,s);if(f.success===!1)throw new Error(`Crudify initialization failed: ${JSON.stringify(f.errors||"Unknown error")}`)}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=de.getInstance();import{useState as Ce,useCallback as D,useRef as di,useMemo as te}from"react";import fe 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}`},vt=(r={})=>{let{acceptedTypes:i,maxFileSize:e=10*1024*1024,maxFiles:t,minFiles:n=0,visibility:s="private",onUploadComplete:f,onUploadError:h,onFileRemoved:S,onFilesChange:I}=r,[m,c]=Ce([]),[a,l]=Ce(!1),o=di(new Map),p=D(()=>{l(!0)},[]),v=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:`Tipo de archivo no permitido: ${u.type}`}:u.size>e?{valid:!1,error:`El archivo excede el tama\xF1o m\xE1ximo de ${(e/1048576).toFixed(1)}MB`}:{valid:!0},[i,e]),b=D(async(u,y)=>{try{if(!ie.isInitialized())throw new Error("Crudify no est\xE1 inicializado. Por favor espere a que la aplicaci\xF3n termine de cargar.");let g=fi(y.name),N=await fe.generateSignedUrl({fileName:g,contentType:y.type,visibility:s});if(!N.success||!N.data)throw new Error("No se pudo obtener URL de upload");let{uploadUrl:T,s3Key:x,publicUrl:M}=N.data;if(!T||!x)throw new Error("Respuesta de signed URL incompleta");let pe=x.indexOf("/"),Ke=pe>0?x.substring(pe+1):x;v(u.id,{status:"uploading",progress:0}),await new Promise((ne,G)=>{let L=new XMLHttpRequest;L.upload.addEventListener("progress",U=>{if(U.lengthComputable){let Ue=Math.round(U.loaded/U.total*100);v(u.id,{progress:Ue})}}),L.addEventListener("load",()=>{L.status>=200&&L.status<300?ne():G(new Error(`Upload fall\xF3 con status ${L.status}`))}),L.addEventListener("error",()=>{G(new Error("Error de red durante el upload"))}),L.addEventListener("abort",()=>{G(new Error("Upload cancelado"))}),L.open("PUT",T),L.setRequestHeader("Content-Type",y.type),L.send(y)});let Oe={status:"completed",progress:100,filePath:Ke,visibility:s,publicUrl:s==="public"?M:void 0,file:void 0};c(ne=>{let G=ne.map(U=>U.id===u.id?{...U,...Oe}:U);k(G);let L=G.find(U=>U.id===u.id);return L&&f?.(L),G})}catch(g){let N=g instanceof Error?g.message:"Error desconocido";v(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})}},[v,f,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(`Ya se alcanz\xF3 el l\xEDmite de ${t} archivos`);return}y.length>x&&(y.splice(x),console.warn(`Solo se agregar\xE1n ${x} archivos para no exceder el l\xEDmite`))}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;v(u,{status:"removing"});try{if(y.filePath){if(!ie.isInitialized())throw new Error("Crudify no est\xE1 inicializado. Por favor espere a que la aplicaci\xF3n termine de cargar.");if(!(await fe.disableFile({filePath:y.filePath})).success)throw new Error("No se pudo eliminar el archivo del servidor")}return c(g=>{let N=g.filter(T=>T.id!==u);return k(N),N}),S?.(y),!0}catch(g){return v(u,{status:y.filePath?"completed":"error",errorMessage:g instanceof Error?g.message:"Error al eliminar"}),!1}},[m,v,k,S]),E=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("No se puede reintentar: archivo no encontrado o sin archivo original");return}v(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,v,b]),H=D(async()=>{let u=Array.from(o.current.values());u.length>0&&await Promise.allSettled(u)},[]),Y=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]),ge=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(!ie.isInitialized())return null;let g=await fe.getFileUrl({filePath:y.filePath,expiresIn:3600});return g.success&&g.data?.url?g.data.url:null}catch{return null}},[m]),F=te(()=>m.some(u=>u.status==="uploading"||u.status==="pending"),[m]),re=te(()=>m.filter(u=>u.status==="uploading"||u.status==="pending").length,[m]),De=te(()=>m.filter(u=>u.status==="completed"&&u.filePath).map(u=>u.filePath),[m]),{isValid:ze,validationError:Fe}=te(()=>{let u=m.filter(g=>g.status==="completed").length;return u<n?{isValid:!1,validationError:n===1?"Se requiere al menos un archivo":`Se requieren al menos ${n} archivos`}:t!==void 0&&u>t?{isValid:!1,validationError:`M\xE1ximo ${t} archivos permitidos`}:m.some(g=>g.status==="error")?{isValid:!1,validationError:"Algunos archivos tienen errores"}:{isValid:!0,validationError:null}},[m,n,t]);return{files:m,isUploading:F,pendingCount:re,addFiles:P,removeFile:z,clearFiles:E,retryUpload:V,isValid:ze,validationError:Fe,waitForUploads:H,completedFilePaths:De,initializeFiles:Y,isTouched:a,markAsTouched:p,getPreviewUrl:ge}};export{Te as a,Ae as b,Ie as c,A as d,W as e,be as f,ae as g,Se as h,et as i,oi as j,it as k,at as l,dt as m,de as n,ie as o,vt as p};
|
|
1
|
+
import{b as oe,d as ye,h as K,i as he,j as me,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 se=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}},Ee=se.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),[f,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&&f){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&&Ee.notifyCredentialsReady({apiUrl:p.apiEndpointAdmin,apiKey:p.apiKeyEndpointAdmin});else throw new Error("Crudify methods not properly initialized")}catch(p){let T=p instanceof Error?p.message:"Failed to initialize Crudify";console.error("[CrudifyProvider] Initialization error:",p),s(T),h(!1)}finally{t(!1)}})()},[r.publicApiKey,r.env,S,f]);let a={crudify:f?Y:null,isLoading:e,error:n,isInitialized:f,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 Z from"crypto-js";var d=class d{static setStorageType(i){d.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 Z.SHA256(i).toString()}static getEncryptionKey(){if(d.encryptionKey)return d.encryptionKey;let i=window.localStorage;if(!i)return d.encryptionKey=d.generateEncryptionKey(),d.encryptionKey;try{let e=i.getItem(d.ENCRYPTION_KEY_STORAGE);return(!e||e.length<32)&&(e=d.generateEncryptionKey(),i.setItem(d.ENCRYPTION_KEY_STORAGE,e)),d.encryptionKey=e,e}catch{return console.warn("Crudify: Cannot persist encryption key, using temporary key"),d.encryptionKey=d.generateEncryptionKey(),d.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 d.storageType==="none"?null:d.isStorageAvailable(d.storageType)?window[d.storageType]:(console.warn(`Crudify: ${d.storageType} not available, tokens won't persist`),null)}static encrypt(i){try{let e=d.getEncryptionKey();return Z.AES.encrypt(i,e).toString()}catch(e){return console.error("Crudify: Encryption failed",e),i}}static decrypt(i){try{let e=d.getEncryptionKey();return Z.AES.decrypt(i,e).toString(Z.enc.Utf8)||i}catch(e){return console.error("Crudify: Decryption failed",e),i}}static saveTokens(i){let e=d.getStorage();if(e)try{let t={accessToken:i.accessToken,refreshToken:i.refreshToken,expiresAt:i.expiresAt,refreshExpiresAt:i.refreshExpiresAt,savedAt:Date.now()},n=d.encrypt(JSON.stringify(t));e.setItem(d.TOKEN_KEY,n),console.debug("Crudify: Tokens saved successfully")}catch(t){console.error("Crudify: Failed to save tokens",t)}}static getTokens(){let i=d.getStorage();if(!i)return null;try{let e=i.getItem(d.TOKEN_KEY);if(!e)return null;let t=d.decrypt(e),n=JSON.parse(t);return!n.accessToken||!n.refreshToken||!n.expiresAt||!n.refreshExpiresAt?(console.warn("Crudify: Incomplete token data found, clearing storage"),d.clearTokens(),null):Date.now()>=n.refreshExpiresAt?(console.info("Crudify: Refresh token expired, clearing storage"),d.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),d.clearTokens(),null}}static clearTokens(){let i=d.getStorage();if(i)try{i.removeItem(d.TOKEN_KEY),console.debug("Crudify: Tokens cleared from storage")}catch(e){console.error("Crudify: Failed to clear tokens",e)}}static rotateEncryptionKey(){try{d.clearTokens(),d.encryptionKey=null;let i=window.localStorage;i&&i.removeItem(d.ENCRYPTION_KEY_STORAGE),console.info("Crudify: Encryption key rotated successfully")}catch(i){console.error("Crudify: Failed to rotate encryption key",i)}}static hasValidTokens(){return d.getTokens()!==null}static getExpirationInfo(){let i=d.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=d.getTokens();if(!t){console.warn("Crudify: Cannot update access token, no existing tokens found");return}d.saveTokens({...t,accessToken:i,expiresAt:e})}static subscribeToChanges(i){let e=t=>{if(t.key===d.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=d.getTokens();i(n)}}};return window.addEventListener("storage",e),()=>{window.removeEventListener("storage",e)}}};d.TOKEN_KEY="crudify_tokens",d.ENCRYPTION_KEY_STORAGE="crudify_enc_key",d.encryptionKey=null,d.storageType="localStorage";var A=d;import R from"@nocios/crudify-browser";var W=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?ye("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 q,useCallback as $}from"react";function be(r={}){let[i,e]=_e({isAuthenticated:!1,isLoading:!0,isInitialized:!1,tokens:null,error:null}),t=W.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(T=>({...T,isAuthenticated:!1,tokens:null,isLoading:!1,error:p?null:o})),{success:!1,error:o}}},[t]),f=$(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]);q(()=>{n()},[n]),q(()=>{if(!i.isAuthenticated||!i.tokens)return;let c=he.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,T=()=>{let k=o();p=setTimeout(async()=>{if(t.isRefreshing()){r.enableLogging&&console.log("\u23F8\uFE0F Refresh in progress, rescheduling check"),T();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(re=>({...re,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 f()):T()},k)};return T(),()=>{clearTimeout(p),window.removeEventListener("popstate",a),l()}},[i.isAuthenticated,i.tokens,t,r.enableLogging,f]),q(()=>{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]),q(()=>{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:f,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}),ae=({children:r,maxNotifications:i=5,defaultAutoHideDuration:e=6e3,position:t={vertical:"top",horizontal:"right"},enabled:n=!1,allowHtml:s=!1})=>{let[f,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(),T={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,T]),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:f.map(a=>_(ei,{notification:a,onClose:()=>I(a.id)},a.id))})})]})},ei=({notification:r,onClose:i})=>{let[e,t]=ke(!0),n=J((s,f)=>{f!=="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 le}from"react";import{Fragment as si,jsx as w,jsxs as O}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 f={};try{let o=Ie();o.isInitialized&&o.adminCredentials&&(f=o.adminCredentials)}catch{}let h=le(()=>{let o=oe({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:f.apiEndpointAdmin,apiKeyEndpointAdmin:f.apiKeyEndpointAdmin,publicApiKey:h.publicApiKey,env:h.env,onSessionExpired:()=>{i.onSessionExpired?.()}}),[i,s,f.apiEndpointAdmin,f.apiKeyEndpointAdmin,h]),I=be(S),m=le(()=>{let o=oe({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=le(()=>{if(!I.tokens?.accessToken||!I.isAuthenticated)return null;try{let o=me(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(T=>{["sub","email","subscriber"].includes(T)||(p[T]=o[T])}),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(ae,{...i,children:w(Pe,{...r})})}):w(ae,{...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?O("div",{style:{padding:"10px",margin:"10px",border:"1px solid #ccc",borderRadius:"4px",fontSize:"12px",fontFamily:"monospace"},children:[w("h4",{children:"Session Debug Info"}),O("div",{children:[w("strong",{children:"Authenticated:"})," ",r.isAuthenticated?"Yes":"No"]}),O("div",{children:[w("strong",{children:"Loading:"})," ",r.isLoading?"Yes":"No"]}),O("div",{children:[w("strong",{children:"Error:"})," ",r.error||"None"]}),r.tokens&&O(si,{children:[O("div",{children:[w("strong",{children:"Access Token:"})," ",r.tokens.accessToken.substring(0,20),"..."]}),O("div",{children:[w("strong",{children:"Refresh Token:"})," ",r.tokens.refreshToken.substring(0,20),"..."]}),O("div",{children:[w("strong",{children:"Access Expires In:"})," ",Math.round(r.expiresIn/1e3/60)," minutes"]}),O("div",{children:[w("strong",{children:"Refresh Expires In:"})," ",Math.round(r.refreshExpiresIn/1e3/60/60)," hours"]}),O("div",{children:[w("strong",{children:"Expiring Soon:"})," ",r.isExpiringSoon?"Yes":"No"]})]})]}):w("div",{children:"Session not initialized"})}import{useState as j,useEffect as we,useCallback as Re,useRef as Q}from"react";import ai from"@nocios/crudify-browser";var at=(r={})=>{let{autoFetch:i=!0,retryOnError:e=!1,maxRetries:t=3}=r,[n,s]=j(null),[f,h]=j(!1),[S,I]=j(null),[m,c]=j({}),a=Q(null),l=Q(!0),o=Q(0),p=Q(0),T=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:f,error:S,extendedData:m,refreshProfile:k,clearProfile:T}};import{useState as ce,useEffect as li,useCallback as ee,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:f=0,separator:h=""}=r,[S,I]=ce(""),[m,c]=ce(!1),[a,l]=ce(null),o=ci(!1),p=ee(b=>{let P=String(b).padStart(f,"0");return`${s}${h}${P}`},[s,f,h]),T=ee(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=ee(async()=>{await T()},[T]),C=ee(()=>{l(null)},[]);return li(()=>{e&&!S&&!o.current&&(o.current=!0,T())},[e,S,T]),{value:S,loading:m,error:a,regenerate:k,clearError:C}};import ue from"@nocios/crudify-browser";var de=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:f}=i;if(this.state.status==="INITIALIZED"){this.state.publicApiKey!==t&&console.warn(`[CrudifyInitialization] ${f} 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] ${f} waiting for ongoing initialization...`),this.initializationPromise;if(e==="LOW"&&this.highPriorityInitializerPresent&&this.state.status==="UNINITIALIZED"){if(s&&console.log(`[CrudifyInitialization] ${f} (LOW priority) waiting for HIGH priority initializer...`),this.waitingForHighPriority.add(f),await this.waitForHighPriorityOrTimeout(s),this.waitingForHighPriority.delete(f),this.getState().status==="INITIALIZED"){s&&console.log(`[CrudifyInitialization] ${f} found initialization completed by HIGH priority`);return}s&&console.warn(`[CrudifyInitialization] ${f} 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 ${f} interrupting LOW priority initialization by ${this.state.initializedBy}`),this.state.status="UNINITIALIZED",this.initializationPromise=null),s&&console.log(`[CrudifyInitialization] ${f} starting initialization (${e} priority)...`),this.state.status="INITIALIZING",this.state.priority=e,this.state.initializedBy=f,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 ${f} (${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 ${f}:`,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=ue.getTokenData();if(n&&n.endpoint){t&&console.log("[CrudifyInitialization] SDK already initialized externally");return}ue.config(e);let s=t?"debug":"none",f=await ue.init(i,s);if(f.success===!1)throw new Error(`Crudify initialization failed: ${JSON.stringify(f.errors||"Unknown error")}`)}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=de.getInstance();import{useState as Ce,useCallback as D,useRef as di,useMemo as te}from"react";import fe 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:f,onUploadError:h,onFileRemoved:S,onFilesChange:I}=r,[m,c]=Ce([]),[a,l]=Ce(!1),o=di(new Map),p=D(()=>{l(!0)},[]),T=D((u,y)=>{c(g=>g.map(E=>E.id===u?{...E,...y}:E))},[]),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(!ie.isInitialized())throw new Error("Crudify is not initialized. Please wait for the application to finish loading.");let g=fi(y.name),N=await fe.generateSignedUrl({fileName:g,contentType:y.type,visibility:s});if(!N.success||!N.data)throw new Error("Failed to get upload URL");let{uploadUrl:E,s3Key:x,publicUrl:M}=N.data;if(!E||!x)throw new Error("Incomplete signed URL response");let pe=x.indexOf("/"),Ke=pe>0?x.substring(pe+1):x;T(u.id,{status:"uploading",progress:0}),await new Promise((ne,G)=>{let L=new XMLHttpRequest;L.upload.addEventListener("progress",U=>{if(U.lengthComputable){let Ue=Math.round(U.loaded/U.total*100);T(u.id,{progress:Ue})}}),L.addEventListener("load",()=>{L.status>=200&&L.status<300?ne():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",E),L.setRequestHeader("Content-Type",y.type),L.send(y)});let Oe={status:"completed",progress:100,filePath:Ke,visibility:s,publicUrl:s==="public"?M:void 0,file:void 0};c(ne=>{let G=ne.map(U=>U.id===u.id?{...U,...Oe}:U);k(G);let L=G.find(U=>U.id===u.id);return L&&f?.(L),G})}catch(g){let N=g instanceof Error?g.message:"Unknown error";T(u.id,{status:"error",progress:0,errorMessage:N}),c(E=>{let x=E.find(M=>M.id===u.id);return x&&h?.(x,N),E})}},[T,f,h,s]),P=D(async u=>{let y=Array.from(u);if(t!==void 0){let E=m.filter(M=>M.status!=="error").length,x=t-E;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 E of y){let x=C(E),M={id:Le(),name:E.name,size:E.size,contentType:E.type,status:x.valid?"pending":"error",progress:0,createdAt:Date.now(),file:x.valid?E:void 0,errorMessage:x.error};g.push(M)}c(E=>{let x=[...E,...g];return k(x),x});let N=g.filter(E=>E.status==="pending"&&E.file);for(let E of N)if(E.file){let x=b(E,E.file);o.current.set(E.id,x),x.finally(()=>{o.current.delete(E.id)})}},[m,t,C,b,k]),z=D(async u=>{let y=m.find(g=>g.id===u);if(!y)return!1;T(u,{status:"removing"});try{if(y.filePath){if(!ie.isInitialized())throw new Error("Crudify is not initialized. Please wait for the application to finish loading.");if(!(await fe.disableFile({filePath:y.filePath})).success)throw new Error("Failed to remove file from server")}return c(g=>{let N=g.filter(E=>E.id!==u);return k(N),N}),S?.(y),!0}catch(g){return T(u,{status:y.filePath?"completed":"error",errorMessage:g instanceof Error?g.message:"Error removing file"}),!1}},[m,T,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}T(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,T,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]),ge=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(!ie.isInitialized())return null;let g=await fe.getFileUrl({filePath:y.filePath,expiresIn:3600});return g.success&&g.data?.url?g.data.url:null}catch{return null}},[m]),F=te(()=>m.some(u=>u.status==="uploading"||u.status==="pending"),[m]),re=te(()=>m.filter(u=>u.status==="uploading"||u.status==="pending").length,[m]),De=te(()=>m.filter(u=>u.status==="completed"&&u.filePath).map(u=>u.filePath),[m]),{isValid:ze,validationError:Fe}=te(()=>{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:re,addFiles:P,removeFile:z,clearFiles:v,retryUpload:V,isValid:ze,validationError:Fe,waitForUploads:H,completedFilePaths:De,initializeFiles:B,isTouched:a,markAsTouched:p,getPreviewUrl:ge}};export{Ee as a,Ae as b,Ie as c,A as d,W as e,be as f,ae as g,Se as h,et as i,oi as j,it as k,at as l,dt as m,de as n,ie as o,Tt as p};
|
package/dist/components.d.mts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export { B as BoxScreenType, a as CrudiaAutoGenerate, h as CrudiaAutoGenerateProps, b as CrudiaFileField, i as CrudiaFileFieldProps, C as CrudifyLogin, c as CrudifyLoginConfig, d as CrudifyLoginProps, e as CrudifyLoginTranslations, L as LoginComponent, P as Policies, g as PolicyAction, S as SessionStatus, f as UserLoginData, U as UserProfileDisplay } from './CrudiaFileField-
|
|
1
|
+
export { B as BoxScreenType, a as CrudiaAutoGenerate, h as CrudiaAutoGenerateProps, b as CrudiaFileField, i as CrudiaFileFieldProps, C as CrudifyLogin, c as CrudifyLoginConfig, d as CrudifyLoginProps, e as CrudifyLoginTranslations, L as LoginComponent, P as Policies, g as PolicyAction, S as SessionStatus, f as UserLoginData, U as UserProfileDisplay } from './CrudiaFileField-8ArxOo5y.mjs';
|
|
2
2
|
export { G as GlobalNotificationProvider, a as GlobalNotificationProviderProps, N as Notification, b as NotificationSeverity, u as useGlobalNotification } from './GlobalNotificationProvider-Zq18OkpI.mjs';
|
|
3
3
|
import * as react_jsx_runtime from 'react/jsx-runtime';
|
|
4
4
|
import 'react';
|
package/dist/components.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export { B as BoxScreenType, a as CrudiaAutoGenerate, h as CrudiaAutoGenerateProps, b as CrudiaFileField, i as CrudiaFileFieldProps, C as CrudifyLogin, c as CrudifyLoginConfig, d as CrudifyLoginProps, e as CrudifyLoginTranslations, L as LoginComponent, P as Policies, g as PolicyAction, S as SessionStatus, f as UserLoginData, U as UserProfileDisplay } from './CrudiaFileField-
|
|
1
|
+
export { B as BoxScreenType, a as CrudiaAutoGenerate, h as CrudiaAutoGenerateProps, b as CrudiaFileField, i as CrudiaFileFieldProps, C as CrudifyLogin, c as CrudifyLoginConfig, d as CrudifyLoginProps, e as CrudifyLoginTranslations, L as LoginComponent, P as Policies, g as PolicyAction, S as SessionStatus, f as UserLoginData, U as UserProfileDisplay } from './CrudiaFileField-DA-kEoTA.js';
|
|
2
2
|
export { G as GlobalNotificationProvider, a as GlobalNotificationProviderProps, N as Notification, b as NotificationSeverity, u as useGlobalNotification } from './GlobalNotificationProvider-Zq18OkpI.js';
|
|
3
3
|
import * as react_jsx_runtime from 'react/jsx-runtime';
|
|
4
4
|
import 'react';
|
package/dist/components.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports, "__esModule", {value: true});var
|
|
1
|
+
"use strict";Object.defineProperty(exports, "__esModule", {value: true});var _chunkURTGOZMJjs = require('./chunk-URTGOZMJ.js');var _chunkPDFLD5FFjs = require('./chunk-PDFLD5FF.js');require('./chunk-YIIUEOXC.js');require('./chunk-FC7HOMNQ.js');var _react = require('react');var _jsxruntime = require('react/jsx-runtime');function B({showBelowMinutes:f=5,position:c="bottom-right",colorNormal:m="#ed6c02",colorCritical:x="#d32f2f",style:u,className:g}={}){let{isAuthenticated:o,tokens:t}=_chunkPDFLD5FFjs.f.call(void 0, ),[i,y]=_react.useState.call(void 0, 0),[h,S]=_react.useState.call(void 0, 100);if(_react.useEffect.call(void 0, ()=>{if(!o||!t)return;let v=setInterval(()=>{let P=Date.now(),p=t.expiresAt-P,w=900*1e3;y(Math.max(0,p)),S(Math.max(0,p/w*100))},1e3);return()=>clearInterval(v)},[o,t]),!o||i<=0)return null;let e=Math.floor(i/6e4),b=Math.floor(i%6e4/1e3);if(e>=f)return null;let s=e<2,a=s?x:m,C={"top-left":{top:"16px",left:"16px"},"top-right":{top:"16px",right:"16px"},"bottom-left":{bottom:"16px",left:"16px"},"bottom-right":{bottom:"16px",right:"16px"}}[c];return _jsxruntime.jsxs.call(void 0, "div",{className:g,style:{position:"fixed",...C,padding:"12px 16px",backgroundColor:"white",borderRadius:"8px",boxShadow:"0 4px 12px rgba(0, 0, 0, 0.15)",minWidth:"200px",zIndex:9999,fontFamily:"system-ui, -apple-system, sans-serif",...u},children:[_jsxruntime.jsxs.call(void 0, "div",{style:{marginBottom:"8px"},children:[_jsxruntime.jsx.call(void 0, "div",{style:{fontSize:"12px",fontWeight:600,color:a,marginBottom:"4px"},children:s?"\u26A0\uFE0F Sesi\xF3n expirando":"\u23F0 Sesi\xF3n por expirar"}),_jsxruntime.jsxs.call(void 0, "div",{style:{fontSize:"14px",color:"#333",fontWeight:500},children:[e,":",b.toString().padStart(2,"0")]})]}),_jsxruntime.jsx.call(void 0, "div",{style:{width:"100%",height:"6px",backgroundColor:"#e0e0e0",borderRadius:"3px",overflow:"hidden"},children:_jsxruntime.jsx.call(void 0, "div",{style:{width:`${h}%`,height:"100%",backgroundColor:a,transition:"width 1s linear"}})})]})}exports.CrudiaAutoGenerate = _chunkURTGOZMJjs.o; exports.CrudiaFileField = _chunkURTGOZMJjs.p; exports.CrudifyLogin = _chunkURTGOZMJjs.h; exports.GlobalNotificationProvider = _chunkPDFLD5FFjs.g; exports.LoginComponent = _chunkURTGOZMJjs.m; exports.Policies = _chunkURTGOZMJjs.l; exports.SessionStatus = _chunkURTGOZMJjs.n; exports.SessionTimeIndicator = B; exports.UserProfileDisplay = _chunkURTGOZMJjs.i; exports.useGlobalNotification = _chunkPDFLD5FFjs.h;
|
package/dist/components.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{h as T,i as F,l as G,m as L,n as A,o as M,p as R}from"./chunk-
|
|
1
|
+
import{h as T,i as F,l as G,m as L,n as A,o as M,p as R}from"./chunk-GFSDL6HT.mjs";import{f as l,g as I,h as N}from"./chunk-YRS5XYAB.mjs";import"./chunk-BJ6PIVZR.mjs";import"./chunk-6GPSBDW6.mjs";import{useEffect as k,useState as d}from"react";import{jsx as r,jsxs as n}from"react/jsx-runtime";function B({showBelowMinutes:f=5,position:c="bottom-right",colorNormal:m="#ed6c02",colorCritical:x="#d32f2f",style:u,className:g}={}){let{isAuthenticated:o,tokens:t}=l(),[i,y]=d(0),[h,S]=d(100);if(k(()=>{if(!o||!t)return;let v=setInterval(()=>{let P=Date.now(),p=t.expiresAt-P,w=900*1e3;y(Math.max(0,p)),S(Math.max(0,p/w*100))},1e3);return()=>clearInterval(v)},[o,t]),!o||i<=0)return null;let e=Math.floor(i/6e4),b=Math.floor(i%6e4/1e3);if(e>=f)return null;let s=e<2,a=s?x:m,C={"top-left":{top:"16px",left:"16px"},"top-right":{top:"16px",right:"16px"},"bottom-left":{bottom:"16px",left:"16px"},"bottom-right":{bottom:"16px",right:"16px"}}[c];return n("div",{className:g,style:{position:"fixed",...C,padding:"12px 16px",backgroundColor:"white",borderRadius:"8px",boxShadow:"0 4px 12px rgba(0, 0, 0, 0.15)",minWidth:"200px",zIndex:9999,fontFamily:"system-ui, -apple-system, sans-serif",...u},children:[n("div",{style:{marginBottom:"8px"},children:[r("div",{style:{fontSize:"12px",fontWeight:600,color:a,marginBottom:"4px"},children:s?"\u26A0\uFE0F Sesi\xF3n expirando":"\u23F0 Sesi\xF3n por expirar"}),n("div",{style:{fontSize:"14px",color:"#333",fontWeight:500},children:[e,":",b.toString().padStart(2,"0")]})]}),r("div",{style:{width:"100%",height:"6px",backgroundColor:"#e0e0e0",borderRadius:"3px",overflow:"hidden"},children:r("div",{style:{width:`${h}%`,height:"100%",backgroundColor:a,transition:"width 1s linear"}})})]})}export{M as CrudiaAutoGenerate,R as CrudiaFileField,T as CrudifyLogin,I as GlobalNotificationProvider,L as LoginComponent,G as Policies,A as SessionStatus,B as SessionTimeIndicator,F as UserProfileDisplay,N as useGlobalNotification};
|
package/dist/hooks.d.mts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export { F as FileItem, q as FileStatus, d as SessionState, j as UseAuthReturn, l as UseDataReturn, o as UseFileUploadOptions, p as UseFileUploadReturn, U as UseSessionOptions, g as UseUserDataOptions, f as UseUserDataReturn, h as UserData, i as useAuth, r as useCrudifyWithNotifications, k as useData, n as useFileUpload, u as useSession, e as useUserData, m as useUserProfile } from './index-
|
|
1
|
+
export { F as FileItem, q as FileStatus, d as SessionState, j as UseAuthReturn, l as UseDataReturn, o as UseFileUploadOptions, p as UseFileUploadReturn, U as UseSessionOptions, g as UseUserDataOptions, f as UseUserDataReturn, h as UserData, i as useAuth, r as useCrudifyWithNotifications, k as useData, n as useFileUpload, u as useSession, e as useUserData, m as useUserProfile } from './index-CQnAzvOE.mjs';
|
|
2
2
|
export { A as AutoGenerateConfig, d as UseAutoGenerateOptions, U as UseAutoGenerateReturn, c as useAutoGenerate } from './GlobalNotificationProvider-Zq18OkpI.mjs';
|
|
3
3
|
import './api-Djqihi4n.mjs';
|
|
4
4
|
import '@nocios/crudify-browser';
|
package/dist/hooks.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export { F as FileItem, q as FileStatus, d as SessionState, j as UseAuthReturn, l as UseDataReturn, o as UseFileUploadOptions, p as UseFileUploadReturn, U as UseSessionOptions, g as UseUserDataOptions, f as UseUserDataReturn, h as UserData, i as useAuth, r as useCrudifyWithNotifications, k as useData, n as useFileUpload, u as useSession, e as useUserData, m as useUserProfile } from './index-
|
|
1
|
+
export { F as FileItem, q as FileStatus, d as SessionState, j as UseAuthReturn, l as UseDataReturn, o as UseFileUploadOptions, p as UseFileUploadReturn, U as UseSessionOptions, g as UseUserDataOptions, f as UseUserDataReturn, h as UserData, i as useAuth, r as useCrudifyWithNotifications, k as useData, n as useFileUpload, u as useSession, e as useUserData, m as useUserProfile } from './index-BVT7flO5.js';
|
|
2
2
|
export { A as AutoGenerateConfig, d as UseAutoGenerateOptions, U as UseAutoGenerateReturn, c as useAutoGenerate } from './GlobalNotificationProvider-Zq18OkpI.js';
|
|
3
3
|
import './api-Djqihi4n.js';
|
|
4
4
|
import '@nocios/crudify-browser';
|
package/dist/hooks.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports, "__esModule", {value: true});var
|
|
1
|
+
"use strict";Object.defineProperty(exports, "__esModule", {value: true});var _chunkJ4K6MZHYjs = require('./chunk-J4K6MZHY.js');var _chunkPDFLD5FFjs = require('./chunk-PDFLD5FF.js');require('./chunk-FC7HOMNQ.js');exports.useAuth = _chunkJ4K6MZHYjs.b; exports.useAutoGenerate = _chunkPDFLD5FFjs.m; exports.useCrudifyWithNotifications = _chunkJ4K6MZHYjs.d; exports.useData = _chunkJ4K6MZHYjs.c; exports.useFileUpload = _chunkPDFLD5FFjs.p; exports.useSession = _chunkPDFLD5FFjs.f; exports.useUserData = _chunkJ4K6MZHYjs.a; exports.useUserProfile = _chunkPDFLD5FFjs.l;
|
package/dist/hooks.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as s,b as u,c as a,d as p}from"./chunk-
|
|
1
|
+
import{a as s,b as u,c as a,d as p}from"./chunk-GWQVH4G4.mjs";import{f as e,l as t,m as o,p as r}from"./chunk-YRS5XYAB.mjs";import"./chunk-6GPSBDW6.mjs";export{u as useAuth,o as useAutoGenerate,p as useCrudifyWithNotifications,a as useData,r as useFileUpload,e as useSession,s as useUserData,t as useUserProfile};
|
|
@@ -463,121 +463,129 @@ interface UseUserProfileReturn {
|
|
|
463
463
|
declare const useUserProfile: (options?: UseUserProfileOptions) => UseUserProfileReturn;
|
|
464
464
|
|
|
465
465
|
/**
|
|
466
|
-
*
|
|
466
|
+
* Complete hook for file handling with:
|
|
467
|
+
* - Progressive upload to S3 with pre-signed URLs
|
|
468
|
+
* - Per-file progress tracking
|
|
469
|
+
* - Type and size validation
|
|
470
|
+
* - Soft delete (disableFile)
|
|
471
|
+
* - Multiple file support
|
|
472
|
+
*/
|
|
473
|
+
/**
|
|
474
|
+
* Individual file status
|
|
467
475
|
*/
|
|
468
476
|
type FileStatus = "pending" | "uploading" | "completed" | "error" | "removing";
|
|
469
477
|
/**
|
|
470
|
-
*
|
|
478
|
+
* Represents a file in the system
|
|
471
479
|
*/
|
|
472
480
|
interface FileItem {
|
|
473
|
-
/**
|
|
481
|
+
/** Unique file ID (generated or from server) */
|
|
474
482
|
id: string;
|
|
475
|
-
/**
|
|
483
|
+
/** Original file name */
|
|
476
484
|
name: string;
|
|
477
|
-
/**
|
|
485
|
+
/** Size in bytes */
|
|
478
486
|
size: number;
|
|
479
|
-
/**
|
|
487
|
+
/** MIME content type */
|
|
480
488
|
contentType: string;
|
|
481
|
-
/**
|
|
489
|
+
/** Current file status */
|
|
482
490
|
status: FileStatus;
|
|
483
|
-
/**
|
|
491
|
+
/** Upload progress (0-100) */
|
|
484
492
|
progress: number;
|
|
485
493
|
/**
|
|
486
|
-
*
|
|
487
|
-
*
|
|
494
|
+
* Relative file path (includes visibility)
|
|
495
|
+
* Format: "public/path/file.ext" or "private/path/file.ext"
|
|
488
496
|
*/
|
|
489
497
|
filePath?: string;
|
|
490
498
|
/**
|
|
491
|
-
*
|
|
492
|
-
*
|
|
499
|
+
* File visibility
|
|
500
|
+
* Extracted from filePath for convenience
|
|
493
501
|
*/
|
|
494
502
|
visibility?: "public" | "private";
|
|
495
|
-
/** URL
|
|
503
|
+
/** Public URL for public files */
|
|
496
504
|
publicUrl?: string;
|
|
497
|
-
/** URL
|
|
505
|
+
/** Preview URL (for images) */
|
|
498
506
|
previewUrl?: string;
|
|
499
|
-
/**
|
|
507
|
+
/** Error message if failed */
|
|
500
508
|
errorMessage?: string;
|
|
501
|
-
/**
|
|
509
|
+
/** Creation timestamp */
|
|
502
510
|
createdAt: number;
|
|
503
|
-
/**
|
|
511
|
+
/** Original file (only during upload) */
|
|
504
512
|
file?: File;
|
|
505
513
|
}
|
|
506
514
|
/**
|
|
507
|
-
*
|
|
515
|
+
* Hook configuration
|
|
508
516
|
*/
|
|
509
517
|
interface UseFileUploadOptions {
|
|
510
|
-
/**
|
|
518
|
+
/** Allowed MIME types (e.g., ["image/png", "image/jpeg", "application/pdf"]) */
|
|
511
519
|
acceptedTypes?: string[];
|
|
512
|
-
/**
|
|
520
|
+
/** Maximum file size in bytes (default: 10MB) */
|
|
513
521
|
maxFileSize?: number;
|
|
514
|
-
/**
|
|
522
|
+
/** Maximum number of files (undefined = no limit) */
|
|
515
523
|
maxFiles?: number;
|
|
516
|
-
/**
|
|
524
|
+
/** Minimum number of required files (default: 0) */
|
|
517
525
|
minFiles?: number;
|
|
518
526
|
/**
|
|
519
|
-
*
|
|
527
|
+
* Visibility of uploaded files
|
|
520
528
|
* @default "private"
|
|
521
529
|
*/
|
|
522
530
|
visibility?: "public" | "private";
|
|
523
|
-
/** Callback
|
|
531
|
+
/** Callback when an upload completes successfully */
|
|
524
532
|
onUploadComplete?: (file: FileItem) => void;
|
|
525
|
-
/** Callback
|
|
533
|
+
/** Callback when an upload fails */
|
|
526
534
|
onUploadError?: (file: FileItem, error: string) => void;
|
|
527
|
-
/** Callback
|
|
535
|
+
/** Callback when a file is removed */
|
|
528
536
|
onFileRemoved?: (file: FileItem) => void;
|
|
529
|
-
/** Callback
|
|
537
|
+
/** Callback when the file list changes */
|
|
530
538
|
onFilesChange?: (files: FileItem[]) => void;
|
|
531
539
|
}
|
|
532
540
|
/**
|
|
533
|
-
*
|
|
541
|
+
* Hook return type
|
|
534
542
|
*/
|
|
535
543
|
interface UseFileUploadReturn {
|
|
536
|
-
/**
|
|
544
|
+
/** Current file list */
|
|
537
545
|
files: FileItem[];
|
|
538
|
-
/**
|
|
546
|
+
/** Whether uploads are in progress */
|
|
539
547
|
isUploading: boolean;
|
|
540
|
-
/**
|
|
548
|
+
/** Number of pending uploads */
|
|
541
549
|
pendingCount: number;
|
|
542
|
-
/**
|
|
550
|
+
/** Add files (triggers automatic upload) */
|
|
543
551
|
addFiles: (files: FileList | File[]) => Promise<void>;
|
|
544
|
-
/**
|
|
552
|
+
/** Remove a file (soft delete in S3) */
|
|
545
553
|
removeFile: (fileId: string) => Promise<boolean>;
|
|
546
|
-
/**
|
|
554
|
+
/** Clear all files */
|
|
547
555
|
clearFiles: () => void;
|
|
548
|
-
/**
|
|
556
|
+
/** Retry upload for a failed file */
|
|
549
557
|
retryUpload: (fileId: string) => Promise<void>;
|
|
550
|
-
/**
|
|
558
|
+
/** Validate if minimum requirements are met */
|
|
551
559
|
isValid: boolean;
|
|
552
|
-
/**
|
|
560
|
+
/** Validation error message */
|
|
553
561
|
validationError: string | null;
|
|
554
|
-
/**
|
|
562
|
+
/** Wait for all uploads to complete */
|
|
555
563
|
waitForUploads: () => Promise<void>;
|
|
556
564
|
/**
|
|
557
|
-
*
|
|
558
|
-
*
|
|
565
|
+
* Completed file paths (for saving in form)
|
|
566
|
+
* Relative paths with visibility - subscriberKey is added in backend
|
|
559
567
|
*/
|
|
560
568
|
completedFilePaths: string[];
|
|
561
|
-
/**
|
|
569
|
+
/** Initialize with existing files (for editing) */
|
|
562
570
|
initializeFiles: (existingFiles: Array<{
|
|
563
571
|
filePath: string;
|
|
564
572
|
name: string;
|
|
565
573
|
size?: number;
|
|
566
574
|
contentType?: string;
|
|
567
575
|
}>) => void;
|
|
568
|
-
/**
|
|
576
|
+
/** Whether the user has interacted with the field */
|
|
569
577
|
isTouched: boolean;
|
|
570
|
-
/**
|
|
578
|
+
/** Mark the field as touched (to show validation errors) */
|
|
571
579
|
markAsTouched: () => void;
|
|
572
580
|
/**
|
|
573
|
-
*
|
|
574
|
-
* -
|
|
575
|
-
* -
|
|
581
|
+
* Get URL for file preview
|
|
582
|
+
* - Public: returns publicUrl directly
|
|
583
|
+
* - Private: requests signed URL from backend
|
|
576
584
|
*/
|
|
577
585
|
getPreviewUrl: (fileId: string) => Promise<string | null>;
|
|
578
586
|
}
|
|
579
587
|
/**
|
|
580
|
-
* Hook
|
|
588
|
+
* Hook for complete file handling with S3 upload
|
|
581
589
|
*
|
|
582
590
|
* @example
|
|
583
591
|
* ```tsx
|
|
@@ -595,9 +603,9 @@ interface UseFileUploadReturn {
|
|
|
595
603
|
* minFiles: 1
|
|
596
604
|
* });
|
|
597
605
|
*
|
|
598
|
-
* //
|
|
606
|
+
* // In form submit
|
|
599
607
|
* const handleSubmit = async () => {
|
|
600
|
-
* await waitForUploads(); //
|
|
608
|
+
* await waitForUploads(); // Wait for pending uploads
|
|
601
609
|
* if (!isValid) return;
|
|
602
610
|
*
|
|
603
611
|
* await crudify.createItem("documents", {
|