@nocios/crudify-ui 5.0.34 → 5.0.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/chunk-36AFCLOP.mjs +1 -0
- package/dist/{chunk-AN7YGJ4Y.mjs → chunk-3TIUUDDO.mjs} +1 -1
- package/dist/{chunk-3CHTFEQP.mjs → chunk-C2BVDP4U.mjs} +1 -1
- package/dist/chunk-GFPLE6JY.js +1 -0
- package/dist/{chunk-D5C47TXS.js → chunk-MUUOVMDY.js} +1 -1
- package/dist/{chunk-6RAYJV6M.js → chunk-WT22TBLW.js} +1 -1
- package/dist/components.js +1 -1
- package/dist/components.mjs +1 -1
- package/dist/hooks.js +1 -1
- package/dist/hooks.mjs +1 -1
- package/dist/index.js +2 -2
- package/dist/index.mjs +2 -2
- package/package.json +1 -1
- package/dist/chunk-6UUAR5KP.js +0 -1
- package/dist/chunk-L664MA74.mjs +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a as p,c as ge,e as M,f as Ae,g as Ie,h as ke,i as xe,j as we,k as Re,l as Pe,p as Ne,q as Ce,r as De}from"./chunk-MGJZTOEM.mjs";var Le="crudify_storage_version",Oe=2,a=class a{static setStorageType(t){a.storageType=t}static async initialize(){if(!(a.encryptionKey&&a.salt))return a.initPromise||(a.initPromise=(async()=>{try{a.checkStorageVersion(),a.salt=a.getOrCreateSalt(),a.fingerprint=await a.generateFingerprint(),a.encryptionKey=await Ie(a.fingerprint,a.salt)}catch(t){throw p.error("Crudify: Failed to initialize encryption",t instanceof Error?t:{message:String(t)}),t}})()),a.initPromise}static checkStorageVersion(){try{if(parseInt(localStorage.getItem(Le)||"1",10)<Oe){let e=a.getStorage();e&&e.removeItem(a.TOKEN_KEY),localStorage.removeItem(a.ENCRYPTION_KEY_STORAGE),localStorage.removeItem(a.SALT_KEY),localStorage.setItem(Le,Oe.toString()),p.info("Crudify: Storage upgraded to v2, tokens cleared for security")}}catch{}}static getOrCreateSalt(){try{let e=localStorage.getItem(a.SALT_KEY);if(e){let i=atob(e),n=new Uint8Array(i.length);for(let o=0;o<i.length;o++)n[o]=i.charCodeAt(o);return n}}catch{}let t=we();try{let e="";for(let i=0;i<t.length;i++)e+=String.fromCharCode(t[i]);localStorage.setItem(a.SALT_KEY,btoa(e))}catch{p.warn("Crudify: Cannot persist salt, encryption may not persist across sessions")}return t}static async generateFingerprint(){let t=new Uint8Array(16);crypto.getRandomValues(t);let e=Array.from(t,o=>o.toString(16).padStart(2,"0")).join(""),i=[navigator.userAgent,navigator.language,navigator.platform,screen.width,screen.height,e].join("|");try{let o=localStorage.getItem(a.ENCRYPTION_KEY_STORAGE);if(o&&o.length>=32)return o}catch{}let n=await Ae(i);try{localStorage.setItem(a.ENCRYPTION_KEY_STORAGE,n)}catch{p.warn("Crudify: Cannot persist encryption key hash")}return n}static isStorageAvailable(t){try{let e=window[t],i="__storage_test__";return e.setItem(i,"test"),e.removeItem(i),!0}catch{return!1}}static getStorage(){return a.storageType==="none"?null:a.isStorageAvailable(a.storageType)?window[a.storageType]:(p.warn(`Crudify: ${a.storageType} not available, tokens won't persist`),null)}static async encryptData(t){if(await a.initialize(),!a.encryptionKey||!a.salt)throw new Error("Encryption not initialized");return ke(t,a.encryptionKey,a.salt)}static async decryptData(t){if(await a.initialize(),!a.fingerprint)throw new Error("Encryption not initialized");return Re(t)?xe(t,a.fingerprint):(p.warn("Crudify: Legacy encrypted data detected, cannot decrypt"),null)}static async saveTokens(t){let e=a.getStorage();if(e)try{let i={accessToken:t.accessToken,refreshToken:t.refreshToken,expiresAt:t.expiresAt,refreshExpiresAt:t.refreshExpiresAt,savedAt:Date.now()},n=await a.encryptData(JSON.stringify(i));e.setItem(a.TOKEN_KEY,n),p.debug("Crudify: Tokens saved successfully")}catch(i){p.error("Crudify: Failed to save tokens",i instanceof Error?i:{message:String(i)})}}static async getTokens(){let t=a.getStorage();if(!t)return null;try{let e=t.getItem(a.TOKEN_KEY);if(!e)return null;let i=await a.decryptData(e);if(!i)return p.warn("Crudify: Failed to decrypt tokens, clearing storage"),await a.clearTokens(),null;let n=JSON.parse(i);return!n.accessToken||!n.refreshToken||!n.expiresAt||!n.refreshExpiresAt?(p.warn("Crudify: Incomplete token data found, clearing storage"),await a.clearTokens(),null):Date.now()>=n.refreshExpiresAt?(p.info("Crudify: Refresh token expired, clearing storage"),await a.clearTokens(),null):{accessToken:n.accessToken,refreshToken:n.refreshToken,expiresAt:n.expiresAt,refreshExpiresAt:n.refreshExpiresAt}}catch(e){return p.error("Crudify: Failed to retrieve tokens",e instanceof Error?e:{message:String(e)}),await a.clearTokens(),null}}static async clearTokens(){let t=a.getStorage();if(t)try{t.removeItem(a.TOKEN_KEY),p.debug("Crudify: Tokens cleared from storage")}catch(e){p.error("Crudify: Failed to clear tokens",e instanceof Error?e:{message:String(e)})}}static async rotateEncryptionKey(){try{await a.clearTokens(),a.encryptionKey=null,a.salt=null,a.fingerprint=null,a.initPromise=null;try{localStorage.removeItem(a.ENCRYPTION_KEY_STORAGE),localStorage.removeItem(a.SALT_KEY)}catch{}p.info("Crudify: Encryption key rotated successfully")}catch(t){p.error("Crudify: Failed to rotate encryption key",t instanceof Error?t:{message:String(t)})}}static async hasValidTokens(){return await a.getTokens()!==null}static async getExpirationInfo(){let t=await a.getTokens();if(!t)return null;let e=Date.now();return{accessExpired:e>=t.expiresAt,refreshExpired:e>=t.refreshExpiresAt,accessExpiresIn:Math.max(0,t.expiresAt-e),refreshExpiresIn:Math.max(0,t.refreshExpiresAt-e)}}static async updateAccessToken(t,e){let i=await a.getTokens();if(!i){p.warn("Crudify: Cannot update access token, no existing tokens found");return}await a.saveTokens({...i,accessToken:t,expiresAt:e})}static createSyncEvent(t,e,i){return{type:t,tokens:e,hadPreviousTokens:i}}static subscribeToChanges(t){let e=async i=>{if(i.key!==a.TOKEN_KEY)return;let n=i.oldValue!==null&&i.oldValue!=="";if(i.newValue===null){p.debug("Crudify: Tokens removed in another tab"),t(null,a.SYNC_EVENTS.TOKENS_CLEARED,n);return}if(i.newValue){p.debug("Crudify: Tokens updated in another tab");let o=await a.getTokens();t(o,a.SYNC_EVENTS.TOKENS_UPDATED,n)}};return window.addEventListener("storage",e),()=>{window.removeEventListener("storage",e)}}};a.TOKEN_KEY="crudify_tokens",a.ENCRYPTION_KEY_STORAGE="crudify_enc_key",a.SALT_KEY="crudify_enc_salt",a.encryptionKey=null,a.salt=null,a.fingerprint=null,a.storageType="localStorage",a.initPromise=null,a.SYNC_EVENTS={TOKENS_CLEARED:"TOKENS_CLEARED",TOKENS_UPDATED:"TOKENS_UPDATED"};var I=a;import L from"@nocios/crudify-browser";var ie=class r{constructor(){this.config={};this.initialized=!1;this.crudifyInitialized=!1;this.lastActivityTime=0;this.isRefreshingLocally=!1;this.refreshPromise=null}static getInstance(){return r.instance||(r.instance=new r),r.instance}async initialize(t={}){if(!this.initialized){if(this.config={storageType:"localStorage",autoRestore:!0,enableLogging:!1,env:"stg",...t},I.setStorageType(this.config.storageType||"localStorage"),this.config.publicApiKey&&!this.crudifyInitialized&&await this.ensureCrudifyInitialized(),L.setTokenInvalidationCallback(()=>{this.log("Tokens invalidated by crudify-core"),M.emit("SESSION_EXPIRED",{message:"Your session has expired. Please log in again.",source:"crudify-core.clearTokensAndRefreshState"})}),this.config.apiEndpointAdmin&&this.config.apiKeyEndpointAdmin){let e=await I.getTokens();e?await I.saveTokens({...e,apiEndpointAdmin:this.config.apiEndpointAdmin,apiKeyEndpointAdmin:this.config.apiKeyEndpointAdmin}):await 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(t,e){try{let i=await L.login(t,e);if(!i.success)return{success:!1,error:this.formatError(i.errors),rawResponse:i};let n=await I.getTokens(),o=i.data,c={accessToken:o.token,refreshToken:o.refreshToken,expiresAt:o.expiresAt,refreshExpiresAt:o.refreshExpiresAt,apiEndpointAdmin:n?.apiEndpointAdmin||this.config.apiEndpointAdmin,apiKeyEndpointAdmin:n?.apiKeyEndpointAdmin||this.config.apiKeyEndpointAdmin};return await I.saveTokens(c),this.lastActivityTime=Date.now(),this.config.onLoginSuccess?.(c),{success:!0,tokens:c,data:o}}catch(i){return p.error("[SessionManager] Login error",i instanceof Error?i:{message:String(i)}),{success:!1,error:i instanceof Error?i.message:"Unknown error"}}}async logout(){try{this.log("Logging out..."),M.emit("LOGOUT",{message:"User logged out",source:"SessionManager.logout"}),await L.logout(),await I.clearTokens(),this.log("Logout successful"),this.config.onLogout?.()}catch(t){this.log("Logout error",{error:t instanceof Error?t.message:String(t)}),await I.clearTokens()}}async restoreSession(){try{this.log("Attempting to restore session...");let t=await I.getTokens();if(!t)return this.log("No valid tokens found in storage"),!1;if(Date.now()>=t.refreshExpiresAt)return this.log("Refresh token expired, clearing storage"),await I.clearTokens(),!1;if(L.setTokens({accessToken:t.accessToken,refreshToken:t.refreshToken,expiresAt:t.expiresAt,refreshExpiresAt:t.refreshExpiresAt}),L.getTokenData().isValid===!1){if(this.log("Restored access token is invalid or expired"),Date.now()<t.refreshExpiresAt&&(this.log("Access token expired but refresh is valid, attempting refresh..."),await this.refreshTokens())){this.log("Session restored successfully via token refresh");let n=await I.getTokens();return n&&this.config.onSessionRestored?.(n),!0}return await I.clearTokens(),await L.logout(),!1}return this.log("Session restored successfully"),this.lastActivityTime=Date.now(),this.config.onSessionRestored?.(t),!0}catch(t){return this.log("Session restore error",{error:t instanceof Error?t.message:String(t)}),await I.clearTokens(),await L.logout(),!1}}async isAuthenticated(){return L.isLogin()||await I.hasValidTokens()}async getTokenInfo(){let t=L.getTokenData(),e=await I.getExpirationInfo(),i=await I.getTokens();return{isLoggedIn:await this.isAuthenticated(),crudifyTokens:t,storageInfo:e,hasValidTokens:await I.hasValidTokens(),apiEndpointAdmin:i?.apiEndpointAdmin,apiKeyEndpointAdmin:i?.apiKeyEndpointAdmin}}async refreshTokens(){if(this.isRefreshingLocally&&this.refreshPromise)return this.log("Refresh already in progress, waiting for existing promise..."),this.refreshPromise;this.isRefreshingLocally=!0,this.refreshPromise=this._performRefresh();try{return await this.refreshPromise}finally{this.isRefreshingLocally=!1,this.refreshPromise=null}}async _performRefresh(){try{this.log("Starting token refresh...");let t=await L.refreshAccessToken();if(!t.success)return this.log("Token refresh failed",{errors:t.errors}),await I.clearTokens(),this.config.showNotification?.(this.getSessionExpiredMessage(),"warning"),this.config.onSessionExpired?.(),!1;let e=t.data,i={accessToken:e.token,refreshToken:e.refreshToken,expiresAt:e.expiresAt,refreshExpiresAt:e.refreshExpiresAt};return await I.saveTokens(i),this.log("Tokens refreshed and saved successfully"),this.lastActivityTime=Date.now(),!0}catch(t){return this.log("Token refresh error",{error:t instanceof Error?t.message:String(t)}),await I.clearTokens(),this.config.showNotification?.(this.getSessionExpiredMessage(),"warning"),this.config.onSessionExpired?.(),!1}}isRefreshing(){return this.isRefreshingLocally}setupResponseInterceptor(){L.setResponseInterceptor(async t=>{this.updateLastActivity();let e=this.detectAuthorizationError(t);if(e.isAuthError){if(this.log("\u{1F6A8} Authorization error detected:",{errorType:e.errorType,shouldLogout:e.shouldTriggerLogout}),e.isRefreshTokenInvalid||e.isTokenRefreshFailed)return this.log("Refresh token invalid, emitting TOKEN_REFRESH_FAILED event"),M.emit("TOKEN_REFRESH_FAILED",{message:e.userFriendlyMessage,error:e.errorDetails,source:"SessionManager.setupResponseInterceptor"}),t;e.shouldTriggerLogout&&(await I.hasValidTokens()&&!e.isIrrecoverable?(this.log("Access token expired, emitting TOKEN_EXPIRED event"),M.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"),M.emit("SESSION_EXPIRED",{message:e.userFriendlyMessage,error:e.errorDetails,source:"SessionManager.setupResponseInterceptor"})))}return t}),this.log("Response interceptor configured (non-blocking mode)")}async ensureCrudifyInitialized(){if(!this.crudifyInitialized)try{this.log("Initializing crudify SDK...");let t=L.getTokenData();if(t&&t.endpoint){this.log("Crudify already initialized by another service"),this.crudifyInitialized=!0;return}let e=this.config.env||"stg";L.config(e);let i=this.config.publicApiKey,n=this.config.enableLogging?"debug":"none",o=await L.init(i,n);if(o&&o.success===!1&&o.errors)throw new Error(`Failed to initialize crudify: ${JSON.stringify(o.errors)}`);this.crudifyInitialized=!0,this.log("Crudify SDK initialized successfully")}catch(t){throw p.error("[SessionManager] Failed to initialize crudify",t instanceof Error?t:{message:String(t)}),t}}detectAuthorizationError(t){let e={isAuthError:!1,isRefreshTokenInvalid:!1,isTokenRefreshFailed:!1,isTokenExpired:!1,isUnauthorized:!1,isIrrecoverable:!1,shouldTriggerLogout:!1,errorType:"",errorDetails:null,userFriendlyMessage:""};if(t.errors&&Array.isArray(t.errors)){let i=t.errors.find(n=>n.errorType==="Unauthorized"||n.message?.includes("Unauthorized")||n.message?.includes("Not Authorized")||n.message?.includes("NOT_AUTHORIZED")||n.message?.includes("Token")||n.message?.includes("TOKEN")||n.message?.includes("Authentication")||n.message?.includes("UNAUTHENTICATED")||n.extensions?.code==="UNAUTHENTICATED"||n.extensions?.code==="FORBIDDEN");i&&(e.isAuthError=!0,e.errorType="GraphQL Array",e.errorDetails=i,e.shouldTriggerLogout=!0,e.userFriendlyMessage="Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente.",(i.message?.includes("TOKEN")||i.message?.includes("Token"))&&(e.isTokenExpired=!0),i.extensions?.code==="UNAUTHENTICATED"&&(e.isUnauthorized=!0))}if(!e.isAuthError&&t.errors&&typeof t.errors=="object"&&!Array.isArray(t.errors)){let n=Object.values(t.errors).flat().find(o=>typeof o=="string"&&(o.includes("NOT_AUTHORIZED")||o.includes("TOKEN_REFRESH_FAILED")||o.includes("TOKEN_HAS_EXPIRED")||o.includes("PLEASE_LOGIN")||o.includes("Unauthorized")||o.includes("UNAUTHENTICATED")||o.includes("SESSION_EXPIRED")||o.includes("INVALID_TOKEN")));n&&typeof n=="string"&&(e.isAuthError=!0,e.errorType="GraphQL Object",e.errorDetails=t.errors,e.shouldTriggerLogout=!0,n.includes("TOKEN_REFRESH_FAILED")?(e.isTokenRefreshFailed=!0,e.isRefreshTokenInvalid=!0,e.isIrrecoverable=!0,e.userFriendlyMessage="Tu sesi\xF3n ha caducado. Por favor, inicia sesi\xF3n nuevamente."):n.includes("TOKEN_HAS_EXPIRED")||n.includes("SESSION_EXPIRED")?(e.isTokenExpired=!0,e.userFriendlyMessage="Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente."):n.includes("INVALID_TOKEN")?(e.isTokenExpired=!0,e.isIrrecoverable=!0,e.userFriendlyMessage="Token inv\xE1lido. Por favor, inicia sesi\xF3n nuevamente."):e.userFriendlyMessage="Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente.")}if(!e.isAuthError&&t.data?.response?.status){let i=t.data.response.status.toUpperCase();(i==="UNAUTHORIZED"||i==="UNAUTHENTICATED")&&(e.isAuthError=!0,e.errorType="Status",e.errorDetails=t.data.response,e.isUnauthorized=!0,e.shouldTriggerLogout=!0,e.isIrrecoverable=!0,e.userFriendlyMessage="Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente.")}if(!e.isAuthError&&t.data?.response?.data)try{let i=typeof t.data.response.data=="string"?JSON.parse(t.data.response.data):t.data.response.data;(i.error==="REFRESH_TOKEN_INVALID"||i.error==="TOKEN_EXPIRED"||i.error==="INVALID_TOKEN")&&(e.isAuthError=!0,e.errorType="Parsed Data",e.errorDetails=i,e.shouldTriggerLogout=!0,e.isIrrecoverable=!0,i.error==="REFRESH_TOKEN_INVALID"?(e.isRefreshTokenInvalid=!0,e.isTokenRefreshFailed=!0,e.userFriendlyMessage="Tu sesi\xF3n ha caducado. Por favor, inicia sesi\xF3n nuevamente."):(e.isTokenExpired=!0,e.userFriendlyMessage="Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente."))}catch{}if(!e.isAuthError&&t.errorCode){let i=String(t.errorCode).toUpperCase();(i==="UNAUTHORIZED"||i==="UNAUTHENTICATED"||i==="TOKEN_EXPIRED"||i==="INVALID_TOKEN")&&(e.isAuthError=!0,e.errorType="Error Code",e.errorDetails={errorCode:i},e.shouldTriggerLogout=!0,i==="TOKEN_EXPIRED"?e.isTokenExpired=!0:e.isUnauthorized=!0,e.userFriendlyMessage="Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente.")}return e}updateLastActivity(){this.lastActivityTime=Date.now(),this.log("Last activity updated")}getTimeSinceLastActivity(){return this.lastActivityTime===0?0:Date.now()-this.lastActivityTime}checkInactivity(){let t=this.getTimeSinceLastActivity();if(this.lastActivityTime===0)return"none";let e=1800*1e3;return t>e?(this.log(`Inactivity timeout: ${Math.floor(t/6e4)} minutes since last activity`),"logout"):"none"}async clearSession(){await I.clearTokens(),await L.logout(),this.lastActivityTime=0,this.log("Session cleared completely")}getSessionExpiredMessage(){return this.config.translateFn?Pe("SESSION_EXPIRED",{translateFn:this.config.translateFn,enableDebug:this.config.enableLogging}):"Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente."}log(t,e){this.config.enableLogging&&p.debug(`[SessionManager] ${t}`,e)}formatError(t){return t?typeof t=="string"?t:typeof t=="object"?Object.values(t).flat().map(String).join(", "):"Authentication failed":"Unknown error"}};import{useEffect as Ft,useCallback as Z}from"react";import{useState as wt,useCallback as j}from"react";var Fe={isAuthenticated:!1,isLoading:!0,isLoggingOut:!1,isInitialized:!1,tokens:null,error:null};function Ue(){let[r,t]=wt(Fe),e=j(s=>{t(d=>({...d,isLoading:s}))},[]),i=j((s,d)=>{console.error("[useSessionState.setAuthenticated] Called with:",{isAuthenticated:s,hasTokens:!!d}),t(g=>(console.error("[useSessionState.setAuthenticated] prev state:",{isAuthenticated:g.isAuthenticated,isLoggingOut:g.isLoggingOut,isInitialized:g.isInitialized}),{...g,isAuthenticated:s,tokens:d,error:s?null:g.error}))},[]),n=j(s=>{t(d=>({...d,isLoggingOut:s}))},[]),o=j(s=>{t(d=>({...d,error:s}))},[]),c=j(s=>{t(d=>({...d,isInitialized:s}))},[]);return{state:r,setState:t,setLoading:e,setAuthenticated:i,setLoggingOut:n,setError:o,setInitialized:c}}import{useCallback as ne}from"react";var re={AGGRESSIVE:3e4,MODERATE:6e4,RELAXED:12e4},pe={AGGRESSIVE:300*1e3,MODERATE:1800*1e3},ze=.5;function Ke(r){return r?r.expiresAt-Date.now()<3e5:!1}function Me(r){return r?Math.max(0,r.expiresAt-Date.now()):0}function He(r){return r?Math.max(0,r.refreshExpiresAt-Date.now()):0}function V(r){return r.crudifyTokens.accessToken?{accessToken:r.crudifyTokens.accessToken,refreshToken:r.crudifyTokens.refreshToken||"",expiresAt:r.crudifyTokens.expiresAt,refreshExpiresAt:r.crudifyTokens.refreshExpiresAt}:null}function _e(r){let{sessionManager:t,stateManager:e}=r,i=ne(async(s,d)=>{console.error("[useSessionActions.login] 1. Starting login, setting isLoggingOut=false"),e.setState(g=>(console.error("[useSessionActions.login] 2. setState - prev.isLoggingOut:",g.isLoggingOut),{...g,isLoading:!0,isLoggingOut:!1,error:null}));try{let g=await t.login(s,d);return console.error("[useSessionActions.login] 3. Login result:",{success:g.success,hasTokens:!!g.tokens}),g.success&&g.tokens?(console.error("[useSessionActions.login] 4. Login SUCCESS - setting isAuthenticated=true, isLoggingOut=false"),e.setState(v=>({...v,isAuthenticated:!0,tokens:g.tokens,isLoading:!1,isLoggingOut:!1,error:null}))):e.setState(v=>({...v,isAuthenticated:!1,tokens:null,isLoading:!1,isLoggingOut:!1,error:null})),g}catch(g){let v=g instanceof Error?g.message:"Login failed";p.error("[useSession] Login error",g instanceof Error?g:{message:v});let T=v.includes("INVALID_CREDENTIALS")||v.includes("Invalid email")||v.includes("Invalid password")||v.includes("credentials");return e.setState(y=>({...y,isAuthenticated:!1,tokens:null,isLoading:!1,isLoggingOut:!1,error:T?null:v})),{success:!1,error:v}}},[t,e]),n=ne(async()=>{e.setState(s=>({...s,isLoading:!0,isLoggingOut:!0}));try{await t.logout(),e.setState(s=>({...s,isAuthenticated:!1,tokens:null,isLoading:!1,error:null}))}catch(s){e.setState(d=>({...d,isAuthenticated:!1,tokens:null,isLoading:!1,error:s instanceof Error?s.message:"Logout error"}))}},[t,e]),o=ne(async()=>{try{let s=await t.refreshTokens();if(s){let d=await t.getTokenInfo();e.setState(g=>({...g,tokens:V(d),error:null}))}else e.setState(d=>({...d,isAuthenticated:!1,tokens:null,error:"Token refresh failed"}));return s}catch(s){return e.setState(d=>({...d,isAuthenticated:!1,tokens:null,error:s instanceof Error?s.message:"Token refresh failed"})),!1}},[t,e]),c=ne(()=>{e.setError(null)},[e]);return{login:i,logout:n,refreshTokens:o,clearError:c}}import{useEffect as Nt,useCallback as Ct}from"react";function Dt(r){return r<pe.AGGRESSIVE?re.AGGRESSIVE:r<pe.MODERATE?re.MODERATE:re.RELAXED}function Ge(r){let{isAuthenticated:t,tokens:e,sessionManager:i,onTokensRefreshed:n,onSessionExpired:o,onSetLoading:c,logout:s}=r,d=Ct(()=>{i.updateLastActivity()},[i]);Nt(()=>{if(!t||!e)return;let v=Ne.getInstance().subscribe(d);window.addEventListener("popstate",d);let T,y=!0,b=async()=>{if(!y)return;let A=(await i.getTokenInfo()).crudifyTokens.expiresIn||0,P=Dt(A);T=setTimeout(async()=>{if(!y)return;if(i.isRefreshing()){b();return}let x=await i.getTokenInfo(),O=x.crudifyTokens.expiresIn||0,U=((x.crudifyTokens.expiresAt||0)-(Date.now()-O))*ze;if(O>0&&O<=U)if(c(!0),await i.refreshTokens()){let X=await i.getTokenInfo();n(V(X)),c(!1)}else n(null),o(),c(!1);i.getTimeSinceLastActivity()>18e5?await s():y&&b()},P)};return b(),()=>{y=!1,clearTimeout(T),window.removeEventListener("popstate",d),v()}},[t,e,i,d,n,o,c,s])}import{useEffect as Lt}from"react";function Ve(r){let{sessionManager:t,onTokensUpdated:e,onSessionExpired:i,onSetLoading:n,onSetError:o}=r;Lt(()=>{console.error("[useAuthEventSubscriber] Setting up subscription");let c=M.subscribe(async s=>{if(console.error("[useAuthEventSubscriber] Event received:",s.type,s.details),s.type==="TOKEN_EXPIRED"){if(t.isRefreshing())return;n(!0);try{if(await t.refreshTokens()){let g=await t.getTokenInfo();e(V(g)),n(!1)}else M.emit("SESSION_EXPIRED",{message:"Failed to refresh token after detecting expiration",source:"useSession.TOKEN_EXPIRED handler"})}catch(d){M.emit("SESSION_EXPIRED",{message:d instanceof Error?d.message:"Unknown error during refresh",source:"useSession.TOKEN_EXPIRED handler (error)"})}}(s.type==="SESSION_EXPIRED"||s.type==="TOKEN_REFRESH_FAILED")&&(e(null),n(!1),o(s.details?.message?.toString()||"Session expired"),i())});return()=>c()},[t,e,i,n,o])}import{useEffect as Ot}from"react";function Ye(r){let{isAuthenticated:t,onTokensUpdated:e,onSessionExpired:i}=r;Ot(()=>{console.error("[useCrossTabSync] Setting up subscription, isAuthenticated:",t);let n=I.subscribeToChanges((o,c,s)=>{console.error("[useCrossTabSync] Event received:",{eventType:c,hasTokens:!!o,hadPreviousTokens:s,isAuthenticated:t}),c===I.SYNC_EVENTS.TOKENS_CLEARED?s&&t?(console.error("[useCrossTabSync] Cross-tab logout detected - calling onTokensUpdated(null) and onSessionExpired()"),e(null),i()):s?(console.error("[useCrossTabSync] TOKENS_CLEARED, had tokens but not authenticated - silent sync"),e(null)):console.error("[useCrossTabSync] TOKENS_CLEARED but no previous tokens - ignoring"):c===I.SYNC_EVENTS.TOKENS_UPDATED&&o&&(console.error("[useCrossTabSync] TOKENS_UPDATED detected - calling onTokensUpdated(tokens)"),e(o))});return()=>n()},[t,e,i])}async function $e(r){let{sessionManager:t,options:e,stateActions:i}=r;try{i.setState(s=>({...s,isLoading:!0,error:null}));let n={autoRestore:e.autoRestore??!0,enableLogging:e.enableLogging??!1,showNotification:e.showNotification,translateFn:e.translateFn,apiEndpointAdmin:e.apiEndpointAdmin,apiKeyEndpointAdmin:e.apiKeyEndpointAdmin,publicApiKey:e.publicApiKey,env:e.env||"stg",onSessionExpired:()=>{i.setState(s=>({...s,isAuthenticated:!1,tokens:null,error:"Session expired"})),e.onSessionExpired?.()},onSessionRestored:s=>{i.setState(d=>({...d,isAuthenticated:!0,tokens:s,error:null})),e.onSessionRestored?.(s)},onLoginSuccess:s=>{i.setState(d=>({...d,isAuthenticated:!0,tokens:s,error:null}))},onLogout:()=>{i.setState(s=>({...s,isAuthenticated:!1,tokens:null,error:null}))}};await t.initialize(n),t.setupResponseInterceptor();let o=await t.isAuthenticated(),c=await t.getTokenInfo();console.error("[initializeSession] Setting final state - isAuth:",o,"isLoggingOut: false"),i.setState(s=>(console.error("[initializeSession] setState - prev.isLoggingOut:",s.isLoggingOut),{...s,isAuthenticated:o,isInitialized:!0,isLoading:!1,isLoggingOut:!1,tokens:V(c)}))}catch(n){let o=n instanceof Error?n.message:"Initialization failed";p.error("[useSession] Initialize failed",n instanceof Error?n:{message:o}),i.setState(c=>({...c,isLoading:!1,isInitialized:!0,isLoggingOut:!1,error:o}))}}function me(r={}){let t=ie.getInstance(),e=Ue(),{state:i}=e,{login:n,logout:o,refreshTokens:c,clearError:s}=_e({sessionManager:t,stateManager:e}),d=Z(f=>{e.setAuthenticated(!!f,f)},[e]),g=Z(()=>{e.setAuthenticated(!1,null),r.onSessionExpired?.()},[e,r.onSessionExpired]),v=Z(f=>{e.setLoading(f)},[e]),T=Z(f=>{e.setError(f)},[e]);Ft(()=>{$e({sessionManager:t,options:r,stateActions:e})},[]),Ge({isAuthenticated:i.isAuthenticated,tokens:i.tokens,sessionManager:t,onTokensRefreshed:d,onSessionExpired:g,onSetLoading:v,logout:o}),Ve({sessionManager:t,onTokensUpdated:d,onSessionExpired:g,onSetLoading:v,onSetError:T}),Ye({isAuthenticated:i.isAuthenticated,onTokensUpdated:d,onSessionExpired:g});let y=Z(()=>{t.updateLastActivity()},[t]),b=Z(async()=>t.getTokenInfo(),[t]);return{...i,login:n,logout:o,refreshTokens:c,clearError:s,getTokenInfo:b,updateActivity:y,isExpiringSoon:Ke(i.tokens),expiresIn:Me(i.tokens),refreshExpiresIn:He(i.tokens)}}import{useState as We,createContext as Ut,useContext as zt,useCallback as oe,useEffect as Kt}from"react";import{Snackbar as Mt,Alert as Ht,Box as _t,Portal as Gt}from"@mui/material";import{v4 as Vt}from"uuid";import Yt from"dompurify";import{jsx as W,jsxs as Xt}from"react/jsx-runtime";var Xe=Ut(null),$t=r=>Yt.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}),ye=({children:r,maxNotifications:t=5,defaultAutoHideDuration:e=6e3,position:i={vertical:"top",horizontal:"right"},enabled:n=!1,allowHtml:o=!1})=>{let[c,s]=We([]),d=oe((y,b="info",f)=>{if(!n)return"";if(!y||typeof y!="string")return p.warn("GlobalNotificationProvider: Invalid message provided"),"";y.length>1e3&&(p.warn("GlobalNotificationProvider: Message too long, truncating"),y=y.substring(0,1e3)+"...");let A=Vt(),P={id:A,message:y,severity:b,autoHideDuration:f?.autoHideDuration??e,persistent:f?.persistent??!1,allowHtml:f?.allowHtml??o};return s(x=>[...x.length>=t?x.slice(-(t-1)):x,P]),A},[t,e,n,o]),g=oe(y=>{s(b=>b.filter(f=>f.id!==y))},[]),v=oe(()=>{s([])},[]),T={showNotification:d,hideNotification:g,clearAllNotifications:v};return Xt(Xe.Provider,{value:T,children:[r,n&&W(Gt,{children:W(_t,{sx:{position:"fixed",zIndex:9999,[i.vertical]:(i.vertical==="top",24),[i.horizontal]:i.horizontal==="right"||i.horizontal==="left"?24:"50%",...i.horizontal==="center"&&{transform:"translateX(-50%)"},display:"flex",flexDirection:i.vertical==="top"?"column":"column-reverse",gap:1,maxWidth:"400px",width:"auto"},children:c.map(y=>W(Wt,{notification:y,onClose:()=>g(y.id)},y.id))})})]})},Wt=({notification:r,onClose:t})=>{let[e,i]=We(!0),n=oe((o,c)=>{c!=="clickaway"&&(i(!1),setTimeout(t,300))},[t]);return Kt(()=>{if(!r.persistent&&r.autoHideDuration){let o=setTimeout(()=>{n()},r.autoHideDuration);return()=>clearTimeout(o)}},[r.autoHideDuration,r.persistent,n]),W(Mt,{open:e,onClose:n,sx:{position:"relative","& .MuiSnackbarContent-root":{minWidth:"auto"}},TransitionProps:{enter:!0,exit:!0},children:W(Ht,{variant:"filled",severity:r.severity,onClose:n,sx:{width:"100%",minWidth:"280px",maxWidth:"400px",wordBreak:"break-word"},children:r.allowHtml?W("span",{dangerouslySetInnerHTML:{__html:$t(r.message)}}):W("span",{children:r.message})})})},Be=()=>{let r=zt(Xe);if(!r)throw new Error("useGlobalNotification debe ser usado dentro de un GlobalNotificationProvider");return r};import{createContext as Bt,useContext as Zt,useEffect as qt,useState as J}from"react";import Q from"@nocios/crudify-browser";var he=class r{constructor(){this.listeners=[];this.credentials=null;this.isReady=!1}static getInstance(){return r.instance||(r.instance=new r),r.instance}notifyCredentialsReady(t){this.credentials=t,this.isReady=!0,this.listeners.forEach(e=>{try{e(t)}catch(i){p.error("[CredentialsEventBus] Error in listener",i instanceof Error?i:{message:String(i)})}}),this.listeners=[]}waitForCredentials(){return this.isReady&&this.credentials?Promise.resolve(this.credentials):new Promise(t=>{this.listeners.push(t)})}reset(){this.credentials=null,this.isReady=!1,this.listeners=[]}areCredentialsReady(){return this.isReady&&this.credentials!==null}},se=he.getInstance();import{jsx as jt}from"react/jsx-runtime";var Ze=Bt(void 0),qe=({config:r,children:t})=>{let[e,i]=J(!0),[n,o]=J(null),[c,s]=J(!1),[d,g]=J(""),[v,T]=J();qt(()=>{if(!r.publicApiKey){o("No publicApiKey provided"),i(!1),s(!1);return}let b=`${r.publicApiKey}-${r.env}`;if(b===d&&c){i(!1);return}(async()=>{i(!0),o(null),s(!1);try{Q.config(r.env||"prod");let A=await Q.init(r.publicApiKey,"none");if(T(A),typeof Q.transaction=="function"&&typeof Q.login=="function")s(!0),g(b),A.apiEndpointAdmin&&A.apiKeyEndpointAdmin&&se.notifyCredentialsReady({apiUrl:A.apiEndpointAdmin,apiKey:A.apiKeyEndpointAdmin});else throw new Error("Crudify methods not properly initialized")}catch(A){let P=A instanceof Error?A.message:"Failed to initialize Crudify";p.error("[CrudifyProvider] Initialization error",A instanceof Error?A:{message:String(A)}),o(P),s(!1)}finally{i(!1)}})()},[r.publicApiKey,r.env,d,c]);let y={crudify:c?Q:null,isLoading:e,error:n,isInitialized:c,adminCredentials:v};return jt(Ze.Provider,{value:y,children:t})},je=()=>{let r=Zt(Ze);if(r===void 0)throw new Error("useCrudify must be used within a CrudifyProvider");return r};import Jt,{createContext as Qt,useContext as ei,useMemo as Ee}from"react";import{Fragment as ii,jsx as C,jsxs as H}from"react/jsx-runtime";var Qe=Qt(void 0);function Je({children:r,options:t={},config:e,showNotifications:i=!1,notificationOptions:n={}}){let o;try{let{showNotification:f}=Be();o=f}catch{}let c={};try{let f=je();f.isInitialized&&f.adminCredentials&&(c=f.adminCredentials)}catch{}let s=Ee(()=>{let f=ge({publicApiKey:e?.publicApiKey,env:e?.env,enableDebug:t?.enableLogging});return{publicApiKey:f.publicApiKey,env:f.env||"prod"}},[e,t?.enableLogging]),d=Jt.useMemo(()=>({...t,showNotification:o,apiEndpointAdmin:c.apiEndpointAdmin,apiKeyEndpointAdmin:c.apiKeyEndpointAdmin,publicApiKey:s.publicApiKey,env:s.env,onSessionExpired:()=>{t.onSessionExpired?.()}}),[t,o,c.apiEndpointAdmin,c.apiKeyEndpointAdmin,s]),g=me(d),v=Ee(()=>{let f=ge({publicApiKey:e?.publicApiKey,env:e?.env,appName:e?.appName,logo:e?.logo,loginActions:e?.loginActions,enableDebug:t?.enableLogging});return{publicApiKey:f.publicApiKey,env:f.env,appName:f.appName,loginActions:f.loginActions,logo:f.logo}},[e,t?.enableLogging]),T=Ee(()=>{if(!g.tokens?.accessToken||!g.isAuthenticated)return null;try{let f=Ce(g.tokens.accessToken);if(f&&f.sub&&f.email&&f.subscriber){let A={_id:f.sub,email:f.email,subscriberKey:f.subscriber};return Object.keys(f).forEach(P=>{["sub","email","subscriber"].includes(P)||(A[P]=f[P])}),A}}catch(f){p.error("Error decoding JWT token for sessionData",f instanceof Error?f:{message:String(f)})}return null},[g.tokens?.accessToken,g.isAuthenticated]),y={...g,sessionData:T,config:v},b={enabled:i,maxNotifications:n.maxNotifications||5,defaultAutoHideDuration:n.defaultAutoHideDuration||6e3,position:n.position||{vertical:"top",horizontal:"right"}};return C(Qe.Provider,{value:y,children:r})}function Or(r){let t={enabled:r.showNotifications,maxNotifications:r.notificationOptions?.maxNotifications||5,defaultAutoHideDuration:r.notificationOptions?.defaultAutoHideDuration||6e3,position:r.notificationOptions?.position||{vertical:"top",horizontal:"right"},allowHtml:r.notificationOptions?.allowHtml||!1};return r.config?.publicApiKey?C(qe,{config:{publicApiKey:r.config.publicApiKey,env:r.config.env||"prod",appName:r.config.appName,loginActions:r.config.loginActions,logo:r.config.logo},children:C(ye,{...t,children:C(Je,{...r})})}):C(ye,{...t,children:C(Je,{...r})})}function ti(){let r=ei(Qe);if(r===void 0)throw new Error("useSessionContext must be used within a SessionProvider");return r}function Fr(){let r=ti();return r.isInitialized?H("div",{style:{padding:"10px",margin:"10px",border:"1px solid #ccc",borderRadius:"4px",fontSize:"12px",fontFamily:"monospace"},children:[C("h4",{children:"Session Debug Info"}),H("div",{children:[C("strong",{children:"Authenticated:"})," ",r.isAuthenticated?"Yes":"No"]}),H("div",{children:[C("strong",{children:"Loading:"})," ",r.isLoading?"Yes":"No"]}),H("div",{children:[C("strong",{children:"Error:"})," ",r.error||"None"]}),r.tokens&&H(ii,{children:[H("div",{children:[C("strong",{children:"Access Token:"})," ",r.tokens.accessToken.substring(0,20),"..."]}),H("div",{children:[C("strong",{children:"Refresh Token:"})," ",r.tokens.refreshToken.substring(0,20),"..."]}),H("div",{children:[C("strong",{children:"Access Expires In:"})," ",Math.round(r.expiresIn/1e3/60)," minutes"]}),H("div",{children:[C("strong",{children:"Refresh Expires In:"})," ",Math.round(r.refreshExpiresIn/1e3/60/60)," hours"]}),H("div",{children:[C("strong",{children:"Expiring Soon:"})," ",r.isExpiringSoon?"Yes":"No"]})]})]}):C("div",{children:"Session not initialized"})}import{useState as ae,useEffect as et,useCallback as tt,useRef as le}from"react";import ri from"@nocios/crudify-browser";var _r=(r={})=>{let{autoFetch:t=!0,retryOnError:e=!1,maxRetries:i=3}=r,[n,o]=ae(null),[c,s]=ae(!1),[d,g]=ae(null),[v,T]=ae({}),y=le(null),b=le(!0),f=le(0),A=le(0),P=tt(()=>{o(null),g(null),s(!1),T({})},[]),x=tt(async()=>{let O=De();if(!O){b.current&&(g("No user email available"),s(!1));return}y.current&&y.current.abort();let w=new AbortController;y.current=w;let F=++f.current;try{b.current&&(s(!0),g(null));let U=await ri.readItems("users",{filter:{email:O},pagination:{limit:1}});if(F===f.current&&b.current&&!w.signal.aborted){let D=U.data;if(U.success&&D&&D.length>0){let S=D[0];o(S);let X={fullProfile:S,totalFields:Object.keys(S).length,displayData:{id:S.id,email:S.email,username:S.username,firstName:S.firstName,lastName:S.lastName,fullName:S.fullName||`${S.firstName||""} ${S.lastName||""}`.trim(),role:S.role,permissions:S.permissions||[],isActive:S.isActive,lastLogin:S.lastLogin,createdAt:S.createdAt,updatedAt:S.updatedAt,...Object.keys(S).filter(G=>!["id","email","username","firstName","lastName","fullName","role","permissions","isActive","lastLogin","createdAt","updatedAt"].includes(G)).reduce((G,te)=>({...G,[te]:S[te]}),{})}};T(X),g(null),A.current=0}else g("User profile not found"),o(null),T({})}}catch(U){if(F===f.current&&b.current){let D=U;if(D.name==="AbortError")return;e&&A.current<i&&(D.message?.includes("Network Error")||D.message?.includes("Failed to fetch"))?(A.current++,setTimeout(()=>{b.current&&x()},1e3*A.current)):(g("Failed to load user profile"),o(null),T({}))}}finally{F===f.current&&b.current&&s(!1),y.current===w&&(y.current=null)}},[e,i]);return et(()=>{t&&x()},[t,x]),et(()=>(b.current=!0,()=>{b.current=!1,y.current&&(y.current.abort(),y.current=null)}),[]),{userProfile:n,loading:c,error:d,extendedData:v,refreshProfile:x,clearProfile:P}};import{useState as Te,useEffect as ni,useCallback as ce,useRef as oi}from"react";import si from"@nocios/crudify-browser";var $r=(r,t={})=>{let{autoFetch:e=!0,onSuccess:i,onError:n}=t,{prefix:o,padding:c=0,separator:s=""}=r,[d,g]=Te(""),[v,T]=Te(!1),[y,b]=Te(null),f=oi(!1),A=ce(w=>{let F=String(w).padStart(c,"0");return`${o}${s}${F}`},[o,c,s]),P=ce(async()=>{T(!0),b(null);try{let w=await si.getNextSequence(o),F=w.data;if(w.success&&F?.value){let U=A(F.value);g(U),i?.(U)}else{let U=w.errors?._error?.[0]||"Failed to generate code";b(U),n?.(U)}}catch(w){let F=w instanceof Error?w.message:"Unknown error";b(F),n?.(F)}finally{T(!1)}},[o,A,i,n]),x=ce(async()=>{await P()},[P]),O=ce(()=>{b(null)},[]);return ni(()=>{e&&!d&&!f.current&&(f.current=!0,P())},[e,d,P]),{value:d,loading:v,error:y,regenerate:x,clearError:O}};import Se from"@nocios/crudify-browser";var ve=class r{constructor(){this.state={status:"UNINITIALIZED",priority:null,publicApiKey:null,env:null,error:null,initializedBy:null};this.initializationPromise=null;this.highPriorityInitializerPresent=!1;this.waitingForHighPriority=new Set;this.HIGH_PRIORITY_WAIT_TIMEOUT=100}static getInstance(){return r.instance||(r.instance=new r),r.instance}registerHighPriorityInitializer(){this.highPriorityInitializerPresent=!0}isHighPriorityInitializerPresent(){return this.highPriorityInitializerPresent}getState(){return{...this.state}}async initialize(t){let{priority:e,publicApiKey:i,env:n,enableLogging:o,requestedBy:c}=t;if(this.state.status==="INITIALIZED"){this.state.publicApiKey!==i&&p.warn(`[CrudifyInitialization] ${c} 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 o&&p.debug(`[CrudifyInitialization] ${c} waiting for ongoing initialization...`),this.initializationPromise;if(e==="LOW"&&this.highPriorityInitializerPresent&&this.state.status==="UNINITIALIZED"){if(o&&p.debug(`[CrudifyInitialization] ${c} (LOW priority) waiting for HIGH priority initializer...`),this.waitingForHighPriority.add(c),await this.waitForHighPriorityOrTimeout(o),this.waitingForHighPriority.delete(c),this.getState().status==="INITIALIZED"){o&&p.debug(`[CrudifyInitialization] ${c} found initialization completed by HIGH priority`);return}o&&p.warn(`[CrudifyInitialization] ${c} 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 ${c} interrupting LOW priority initialization by ${this.state.initializedBy}`),this.state.status="UNINITIALIZED",this.initializationPromise=null),o&&p.debug(`[CrudifyInitialization] ${c} starting initialization (${e} priority)...`),this.state.status="INITIALIZING",this.state.priority=e,this.state.initializedBy=c,this.initializationPromise=this.performInitialization(i,n,o);try{await this.initializationPromise,this.state.status="INITIALIZED",this.state.publicApiKey=i,this.state.env=n,this.state.error=null,o&&p.info(`[CrudifyInitialization] Successfully initialized by ${c} (${e} priority)`)}catch(s){throw this.state.status="ERROR",this.state.error=s instanceof Error?s:new Error(String(s)),this.initializationPromise=null,p.error(`[CrudifyInitialization] Initialization failed for ${c}`,s instanceof Error?s:{message:String(s)}),s}}async waitForHighPriorityOrTimeout(t){return new Promise(e=>{let n=0,o=setInterval(()=>{if(n+=10,this.state.status==="INITIALIZED"&&this.state.priority==="HIGH"){clearInterval(o),e();return}if(this.state.status==="INITIALIZING"&&this.state.priority==="HIGH"){n=0;return}n>=this.HIGH_PRIORITY_WAIT_TIMEOUT&&(clearInterval(o),t&&p.debug(`[CrudifyInitialization] Timeout waiting for HIGH priority (${this.HIGH_PRIORITY_WAIT_TIMEOUT}ms)`),e())},10)})}async performInitialization(t,e,i){let n=Se.getTokenData();if(n&&n.endpoint){i&&p.debug("[CrudifyInitialization] SDK already initialized externally");return}Se.config(e);let o=i?"debug":"none",c=await Se.init(t,o);if(c.success===!1)throw new Error(`Crudify initialization failed: ${JSON.stringify(c.errors||"Unknown error")}`);c.apiEndpointAdmin&&c.apiKeyEndpointAdmin&&se.notifyCredentialsReady({apiUrl:c.apiEndpointAdmin,apiKey:c.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}}},ee=ve.getInstance();import{useState as ue,useCallback as N,useRef as ai,useMemo as q}from"react";import de from"@nocios/crudify-browser";var rt=r=>{let t=new Uint8Array(r);return crypto.getRandomValues(t),Array.from(t,e=>e.toString(36).padStart(2,"0")).join("").substring(0,r)},it=()=>`file_${Date.now()}_${rt(7)}`,li=r=>{let t=r.lastIndexOf("."),e=t>0?r.substring(t):"",i=Date.now(),n=rt(6);return`${i}_${n}${e}`},be=(r,t)=>{if(r.startsWith("http://")||r.startsWith("https://"))try{let e=new URL(r);return e.pathname.startsWith("/")?e.pathname.substring(1):e.pathname}catch{if(t&&r.startsWith(t))return r.substring(t.length)}return t&&r.startsWith(t)?r.substring(t.length):r},tn=(r={})=>{let{acceptedTypes:t,maxFileSize:e=10*1024*1024,maxFiles:i,minFiles:n=0,visibility:o="private",onUploadComplete:c,onUploadError:s,onFileRemoved:d,onFilesChange:g,mode:v="edit"}=r,[T,y]=ue([]),[b,f]=ue(!1),[A,P]=ue(!1),[x,O]=ue([]),w=ai(new Map),F=N(()=>{f(!0)},[]),U=N(()=>{P(!0),f(!0)},[]),D=N((l,m)=>{y(u=>u.map(E=>E.id===l?{...E,...m}:E))},[]),S=N(l=>{g?.(l)},[g]),X=N(l=>t&&t.length>0&&!t.includes(l.type)?{valid:!1,error:`File type not allowed: ${l.type}`}:l.size>e?{valid:!1,error:`File exceeds maximum size of ${(e/1048576).toFixed(1)}MB`}:{valid:!0},[t,e]),G=N(async(l,m)=>{try{if(!ee.isInitialized())throw new Error("Crudify is not initialized. Please wait for the application to finish loading.");let u=li(m.name),h=await de.generateSignedUrl({fileName:u,contentType:m.type,visibility:o});if(!h.success||!h.data)throw new Error("Failed to get upload URL");let E=h.data,{uploadUrl:R,s3Key:k,publicUrl:K}=E;if(!R||!k)throw new Error("Incomplete signed URL response");let Y=k.indexOf("/"),It=Y>0?k.substring(Y+1):k;D(l.id,{status:"uploading",progress:0}),await new Promise((fe,$)=>{let z=new XMLHttpRequest;z.upload.addEventListener("progress",_=>{if(_.lengthComputable){let xt=Math.round(_.loaded/_.total*100);D(l.id,{progress:xt})}}),z.addEventListener("load",()=>{z.status>=200&&z.status<300?fe():$(new Error(`Upload failed with status ${z.status}`))}),z.addEventListener("error",()=>{$(new Error("Network error during upload"))}),z.addEventListener("abort",()=>{$(new Error("Upload cancelled"))}),z.open("PUT",R),z.setRequestHeader("Content-Type",m.type),z.send(m)});let kt={status:"completed",progress:100,filePath:It,visibility:o,publicUrl:o==="public"?K:void 0,file:void 0};y(fe=>{let $=fe.map(_=>_.id===l.id?{..._,...kt}:_);S($);let z=$.find(_=>_.id===l.id);return z&&c?.(z),$})}catch(u){let h=u instanceof Error?u.message:"Unknown error";D(l.id,{status:"error",progress:0,errorMessage:h}),y(E=>{let R=E.find(k=>k.id===l.id);return R&&s?.(R,h),E})}},[D,c,s,o]),te=N(async l=>{let m=Array.from(l),u=[];y(h=>{if(i!==void 0){let k=h.filter(Y=>Y.status!=="pendingDeletion"&&Y.status!=="error").length,K=i-k;if(K<=0)return p.warn(`File limit of ${i} already reached`),h;m.length>K&&(m=m.slice(0,K),p.warn(`Only ${K} files will be added to not exceed limit`))}let E=[];for(let k of m){let K=X(k),Y={id:it(),name:k.name,size:k.size,contentType:k.type,status:K.valid?"pending":"error",progress:0,createdAt:Date.now(),file:K.valid?k:void 0,errorMessage:K.error,isExisting:!1};E.push(Y)}u=E;let R=[...h,...E];return S(R),R}),setTimeout(()=>{let h=u.filter(E=>E.status==="pending"&&E.file);for(let E of h)if(E.file){let R=G(E,E.file);w.current.set(E.id,R),R.finally(()=>{w.current.delete(E.id)})}},0)},[i,X,G,S]),nt=N(async l=>{let m=T.find(h=>h.id===l);if(!m)return{needsConfirmation:!1,isExisting:!1};let u=m.isExisting===!0;return v==="create"||!u?{needsConfirmation:!0,isExisting:u}:(O(h=>[...h,l]),y(h=>{let E=h.map(k=>k.id===l?{...k,status:"pendingDeletion"}:k),R=E.filter(k=>k.status!=="pendingDeletion");return S(R),E}),{needsConfirmation:!1,isExisting:u})},[T,v,S]),ot=N(async l=>{let m=T.find(u=>u.id===l);if(!m)return{success:!1,error:"File not found"};if(!m.filePath)return y(u=>{let h=u.filter(E=>E.id!==l);return S(h),h}),{success:!0};try{if(!ee.isInitialized())return{success:!1,error:"Crudify not initialized"};let u=be(m.filePath);return(await de.disableFile({filePath:u})).success?(y(E=>{let R=E.filter(k=>k.id!==l);return S(R),R}),d?.(m),{success:!0}):{success:!1,error:"Failed to delete file"}}catch(u){return{success:!1,error:u instanceof Error?u.message:"Unknown error"}}},[T,S,d]),st=N(l=>{let m=T.find(u=>u.id===l);return!m||!m.isExisting?!1:(O(u=>u.filter(h=>h!==l)),y(u=>{let h=u.map(E=>E.id===l?{...E,status:"completed"}:E);return S(h),h}),!0)},[T,S]),at=N(()=>{x.length!==0&&(y(l=>{let m=l.map(u=>x.includes(u.id)?{...u,status:"completed"}:u);return S(m),m}),O([]))},[x,S]),lt=N(async()=>{if(x.length===0)return{success:!0,errors:[]};let l=[],m=[];if(!ee.isInitialized())return{success:!1,errors:["Crudify is not initialized. Please wait for the application to finish loading."]};for(let u of x){let h=T.find(E=>E.id===u);if(!h?.filePath){m.push(u);continue}try{let E=be(h.filePath);(await de.disableFile({filePath:E})).success?(m.push(u),d?.(h)):l.push(`Failed to delete ${h.name}`)}catch(E){l.push(`Error deleting ${h.name}: ${E instanceof Error?E.message:"Unknown error"}`)}}return m.length>0&&(y(u=>u.filter(E=>!m.includes(E.id))),O(u=>u.filter(h=>!m.includes(h)))),{success:l.length===0,errors:l}},[T,x,d]),ct=N(()=>{y([]),S([])},[S]),ut=N(async l=>{let m=T.find(h=>h.id===l);if(!m||m.status!=="error"||!m.file){p.warn("Cannot retry: file not found or no original file");return}D(l,{status:"pending",progress:0,errorMessage:void 0});let u=G(m,m.file);w.current.set(l,u),u.finally(()=>{w.current.delete(l)})},[T,D,G]),dt=N(async()=>{let l=Array.from(w.current.values());return l.length>0&&await Promise.allSettled(l),new Promise(m=>{setTimeout(()=>{y(u=>{let h=u.filter(E=>E.status==="completed"&&E.filePath).map(E=>E.filePath);return m(h),u})},0)})},[]),ft=l=>{let m=l.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"}[m]||"application/octet-stream"},gt=N((l,m)=>{let u=l.map(h=>{let E=be(h.filePath,m),R=E.includes("/public/")||E.startsWith("public/")?"public":"private",k=h.contentType||ft(h.name);return{id:it(),name:h.name,size:h.size||0,contentType:k,status:"completed",progress:100,filePath:E,visibility:R,createdAt:Date.now(),isExisting:!0}});y(u),S(u)},[S]),pt=N(async l=>{let m=T.find(u=>u.id===l);if(!m||!m.filePath)return null;if(m.visibility==="public"&&m.publicUrl)return m.publicUrl;try{if(!ee.isInitialized())return null;let u=await de.getFileUrl({filePath:m.filePath,expiresIn:3600}),h=u.data;return u.success&&h?.url?h.url:null}catch{return null}},[T]),mt=q(()=>T.some(l=>l.status==="uploading"||l.status==="pending"),[T]),yt=q(()=>T.filter(l=>l.status==="uploading"||l.status==="pending").length,[T]),ht=q(()=>T.filter(l=>l.status==="completed"&&l.filePath).map(l=>l.filePath),[T]),B=q(()=>T.filter(l=>l.status!=="pendingDeletion"),[T]),Et=q(()=>B.filter(l=>l.status==="completed"||l.status==="pending"||l.status==="uploading").length,[B]),{isValid:Tt,validationError:St,validationErrorKey:vt,validationErrorParams:bt}=q(()=>{let l=B.filter(u=>u.status==="completed").length;if(l<n){let u=n===1?"file.validation.minFilesRequired":"file.validation.minFilesRequiredPlural";return{isValid:!1,validationError:u,validationErrorKey:u,validationErrorParams:{count:n}}}return i!==void 0&&l>i?{isValid:!1,validationError:"file.validation.maxFilesExceeded",validationErrorKey:"file.validation.maxFilesExceeded",validationErrorParams:{count:i}}:B.some(u=>u.status==="error")?{isValid:!1,validationError:"file.validation.filesWithErrors",validationErrorKey:"file.validation.filesWithErrors",validationErrorParams:{}}:{isValid:!0,validationError:null,validationErrorKey:null,validationErrorParams:{}}},[B,n,i]),At=x.length>0;return{files:T,activeFiles:B,activeFileCount:Et,isUploading:mt,pendingCount:yt,addFiles:te,removeFile:nt,deleteFileImmediately:ot,restoreFile:st,clearFiles:ct,retryUpload:ut,isValid:Tt,validationError:St,validationErrorKey:vt,validationErrorParams:bt,waitForUploads:dt,completedFilePaths:ht,initializeFiles:gt,isTouched:b,markAsTouched:F,isSubmitted:A,markAsSubmitted:U,getPreviewUrl:pt,pendingDeletions:x,hasPendingDeletions:At,commitDeletions:lt,restorePendingDeletions:at}};export{I as a,ie as b,me as c,ye as d,Be as e,se as f,qe as g,je as h,Or as i,ti as j,Fr as k,_r as l,$r as m,ve as n,ee as o,tn as p};
|