@nocios/crudify-ui 4.4.74 → 4.4.76
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/{CrudiaMarkdownField-Bs940oF4.d.ts → CrudiaMarkdownField-C30enyF9.d.ts} +2 -2
- package/dist/{CrudiaMarkdownField-CKPdr2JL.d.mts → CrudiaMarkdownField-D-VooBtq.d.mts} +2 -2
- package/dist/{api-Djqihi4n.d.mts → api-RK-xY1Ah.d.mts} +22 -2
- package/dist/{api-Djqihi4n.d.ts → api-RK-xY1Ah.d.ts} +22 -2
- package/dist/chunk-2G33BADS.mjs +1 -0
- package/dist/{chunk-2RQAIPFB.mjs → chunk-7J5RTLCS.mjs} +1 -1
- package/dist/chunk-AEHAZP5F.js +1 -0
- package/dist/{chunk-YLCEL2HE.js → chunk-D3NBX3SM.js} +1 -1
- package/dist/{chunk-PK2UX3UH.mjs → chunk-GCH3QGKL.mjs} +1 -1
- package/dist/{chunk-NXXCVAVE.js → chunk-GNGIFVA4.js} +1 -1
- package/dist/{chunk-N6OQJOCM.js → chunk-HDNGW5H5.js} +1 -1
- package/dist/chunk-IYTXJHKO.js +1 -0
- package/dist/{chunk-7X3OJMPH.mjs → chunk-NZIH26GS.mjs} +1 -1
- package/dist/chunk-ZKWTILQT.mjs +1 -0
- 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/{errorTranslation-BuEEtVg4.d.mts → errorTranslation-B4wcHzD3.d.mts} +1 -1
- package/dist/{errorTranslation-BIyBYuGF.d.ts → errorTranslation-CCC5IWoN.d.ts} +1 -1
- package/dist/hooks.d.mts +4 -3
- package/dist/hooks.d.ts +4 -3
- package/dist/hooks.js +1 -1
- package/dist/hooks.mjs +1 -1
- package/dist/{index-CQnAzvOE.d.mts → index-DEnlzdtV.d.mts} +90 -16
- package/dist/{index-BVT7flO5.d.ts → index-pQmuVg3q.d.ts} +90 -16
- package/dist/index.d.mts +11 -71
- package/dist/index.d.ts +11 -71
- package/dist/index.js +2 -2
- package/dist/index.mjs +2 -2
- package/dist/utils.d.mts +3 -3
- package/dist/utils.d.ts +3 -3
- package/dist/utils.js +1 -1
- package/dist/utils.mjs +1 -1
- package/package.json +3 -3
- package/coverage/base.css +0 -224
- package/coverage/block-navigation.js +0 -87
- package/coverage/configResolver.ts.html +0 -499
- package/coverage/coverage-final.json +0 -2
- package/coverage/favicon.png +0 -0
- package/coverage/index.html +0 -116
- package/coverage/prettify.css +0 -1
- package/coverage/prettify.js +0 -2
- package/coverage/sort-arrow-sprite.png +0 -0
- package/coverage/sorter.js +0 -210
- package/dist/chunk-4Z2XAMJA.js +0 -1
- package/dist/chunk-EXXKBYWY.js +0 -1
- package/dist/chunk-ML7JNB3X.mjs +0 -1
- package/dist/chunk-RPYFDF5Q.mjs +0 -1
package/dist/chunk-RPYFDF5Q.mjs
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{a as p,c as ce,e as me,i as O,j as Ee,k as Te,l as ve}from"./chunk-PK2UX3UH.mjs";import{createContext as Ge,useContext as _e,useEffect as $e,useState as Z}from"react";import q from"@nocios/crudify-browser";var ue=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){p.error("[CredentialsEventBus] Error in listener",t instanceof Error?t:{message:String(t)})}}),this.listeners=[]}waitForCredentials(){return this.isReady&&this.credentials?Promise.resolve(this.credentials):new Promise(i=>{this.listeners.push(i)})}reset(){this.credentials=null,this.isReady=!1,this.listeners=[]}areCredentialsReady(){return this.isReady&&this.credentials!==null}},j=ue.getInstance();import{jsx as Ve}from"react/jsx-runtime";var Ae=Ge(void 0),Ie=({config:r,children:i})=>{let[e,t]=Z(!0),[o,s]=Z(null),[d,m]=Z(!1),[w,b]=Z(""),[T,c]=Z();$e(()=>{if(!r.publicApiKey){s("No publicApiKey provided"),t(!1),m(!1);return}let l=`${r.publicApiKey}-${r.env}`;if(l===w&&d){t(!1);return}(async()=>{t(!0),s(null),m(!1);try{q.config(r.env||"prod");let y=await q.init(r.publicApiKey,"none");if(c(y),typeof q.transaction=="function"&&typeof q.login=="function")m(!0),b(l),y.apiEndpointAdmin&&y.apiKeyEndpointAdmin&&j.notifyCredentialsReady({apiUrl:y.apiEndpointAdmin,apiKey:y.apiKeyEndpointAdmin});else throw new Error("Crudify methods not properly initialized")}catch(y){let E=y instanceof Error?y.message:"Failed to initialize Crudify";p.error("[CrudifyProvider] Initialization error",y instanceof Error?y:{message:String(y)}),s(E),m(!1)}finally{t(!1)}})()},[r.publicApiKey,r.env,w,d]);let a={crudify:d?q:null,isLoading:e,error:o,isInitialized:d,adminCredentials:T};return Ve(Ae.Provider,{value:a,children:i})},be=()=>{let r=_e(Ae);if(r===void 0)throw new Error("useCrudify must be used within a CrudifyProvider");return r};import J from"crypto-js";var f=class f{static setStorageType(i){f.storageType=i}static generateEncryptionKey(){let i=[navigator.userAgent,navigator.language,navigator.platform,screen.width,screen.height,Date.now().toString(),Math.random().toString(36)].join("|");return J.SHA256(i).toString()}static getEncryptionKey(){if(f.encryptionKey)return f.encryptionKey;let i=window.localStorage;if(!i)return f.encryptionKey=f.generateEncryptionKey(),f.encryptionKey;try{let e=i.getItem(f.ENCRYPTION_KEY_STORAGE);return(!e||e.length<32)&&(e=f.generateEncryptionKey(),i.setItem(f.ENCRYPTION_KEY_STORAGE,e)),f.encryptionKey=e,e}catch{return p.warn("Crudify: Cannot persist encryption key, using temporary key"),f.encryptionKey=f.generateEncryptionKey(),f.encryptionKey}}static isStorageAvailable(i){try{let e=window[i],t="__storage_test__";return e.setItem(t,"test"),e.removeItem(t),!0}catch{return!1}}static getStorage(){return f.storageType==="none"?null:f.isStorageAvailable(f.storageType)?window[f.storageType]:(p.warn(`Crudify: ${f.storageType} not available, tokens won't persist`),null)}static encrypt(i){try{let e=f.getEncryptionKey();return J.AES.encrypt(i,e).toString()}catch(e){return p.error("Crudify: Encryption failed",e instanceof Error?e:{message:String(e)}),i}}static decrypt(i){try{let e=f.getEncryptionKey();return J.AES.decrypt(i,e).toString(J.enc.Utf8)||i}catch(e){return p.error("Crudify: Decryption failed",e instanceof Error?e:{message:String(e)}),i}}static saveTokens(i){let e=f.getStorage();if(e)try{let t={accessToken:i.accessToken,refreshToken:i.refreshToken,expiresAt:i.expiresAt,refreshExpiresAt:i.refreshExpiresAt,savedAt:Date.now()},o=f.encrypt(JSON.stringify(t));e.setItem(f.TOKEN_KEY,o),p.debug("Crudify: Tokens saved successfully")}catch(t){p.error("Crudify: Failed to save tokens",t instanceof Error?t:{message:String(t)})}}static getTokens(){let i=f.getStorage();if(!i)return null;try{let e=i.getItem(f.TOKEN_KEY);if(!e)return null;let t=f.decrypt(e),o=JSON.parse(t);return!o.accessToken||!o.refreshToken||!o.expiresAt||!o.refreshExpiresAt?(p.warn("Crudify: Incomplete token data found, clearing storage"),f.clearTokens(),null):Date.now()>=o.refreshExpiresAt?(p.info("Crudify: Refresh token expired, clearing storage"),f.clearTokens(),null):{accessToken:o.accessToken,refreshToken:o.refreshToken,expiresAt:o.expiresAt,refreshExpiresAt:o.refreshExpiresAt}}catch(e){return p.error("Crudify: Failed to retrieve tokens",e instanceof Error?e:{message:String(e)}),f.clearTokens(),null}}static clearTokens(){let i=f.getStorage();if(i)try{i.removeItem(f.TOKEN_KEY),p.debug("Crudify: Tokens cleared from storage")}catch(e){p.error("Crudify: Failed to clear tokens",e instanceof Error?e:{message:String(e)})}}static rotateEncryptionKey(){try{f.clearTokens(),f.encryptionKey=null;let i=window.localStorage;i&&i.removeItem(f.ENCRYPTION_KEY_STORAGE),p.info("Crudify: Encryption key rotated successfully")}catch(i){p.error("Crudify: Failed to rotate encryption key",i instanceof Error?i:{message:String(i)})}}static hasValidTokens(){return f.getTokens()!==null}static getExpirationInfo(){let i=f.getTokens();if(!i)return null;let e=Date.now();return{accessExpired:e>=i.expiresAt,refreshExpired:e>=i.refreshExpiresAt,accessExpiresIn:Math.max(0,i.expiresAt-e),refreshExpiresIn:Math.max(0,i.refreshExpiresAt-e)}}static updateAccessToken(i,e){let t=f.getTokens();if(!t){p.warn("Crudify: Cannot update access token, no existing tokens found");return}f.saveTokens({...t,accessToken:i,expiresAt:e})}static subscribeToChanges(i){let e=t=>{if(t.key===f.TOKEN_KEY){if(t.newValue===null){p.debug("Crudify: Tokens removed in another tab"),i(null);return}if(t.newValue){p.debug("Crudify: Tokens updated in another tab");let o=f.getTokens();i(o)}}};return window.addEventListener("storage",e),()=>{window.removeEventListener("storage",e)}}};f.TOKEN_KEY="crudify_tokens",f.ENCRYPTION_KEY_STORAGE="crudify_enc_key",f.encryptionKey=null,f.storageType="localStorage";var I=f;import C from"@nocios/crudify-browser";var Q=class r{constructor(){this.config={};this.initialized=!1;this.crudifyInitialized=!1;this.lastActivityTime=0;this.isRefreshingLocally=!1;this.refreshPromise=null}static getInstance(){return r.instance||(r.instance=new r),r.instance}async initialize(i={}){if(!this.initialized){if(this.config={storageType:"localStorage",autoRestore:!0,enableLogging:!1,env:"stg",...i},I.setStorageType(this.config.storageType||"localStorage"),this.config.publicApiKey&&!this.crudifyInitialized&&await this.ensureCrudifyInitialized(),C.setTokenInvalidationCallback(()=>{this.log("Tokens invalidated by crudify-core"),O.emit("SESSION_EXPIRED",{message:"Your session has expired. Please log in again.",source:"crudify-core.clearTokensAndRefreshState"})}),this.config.apiEndpointAdmin&&this.config.apiKeyEndpointAdmin){let e=I.getTokens();e?I.saveTokens({...e,apiEndpointAdmin:this.config.apiEndpointAdmin,apiKeyEndpointAdmin:this.config.apiKeyEndpointAdmin}):I.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 C.login(i,e);if(!t.success)return{success:!1,error:this.formatError(t.errors),rawResponse:t};let o=I.getTokens(),s={accessToken:t.data.token,refreshToken:t.data.refreshToken,expiresAt:t.data.expiresAt,refreshExpiresAt:t.data.refreshExpiresAt,apiEndpointAdmin:o?.apiEndpointAdmin||this.config.apiEndpointAdmin,apiKeyEndpointAdmin:o?.apiKeyEndpointAdmin||this.config.apiKeyEndpointAdmin};return I.saveTokens(s),this.lastActivityTime=Date.now(),this.config.onLoginSuccess?.(s),{success:!0,tokens:s,data:t.data}}catch(t){return p.error("[SessionManager] Login error",t instanceof Error?t:{message:String(t)}),{success:!1,error:t instanceof Error?t.message:"Unknown error"}}}async logout(){try{this.log("Logging out..."),await C.logout(),I.clearTokens(),this.log("Logout successful"),this.config.onLogout?.()}catch(i){this.log("Logout error:",i),I.clearTokens()}}async restoreSession(){try{this.log("Attempting to restore session...");let i=I.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"),I.clearTokens(),!1;if(C.setTokens({accessToken:i.accessToken,refreshToken:i.refreshToken,expiresAt:i.expiresAt,refreshExpiresAt:i.refreshExpiresAt}),C.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 o=I.getTokens();return o&&this.config.onSessionRestored?.(o),!0}return I.clearTokens(),await C.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),I.clearTokens(),await C.logout(),!1}}isAuthenticated(){return C.isLogin()||I.hasValidTokens()}getTokenInfo(){let i=C.getTokenData(),e=I.getExpirationInfo(),t=I.getTokens();return{isLoggedIn:this.isAuthenticated(),crudifyTokens:i,storageInfo:e,hasValidTokens:I.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 C.refreshAccessToken();if(!i.success)return this.log("Token refresh failed:",i.errors),I.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 I.saveTokens(e),this.log("Tokens refreshed and saved successfully"),this.lastActivityTime=Date.now(),!0}catch(i){return this.log("Token refresh error:",i),I.clearTokens(),this.config.showNotification?.(this.getSessionExpiredMessage(),"warning"),this.config.onSessionExpired?.(),!1}}isRefreshing(){return this.isRefreshingLocally}setupResponseInterceptor(){C.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"),O.emit("TOKEN_REFRESH_FAILED",{message:e.userFriendlyMessage,error:e.errorDetails,source:"SessionManager.setupResponseInterceptor"}),i;e.shouldTriggerLogout&&(I.hasValidTokens()&&!e.isIrrecoverable?(this.log("Access token expired, emitting TOKEN_EXPIRED event"),O.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"),O.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=C.getTokenData();if(i&&i.endpoint){this.log("Crudify already initialized by another service"),this.crudifyInitialized=!0;return}let e=this.config.env||"stg";C.config(e);let t=this.config.publicApiKey,o=this.config.enableLogging?"debug":"none",s=await C.init(t,o);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 p.error("[SessionManager] Failed to initialize crudify",i instanceof Error?i:{message:String(i)}),i}}detectAuthorizationError(i){let e={isAuthError:!1,isRefreshTokenInvalid:!1,isTokenRefreshFailed:!1,isTokenExpired:!1,isUnauthorized:!1,isIrrecoverable:!1,shouldTriggerLogout:!1,errorType:"",errorDetails:null,userFriendlyMessage:""};if(i.errors&&Array.isArray(i.errors)){let t=i.errors.find(o=>o.errorType==="Unauthorized"||o.message?.includes("Unauthorized")||o.message?.includes("Not Authorized")||o.message?.includes("NOT_AUTHORIZED")||o.message?.includes("Token")||o.message?.includes("TOKEN")||o.message?.includes("Authentication")||o.message?.includes("UNAUTHENTICATED")||o.extensions?.code==="UNAUTHENTICATED"||o.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 o=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")));o&&typeof o=="string"&&(e.isAuthError=!0,e.errorType="GraphQL Object",e.errorDetails=i.errors,e.shouldTriggerLogout=!0,o.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."):o.includes("TOKEN_HAS_EXPIRED")||o.includes("SESSION_EXPIRED")?(e.isTokenExpired=!0,e.userFriendlyMessage="Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente."):o.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(){I.clearTokens(),C.logout(),this.lastActivityTime=0,this.log("Session cleared completely")}getSessionExpiredMessage(){return this.config.translateFn?me("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 Be,useEffect as ee,useCallback as V}from"react";function ke(r={}){let[i,e]=Be({isAuthenticated:!1,isLoading:!0,isInitialized:!1,tokens:null,error:null}),t=Q.getInstance(),o=V(async()=>{try{e(n=>({...n,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(n=>({...n,isAuthenticated:!1,tokens:null,error:"Session expired"})),r.onSessionExpired?.()},onSessionRestored:n=>{e(y=>({...y,isAuthenticated:!0,tokens:n,error:null})),r.onSessionRestored?.(n)},onLoginSuccess:n=>{e(y=>({...y,isAuthenticated:!0,tokens:n,error:null}))},onLogout:()=>{e(n=>({...n,isAuthenticated:!1,tokens:null,error:null}))}};await t.initialize(c),t.setupResponseInterceptor();let a=t.isAuthenticated(),l=t.getTokenInfo();e(n=>({...n,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=V(async(c,a)=>{e(l=>({...l,isLoading:!0,error:null}));try{let l=await t.login(c,a);return l.success&&l.tokens?e(n=>({...n,isAuthenticated:!0,tokens:l.tokens,isLoading:!1,error:null})):e(n=>({...n,isAuthenticated:!1,tokens:null,isLoading:!1,error:null})),l}catch(l){let n=l instanceof Error?l.message:"Login failed",y=n.includes("INVALID_CREDENTIALS")||n.includes("Invalid email")||n.includes("Invalid password")||n.includes("credentials");return e(E=>({...E,isAuthenticated:!1,tokens:null,isLoading:!1,error:y?null:n})),{success:!1,error:n}}},[t]),d=V(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]),m=V(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]),w=V(()=>{e(c=>({...c,error:null}))},[]),b=V(()=>t.getTokenInfo(),[t]);ee(()=>{o()},[o]),ee(()=>{if(!i.isAuthenticated||!i.tokens)return;let c=Ee.getInstance(),a=()=>{t.updateLastActivity()},l=c.subscribe(a);window.addEventListener("popstate",a);let n=()=>{let L=t.getTokenInfo().crudifyTokens.expiresIn||0;return L<300*1e3?30*1e3:L<1800*1e3?60*1e3:120*1e3},y,E=()=>{let k=n();y=setTimeout(async()=>{if(t.isRefreshing()){E();return}let L=t.getTokenInfo(),x=L.crudifyTokens.expiresIn||0,v=((L.crudifyTokens.expiresAt||0)-(Date.now()-x))*.5;if(x>0&&x<=v)if(e(K=>({...K,isLoading:!0})),await t.refreshTokens()){let K=t.getTokenInfo();e(ae=>({...ae,isLoading:!1,tokens:K.crudifyTokens.accessToken?{accessToken:K.crudifyTokens.accessToken,refreshToken:K.crudifyTokens.refreshToken,expiresAt:K.crudifyTokens.expiresAt,refreshExpiresAt:K.crudifyTokens.refreshExpiresAt}:null}))}else e(K=>({...K,isLoading:!1,isAuthenticated:!1,tokens:null}));let Y=t.getTimeSinceLastActivity(),_=1800*1e3;Y>_?await d():E()},k)};return E(),()=>{clearTimeout(y),window.removeEventListener("popstate",a),l()}},[i.isAuthenticated,i.tokens,t,r.enableLogging,d]),ee(()=>{let c=O.subscribe(async a=>{if(a.type==="TOKEN_EXPIRED"){if(t.isRefreshing())return;e(l=>({...l,isLoading:!0}));try{if(await t.refreshTokens()){let n=t.getTokenInfo();e(y=>({...y,isLoading:!1,tokens:n.crudifyTokens.accessToken?{accessToken:n.crudifyTokens.accessToken,refreshToken:n.crudifyTokens.refreshToken,expiresAt:n.crudifyTokens.expiresAt,refreshExpiresAt:n.crudifyTokens.refreshExpiresAt}:null}))}else O.emit("SESSION_EXPIRED",{message:"Failed to refresh token after detecting expiration",source:"useSession.TOKEN_EXPIRED handler"})}catch(l){O.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")&&(e(l=>({...l,isAuthenticated:!1,tokens:null,isLoading:!1,error:a.details?.message||"Session expired"})),r.onSessionExpired?.())});return()=>c()},[r.onSessionExpired,t]),ee(()=>{let c=I.subscribeToChanges(a=>{a?e(l=>({...l,tokens:a,isAuthenticated:!0})):(e(l=>({...l,isAuthenticated:!1,tokens:null})),O.emit("SESSION_EXPIRED",{message:"Sesi\xF3n cerrada en otra pesta\xF1a",source:"CrossTabSync"}))});return()=>c()},[]);let T=V(()=>{t.updateLastActivity()},[t]);return{...i,login:s,logout:d,refreshTokens:m,clearError:w,getTokenInfo:b,updateActivity:T,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 xe,createContext as Ye,useContext as Xe,useCallback as ie,useEffect as We}from"react";import{Snackbar as Ze,Alert as qe,Box as je,Portal as Je}from"@mui/material";import{v4 as Qe}from"uuid";import ei from"dompurify";import{jsx as B,jsxs as ri}from"react/jsx-runtime";var Se=Ye(null),ii=r=>ei.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}),de=({children:r,maxNotifications:i=5,defaultAutoHideDuration:e=6e3,position:t={vertical:"top",horizontal:"right"},enabled:o=!1,allowHtml:s=!1})=>{let[d,m]=xe([]),w=ie((a,l="info",n)=>{if(!o)return"";if(!a||typeof a!="string")return p.warn("GlobalNotificationProvider: Invalid message provided"),"";a.length>1e3&&(p.warn("GlobalNotificationProvider: Message too long, truncating"),a=a.substring(0,1e3)+"...");let y=Qe(),E={id:y,message:a,severity:l,autoHideDuration:n?.autoHideDuration??e,persistent:n?.persistent??!1,allowHtml:n?.allowHtml??s};return m(k=>[...k.length>=i?k.slice(-(i-1)):k,E]),y},[i,e,o,s]),b=ie(a=>{m(l=>l.filter(n=>n.id!==a))},[]),T=ie(()=>{m([])},[]),c={showNotification:w,hideNotification:b,clearAllNotifications:T};return ri(Se.Provider,{value:c,children:[r,o&&B(Je,{children:B(je,{sx:{position:"fixed",zIndex:9999,[t.vertical]:(t.vertical==="top",24),[t.horizontal]:t.horizontal==="right"||t.horizontal==="left"?24:"50%",...t.horizontal==="center"&&{transform:"translateX(-50%)"},display:"flex",flexDirection:t.vertical==="top"?"column":"column-reverse",gap:1,maxWidth:"400px",width:"auto"},children:d.map(a=>B(ti,{notification:a,onClose:()=>b(a.id)},a.id))})})]})},ti=({notification:r,onClose:i})=>{let[e,t]=xe(!0),o=ie((s,d)=>{d!=="clickaway"&&(t(!1),setTimeout(i,300))},[i]);return We(()=>{if(!r.persistent&&r.autoHideDuration){let s=setTimeout(()=>{o()},r.autoHideDuration);return()=>clearTimeout(s)}},[r.autoHideDuration,r.persistent,o]),B(Ze,{open:e,onClose:o,sx:{position:"relative","& .MuiSnackbarContent-root":{minWidth:"auto"}},TransitionProps:{enter:!0,exit:!0},children:B(qe,{variant:"filled",severity:r.severity,onClose:o,sx:{width:"100%",minWidth:"280px",maxWidth:"400px",wordBreak:"break-word"},children:r.allowHtml?B("span",{dangerouslySetInnerHTML:{__html:ii(r.message)}}):B("span",{children:r.message})})})},we=()=>{let r=Xe(Se);if(!r)throw new Error("useGlobalNotification debe ser usado dentro de un GlobalNotificationProvider");return r};import ni,{createContext as oi,useContext as si,useMemo as fe}from"react";import{Fragment as li,jsx as N,jsxs as H}from"react/jsx-runtime";var Ne=oi(void 0);function Pe({children:r,options:i={},config:e,showNotifications:t=!1,notificationOptions:o={}}){let s;try{let{showNotification:n}=we();s=n}catch{}let d={};try{let n=be();n.isInitialized&&n.adminCredentials&&(d=n.adminCredentials)}catch{}let m=fe(()=>{let n=ce({publicApiKey:e?.publicApiKey,env:e?.env,enableDebug:i?.enableLogging});return{publicApiKey:n.publicApiKey,env:n.env||"prod"}},[e,i?.enableLogging]),w=ni.useMemo(()=>({...i,showNotification:s,apiEndpointAdmin:d.apiEndpointAdmin,apiKeyEndpointAdmin:d.apiKeyEndpointAdmin,publicApiKey:m.publicApiKey,env:m.env,onSessionExpired:()=>{i.onSessionExpired?.()}}),[i,s,d.apiEndpointAdmin,d.apiKeyEndpointAdmin,m]),b=ke(w),T=fe(()=>{let n=ce({publicApiKey:e?.publicApiKey,env:e?.env,appName:e?.appName,logo:e?.logo,loginActions:e?.loginActions,enableDebug:i?.enableLogging});return{publicApiKey:n.publicApiKey,env:n.env,appName:n.appName,loginActions:n.loginActions,logo:n.logo}},[e,i?.enableLogging]),c=fe(()=>{if(!b.tokens?.accessToken||!b.isAuthenticated)return null;try{let n=Te(b.tokens.accessToken);if(n&&n.sub&&n.email&&n.subscriber){let y={_id:n.sub,email:n.email,subscriberKey:n.subscriber};return Object.keys(n).forEach(E=>{["sub","email","subscriber"].includes(E)||(y[E]=n[E])}),y}}catch(n){p.error("Error decoding JWT token for sessionData",n instanceof Error?n:{message:String(n)})}return null},[b.tokens?.accessToken,b.isAuthenticated]),a={...b,sessionData:c,config:T},l={enabled:t,maxNotifications:o.maxNotifications||5,defaultAutoHideDuration:o.defaultAutoHideDuration||6e3,position:o.position||{vertical:"top",horizontal:"right"}};return N(Ne.Provider,{value:a,children:r})}function lt(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?N(Ie,{config:{publicApiKey:r.config.publicApiKey,env:r.config.env||"prod",appName:r.config.appName,loginActions:r.config.loginActions,logo:r.config.logo},children:N(de,{...i,children:N(Pe,{...r})})}):N(de,{...i,children:N(Pe,{...r})})}function ai(){let r=si(Ne);if(r===void 0)throw new Error("useSessionContext must be used within a SessionProvider");return r}function ct(){let r=ai();return r.isInitialized?H("div",{style:{padding:"10px",margin:"10px",border:"1px solid #ccc",borderRadius:"4px",fontSize:"12px",fontFamily:"monospace"},children:[N("h4",{children:"Session Debug Info"}),H("div",{children:[N("strong",{children:"Authenticated:"})," ",r.isAuthenticated?"Yes":"No"]}),H("div",{children:[N("strong",{children:"Loading:"})," ",r.isLoading?"Yes":"No"]}),H("div",{children:[N("strong",{children:"Error:"})," ",r.error||"None"]}),r.tokens&&H(li,{children:[H("div",{children:[N("strong",{children:"Access Token:"})," ",r.tokens.accessToken.substring(0,20),"..."]}),H("div",{children:[N("strong",{children:"Refresh Token:"})," ",r.tokens.refreshToken.substring(0,20),"..."]}),H("div",{children:[N("strong",{children:"Access Expires In:"})," ",Math.round(r.expiresIn/1e3/60)," minutes"]}),H("div",{children:[N("strong",{children:"Refresh Expires In:"})," ",Math.round(r.refreshExpiresIn/1e3/60/60)," hours"]}),H("div",{children:[N("strong",{children:"Expiring Soon:"})," ",r.isExpiringSoon?"Yes":"No"]})]})]}):N("div",{children:"Session not initialized"})}import{useState as te,useEffect as Re,useCallback as Ce,useRef as re}from"react";import ci from"@nocios/crudify-browser";var yt=(r={})=>{let{autoFetch:i=!0,retryOnError:e=!1,maxRetries:t=3}=r,[o,s]=te(null),[d,m]=te(!1),[w,b]=te(null),[T,c]=te({}),a=re(null),l=re(!0),n=re(0),y=re(0),E=Ce(()=>{s(null),b(null),m(!1),c({})},[]),k=Ce(async()=>{let L=ve();if(!L){l.current&&(b("No user email available"),m(!1));return}a.current&&a.current.abort();let x=new AbortController;a.current=x;let P=++n.current;try{l.current&&(m(!0),b(null));let M=await ci.readItems("users",{filter:{email:L},pagination:{limit:1}});if(P===n.current&&l.current&&!x.signal.aborted)if(M.success&&M.data&&M.data.length>0){let v=M.data[0];s(v);let Y={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(_=>!["id","email","username","firstName","lastName","fullName","role","permissions","isActive","lastLogin","createdAt","updatedAt"].includes(_)).reduce((_,X)=>({..._,[X]:v[X]}),{})}};c(Y),b(null),y.current=0}else b("User profile not found"),s(null),c({})}catch(M){if(P===n.current&&l.current){let v=M;if(v.name==="AbortError")return;e&&y.current<t&&(v.message?.includes("Network Error")||v.message?.includes("Failed to fetch"))?(y.current++,setTimeout(()=>{l.current&&k()},1e3*y.current)):(b("Failed to load user profile"),s(null),c({}))}}finally{P===n.current&&l.current&&m(!1),a.current===x&&(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:o,loading:d,error:w,extendedData:T,refreshProfile:k,clearProfile:E}};import{useState as pe,useEffect as ui,useCallback as ne,useRef as di}from"react";import fi from"@nocios/crudify-browser";var Tt=(r,i={})=>{let{autoFetch:e=!0,onSuccess:t,onError:o}=i,{prefix:s,padding:d=0,separator:m=""}=r,[w,b]=pe(""),[T,c]=pe(!1),[a,l]=pe(null),n=di(!1),y=ne(x=>{let P=String(x).padStart(d,"0");return`${s}${m}${P}`},[s,d,m]),E=ne(async()=>{c(!0),l(null);try{let x=await fi.getNextSequence(s);if(x.success&&x.data?.value){let P=y(x.data.value);b(P),t?.(P)}else{let P=x.errors?._error?.[0]||"Failed to generate code";l(P),o?.(P)}}catch(x){let P=x instanceof Error?x.message:"Unknown error";l(P),o?.(P)}finally{c(!1)}},[s,y,t,o]),k=ne(async()=>{await E()},[E]),L=ne(()=>{l(null)},[]);return ui(()=>{e&&!w&&!n.current&&(n.current=!0,E())},[e,w,E]),{value:w,loading:T,error:a,regenerate:k,clearError:L}};import ge from"@nocios/crudify-browser";var ye=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:o,enableLogging:s,requestedBy:d}=i;if(this.state.status==="INITIALIZED"){this.state.publicApiKey!==t&&p.warn(`[CrudifyInitialization] ${d} attempted to initialize with different key. Already initialized with key: ${this.state.publicApiKey?.slice(0,10)}... by ${this.state.initializedBy}`);return}if(this.initializationPromise)return s&&p.debug(`[CrudifyInitialization] ${d} waiting for ongoing initialization...`),this.initializationPromise;if(e==="LOW"&&this.highPriorityInitializerPresent&&this.state.status==="UNINITIALIZED"){if(s&&p.debug(`[CrudifyInitialization] ${d} (LOW priority) waiting for HIGH priority initializer...`),this.waitingForHighPriority.add(d),await this.waitForHighPriorityOrTimeout(s),this.waitingForHighPriority.delete(d),this.getState().status==="INITIALIZED"){s&&p.debug(`[CrudifyInitialization] ${d} found initialization completed by HIGH priority`);return}s&&p.warn(`[CrudifyInitialization] ${d} timeout waiting for HIGH priority, initializing with LOW priority`)}e==="HIGH"&&this.state.status==="INITIALIZING"&&this.state.priority==="LOW"&&(p.warn(`[CrudifyInitialization] HIGH priority request from ${d} interrupting LOW priority initialization by ${this.state.initializedBy}`),this.state.status="UNINITIALIZED",this.initializationPromise=null),s&&p.debug(`[CrudifyInitialization] ${d} starting initialization (${e} priority)...`),this.state.status="INITIALIZING",this.state.priority=e,this.state.initializedBy=d,this.initializationPromise=this.performInitialization(t,o,s);try{await this.initializationPromise,this.state.status="INITIALIZED",this.state.publicApiKey=t,this.state.env=o,this.state.error=null,s&&p.info(`[CrudifyInitialization] Successfully initialized by ${d} (${e} priority)`)}catch(m){throw this.state.status="ERROR",this.state.error=m instanceof Error?m:new Error(String(m)),this.initializationPromise=null,p.error(`[CrudifyInitialization] Initialization failed for ${d}`,m instanceof Error?m:{message:String(m)}),m}}async waitForHighPriorityOrTimeout(i){return new Promise(e=>{let o=0,s=setInterval(()=>{if(o+=10,this.state.status==="INITIALIZED"&&this.state.priority==="HIGH"){clearInterval(s),e();return}if(this.state.status==="INITIALIZING"&&this.state.priority==="HIGH"){o=0;return}o>=this.HIGH_PRIORITY_WAIT_TIMEOUT&&(clearInterval(s),i&&p.debug(`[CrudifyInitialization] Timeout waiting for HIGH priority (${this.HIGH_PRIORITY_WAIT_TIMEOUT}ms)`),e())},10)})}async performInitialization(i,e,t){let o=ge.getTokenData();if(o&&o.endpoint){t&&p.debug("[CrudifyInitialization] SDK already initialized externally");return}ge.config(e);let s=t?"debug":"none",d=await ge.init(i,s);if(d.success===!1)throw new Error(`Crudify initialization failed: ${JSON.stringify(d.errors||"Unknown error")}`);d.apiEndpointAdmin&&d.apiKeyEndpointAdmin&&j.notifyCredentialsReady({apiUrl:d.apiEndpointAdmin,apiKey:d.apiKeyEndpointAdmin})}reset(){this.state={status:"UNINITIALIZED",priority:null,publicApiKey:null,env:null,error:null,initializedBy:null},this.initializationPromise=null,this.highPriorityInitializerPresent=!1,this.waitingForHighPriority.clear()}isInitialized(){return this.state.status==="INITIALIZED"}getDiagnostics(){return{...this.state,waitingCount:this.waitingForHighPriority.size,waitingComponents:Array.from(this.waitingForHighPriority),hasActivePromise:this.initializationPromise!==null}}},oe=ye.getInstance();import{useState as Le,useCallback as z,useRef as pi,useMemo as se}from"react";import he from"@nocios/crudify-browser";var De=()=>`file_${Date.now()}_${Math.random().toString(36).substring(2,9)}`,gi=r=>{let i=r.lastIndexOf("."),e=i>0?r.substring(i):"",t=Date.now(),o=Math.random().toString(36).substring(2,8);return`${t}_${o}${e}`},Nt=(r={})=>{let{acceptedTypes:i,maxFileSize:e=10*1024*1024,maxFiles:t,minFiles:o=0,visibility:s="private",onUploadComplete:d,onUploadError:m,onFileRemoved:w,onFilesChange:b}=r,[T,c]=Le([]),[a,l]=Le(!1),n=pi(new Map),y=z(()=>{l(!0)},[]),E=z((u,h)=>{c(g=>g.map(A=>A.id===u?{...A,...h}:A))},[]),k=z(u=>{b?.(u)},[b]),L=z(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]),x=z(async(u,h)=>{try{if(!oe.isInitialized())throw new Error("Crudify is not initialized. Please wait for the application to finish loading.");let g=gi(h.name),S=await he.generateSignedUrl({fileName:g,contentType:h.type,visibility:s});if(!S.success||!S.data)throw new Error("Failed to get upload URL");let{uploadUrl:A,s3Key:R,publicUrl:D}=S.data;if(!A||!R)throw new Error("Incomplete signed URL response");let U=R.indexOf("/"),W=U>0?R.substring(U+1):R;E(u.id,{status:"uploading",progress:0}),await new Promise((le,$)=>{let F=new XMLHttpRequest;F.upload.addEventListener("progress",G=>{if(G.lengthComputable){let Me=Math.round(G.loaded/G.total*100);E(u.id,{progress:Me})}}),F.addEventListener("load",()=>{F.status>=200&&F.status<300?le():$(new Error(`Upload failed with status ${F.status}`))}),F.addEventListener("error",()=>{$(new Error("Network error during upload"))}),F.addEventListener("abort",()=>{$(new Error("Upload cancelled"))}),F.open("PUT",A),F.setRequestHeader("Content-Type",h.type),F.send(h)});let He={status:"completed",progress:100,filePath:W,visibility:s,publicUrl:s==="public"?D:void 0,file:void 0};c(le=>{let $=le.map(G=>G.id===u.id?{...G,...He}:G);k($);let F=$.find(G=>G.id===u.id);return F&&d?.(F),$})}catch(g){let S=g instanceof Error?g.message:"Unknown error";E(u.id,{status:"error",progress:0,errorMessage:S}),c(A=>{let R=A.find(D=>D.id===u.id);return R&&m?.(R,S),A})}},[E,d,m,s]),P=z(async u=>{let h=Array.from(u),g=[];c(S=>{if(t!==void 0){let D=S.filter(W=>W.status!=="error").length,U=t-D;if(U<=0)return p.warn(`File limit of ${t} already reached`),S;h.length>U&&(h=h.slice(0,U),p.warn(`Only ${U} files will be added to not exceed limit`))}let A=[];for(let D of h){let U=L(D),W={id:De(),name:D.name,size:D.size,contentType:D.type,status:U.valid?"pending":"error",progress:0,createdAt:Date.now(),file:U.valid?D:void 0,errorMessage:U.error};A.push(W)}g=A;let R=[...S,...A];return k(R),R}),setTimeout(()=>{let S=g.filter(A=>A.status==="pending"&&A.file);for(let A of S)if(A.file){let R=x(A,A.file);n.current.set(A.id,R),R.finally(()=>{n.current.delete(A.id)})}},0)},[t,L,x,k]),M=z(async u=>{let h=T.find(g=>g.id===u);if(!h)return!1;E(u,{status:"removing"});try{if(h.filePath){if(!oe.isInitialized())throw new Error("Crudify is not initialized. Please wait for the application to finish loading.");if(!(await he.disableFile({filePath:h.filePath})).success)throw new Error("Failed to remove file from server")}return c(g=>{let S=g.filter(A=>A.id!==u);return k(S),S}),w?.(h),!0}catch(g){return E(u,{status:h.filePath?"completed":"error",errorMessage:g instanceof Error?g.message:"Error removing file"}),!1}},[T,E,k,w]),v=z(()=>{c([]),k([])},[k]),Y=z(async u=>{let h=T.find(S=>S.id===u);if(!h||h.status!=="error"||!h.file){p.warn("Cannot retry: file not found or no original file");return}E(u,{status:"pending",progress:0,errorMessage:void 0});let g=x(h,h.file);n.current.set(u,g),g.finally(()=>{n.current.delete(u)})},[T,E,x]),_=z(async()=>{let u=Array.from(n.current.values());u.length>0&&await Promise.allSettled(u)},[]),X=u=>{let h=u.split(".").pop()?.toLowerCase()||"";return{jpg:"image/jpeg",jpeg:"image/jpeg",png:"image/png",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",bmp:"image/bmp",ico:"image/x-icon",pdf:"application/pdf",doc:"application/msword",docx:"application/vnd.openxmlformats-officedocument.wordprocessingml.document",xls:"application/vnd.ms-excel",xlsx:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",ppt:"application/vnd.ms-powerpoint",pptx:"application/vnd.openxmlformats-officedocument.presentationml.presentation",txt:"text/plain",csv:"text/csv",mp3:"audio/mpeg",wav:"audio/wav",mp4:"video/mp4",webm:"video/webm",zip:"application/zip",rar:"application/x-rar-compressed",json:"application/json",xml:"application/xml"}[h]||"application/octet-stream"},K=z(u=>{let h=u.map(g=>{let A=g.filePath.startsWith("http://")||g.filePath.startsWith("https://")?new URL(g.filePath).pathname:g.filePath,R=A.includes("/public/")||A.startsWith("public/")?"public":"private",D=g.contentType||X(g.name);return{id:De(),name:g.name,size:g.size||0,contentType:D,status:"completed",progress:100,filePath:g.filePath,visibility:R,createdAt:Date.now()}});c(h),k(h)},[k]),ae=z(async u=>{let h=T.find(g=>g.id===u);if(!h||!h.filePath)return null;if(h.visibility==="public"&&h.publicUrl)return h.publicUrl;try{if(!oe.isInitialized())return null;let g=await he.getFileUrl({filePath:h.filePath,expiresIn:3600});return g.success&&g.data?.url?g.data.url:null}catch{return null}},[T]),Fe=se(()=>T.some(u=>u.status==="uploading"||u.status==="pending"),[T]),ze=se(()=>T.filter(u=>u.status==="uploading"||u.status==="pending").length,[T]),Ke=se(()=>T.filter(u=>u.status==="completed"&&u.filePath).map(u=>u.filePath),[T]),{isValid:Ue,validationError:Oe}=se(()=>{let u=T.filter(g=>g.status==="completed").length;return u<o?{isValid:!1,validationError:o===1?"At least one file is required":`At least ${o} files are required`}:t!==void 0&&u>t?{isValid:!1,validationError:`Maximum ${t} files allowed`}:T.some(g=>g.status==="error")?{isValid:!1,validationError:"Some files have errors"}:{isValid:!0,validationError:null}},[T,o,t]);return{files:T,isUploading:Fe,pendingCount:ze,addFiles:P,removeFile:M,clearFiles:v,retryUpload:Y,isValid:Ue,validationError:Oe,waitForUploads:_,completedFilePaths:Ke,initializeFiles:K,isTouched:a,markAsTouched:y,getPreviewUrl:ae}};export{j as a,Ie as b,be as c,I as d,Q as e,ke as f,de as g,we as h,lt as i,ai as j,ct as k,yt as l,Tt as m,ye as n,oe as o,Nt as p};
|