@nocios/crudify-components 2.0.12 → 2.0.14
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/coverage/coverage-final.json +10 -10
- package/coverage/index.html +40 -40
- package/dist/chunk-6ONAT4QU.js +1 -0
- package/dist/{chunk-HRV256AI.mjs → chunk-H5M2Q6PB.mjs} +1 -1
- package/dist/{chunk-EVQNIDNI.js → chunk-KFA34SUS.js} +1 -1
- package/dist/{chunk-CLTUGUSZ.mjs → chunk-NXCJZPEQ.mjs} +1 -1
- package/dist/chunk-PTUSZGL4.mjs +1 -0
- package/dist/{chunk-IKTVS5DX.js → chunk-T6R65ROU.js} +1 -1
- package/dist/components.js +1 -1
- package/dist/components.mjs +1 -1
- package/dist/hooks.d.mts +1 -1
- package/dist/hooks.d.ts +1 -1
- package/dist/hooks.js +1 -1
- package/dist/hooks.mjs +1 -1
- package/dist/{index-Y9tTsinC.d.mts → index-DY90WVQQ.d.mts} +20 -2
- package/dist/{index-BUKX3duW.d.ts → index-d1vE803G.d.ts} +20 -2
- package/dist/index.d.mts +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +2 -2
- package/dist/index.mjs +1 -1
- package/dist/utils.d.mts +2 -0
- package/dist/utils.d.ts +2 -0
- package/package.json +1 -1
- package/dist/chunk-4KHK3A5S.mjs +0 -1
- package/dist/chunk-QM34W6EU.js +0 -1
package/dist/chunk-4KHK3A5S.mjs
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{a as c,d as he,f as H,g as Re,h as Ne,i as Pe,j as De,k as Le,l as Oe,m as Fe,q as ze,r as Ue,s as Ke}from"./chunk-4ILUXVPW.mjs";var Me="crudify_storage_version",He=2,a=class a{static setStorageType(e){a.storageType=e}static async initialize(){if(!(a.encryptionKey&&a.salt))return a.initPromise||(a.initPromise=(async()=>{let t=null;for(let i=1;i<=3;i++)try{a.checkStorageVersion(),a.salt=a.getOrCreateSalt(),a.fingerprint=await a.generateFingerprint(),a.encryptionKey=await Ne(a.fingerprint,a.salt);return}catch(n){t=n instanceof Error?n:new Error(String(n)),i<3&&await new Promise(o=>setTimeout(o,100*i))}throw c.error("Crudify: Failed to initialize encryption after retries",t??{message:"Unknown error"}),t})()),a.initPromise}static checkStorageVersion(){try{if(parseInt(localStorage.getItem(Me)||"1",10)<He){let t=a.getStorage();t&&t.removeItem(a.TOKEN_KEY),localStorage.removeItem(a.ENCRYPTION_KEY_STORAGE),localStorage.removeItem(a.SALT_KEY),localStorage.setItem(Me,He.toString()),c.info("Crudify: Storage upgraded to v2, tokens cleared for security")}}catch{}}static getOrCreateSalt(){try{let t=localStorage.getItem(a.SALT_KEY);if(t){let i=atob(t),n=new Uint8Array(i.length);for(let o=0;o<i.length;o++)n[o]=i.charCodeAt(o);return n}}catch{}let e=Le();try{let t="";for(let i=0;i<e.length;i++)t+=String.fromCharCode(e[i]);localStorage.setItem(a.SALT_KEY,btoa(t))}catch{c.warn("Crudify: Cannot persist salt, encryption may not persist across sessions")}return e}static async generateFingerprint(){try{let n=localStorage.getItem(a.ENCRYPTION_KEY_STORAGE);if(n&&n.length>=32)return n}catch{}let t=[navigator.userAgent,navigator.language,navigator.platform||"unknown",String(screen.width),String(screen.height),String(screen.colorDepth||24),String(new Date().getTimezoneOffset()),"crudify-session-v3"].join("|"),i=await Re(t);try{localStorage.setItem(a.ENCRYPTION_KEY_STORAGE,i)}catch{c.warn("Crudify: Cannot persist encryption key hash, session may not survive page reload")}return i}static isStorageAvailable(e){try{let t=window[e],i="__storage_test__";return t.setItem(i,"test"),t.removeItem(i),!0}catch{return!1}}static getStorage(){return a.storageType==="none"?null:a.isStorageAvailable(a.storageType)?window[a.storageType]:(c.warn(`Crudify: ${a.storageType} not available, tokens won't persist`),null)}static async encryptData(e){if(await a.initialize(),!a.encryptionKey||!a.salt)throw new Error("Encryption not initialized");return Pe(e,a.encryptionKey,a.salt)}static async decryptData(e){if(await a.initialize(),!a.fingerprint)throw new Error("Encryption not initialized");return Oe(e)?De(e,a.fingerprint):(c.warn("Crudify: Legacy encrypted data detected, cannot decrypt"),null)}static async saveTokens(e){let t=a.getStorage();if(t)try{let i={accessToken:e.accessToken,refreshToken:e.refreshToken,expiresAt:e.expiresAt,refreshExpiresAt:e.refreshExpiresAt,savedAt:Date.now()},n=await a.encryptData(JSON.stringify(i));t.setItem(a.TOKEN_KEY,n),c.debug("Crudify: Tokens saved successfully")}catch(i){c.error("Crudify: Failed to save tokens",i instanceof Error?i:{message:String(i)})}}static async getTokens(){let e=a.getStorage();if(!e)return null;try{let t=e.getItem(a.TOKEN_KEY);if(!t)return null;let i=await a.decryptData(t);if(!i)return c.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?(c.warn("Crudify: Incomplete token data found, clearing storage"),await a.clearTokens(),null):Date.now()>=n.refreshExpiresAt?(c.info("Crudify: Refresh token expired, clearing storage"),await a.clearTokens(),null):{accessToken:n.accessToken,refreshToken:n.refreshToken,expiresAt:n.expiresAt,refreshExpiresAt:n.refreshExpiresAt}}catch(t){return c.error("Crudify: Failed to retrieve tokens",t instanceof Error?t:{message:String(t)}),await a.clearTokens(),null}}static async clearTokens(){let e=a.getStorage();if(e)try{e.removeItem(a.TOKEN_KEY),c.debug("Crudify: Tokens cleared from storage")}catch(t){c.error("Crudify: Failed to clear tokens",t instanceof Error?t:{message:String(t)})}}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{}c.info("Crudify: Encryption key rotated successfully")}catch(e){c.error("Crudify: Failed to rotate encryption key",e instanceof Error?e:{message:String(e)})}}static async hasValidTokens(){return await a.getTokens()!==null}static async ensureInitialized(){await a.initialize()}static async getExpirationInfo(){let e=await a.getTokens();if(!e)return null;let t=Date.now();return{accessExpired:t>=e.expiresAt,refreshExpired:t>=e.refreshExpiresAt,accessExpiresIn:Math.max(0,e.expiresAt-t),refreshExpiresIn:Math.max(0,e.refreshExpiresAt-t)}}static async updateAccessToken(e,t){let i=await a.getTokens();if(!i){c.warn("Crudify: Cannot update access token, no existing tokens found");return}await a.saveTokens({...i,accessToken:e,expiresAt:t})}static createSyncEvent(e,t,i){return{type:e,tokens:t,hadPreviousTokens:i}}static markLocalChange(){a.ignoreNextStorageEvent=!0,a.ignoreStorageEventTimeout&&clearTimeout(a.ignoreStorageEventTimeout),a.ignoreStorageEventTimeout=setTimeout(()=>{a.ignoreNextStorageEvent=!1},100)}static markSuccessfulLogin(){a.lastSuccessfulLoginTime=Date.now()}static isWithinLoginGracePeriod(){return a.lastSuccessfulLoginTime===0?!1:Date.now()-a.lastSuccessfulLoginTime<a.LOGIN_GRACE_PERIOD_MS}static subscribeToChanges(e){let t=async i=>{if(i.key!==a.TOKEN_KEY)return;if(a.ignoreNextStorageEvent){a.ignoreNextStorageEvent=!1;return}if(i.newValue===null&&a.isWithinLoginGracePeriod())return;if(i.newValue===null){let l=a.getStorage()?.getItem(a.TOKEN_KEY);if(l!==null&&l!=="")return}let n=i.oldValue!==null&&i.oldValue!=="";if(i.newValue===null){c.debug("Crudify: Tokens removed in another tab"),e(null,a.SYNC_EVENTS.TOKENS_CLEARED,n);return}if(i.newValue){c.debug("Crudify: Tokens updated in another tab");let o=await a.getTokens();e(o,a.SYNC_EVENTS.TOKENS_UPDATED,n)}};return window.addEventListener("storage",t),()=>{window.removeEventListener("storage",t)}}};a.TOKEN_KEY="crudify_tokens",a.ENCRYPTION_KEY_STORAGE="crudify_enc_key",a.SALT_KEY="crudify_enc_salt",a.encryptionKey=null,a.salt=null,a.fingerprint=null,a.storageType="localStorage",a.initPromise=null,a.lastSuccessfulLoginTime=0,a.LOGIN_GRACE_PERIOD_MS=5e3,a.SYNC_EVENTS={TOKENS_CLEARED:"TOKENS_CLEARED",TOKENS_UPDATED:"TOKENS_UPDATED"},a.ignoreNextStorageEvent=!1,a.ignoreStorageEventTimeout=null;var v=a;var K=class K{constructor(){this.broadcastChannel=null;this.CHANNEL_NAME="crudify-session-sync";this.listeners=new Set;this.isInitialized=!1;this.tabId=K.generateTabId(),this.initialize()}static generateTabId(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,9);return`tab_${e}_${t}`}static getInstance(){return K.instance||(K.instance=new K),K.instance}static resetInstance(){K.instance&&(K.instance.destroy(),K.instance=null)}initialize(){if(!this.isInitialized)try{typeof BroadcastChannel<"u"?(this.broadcastChannel=new BroadcastChannel(this.CHANNEL_NAME),this.broadcastChannel.onmessage=e=>{this.handleMessage(e.data)},this.broadcastChannel.onmessageerror=()=>{c.warn("Crudify: CrossTabSync message error")},c.debug("Crudify: CrossTabSync initialized with BroadcastChannel")):c.debug("Crudify: BroadcastChannel not available, using localStorage fallback"),this.isInitialized=!0}catch(e){c.warn("Crudify: Failed to initialize CrossTabSync",{message:e instanceof Error?e.message:String(e)})}}destroy(){this.broadcastChannel&&(this.broadcastChannel.close(),this.broadcastChannel=null),this.listeners.clear(),this.isInitialized=!1}getTabId(){return this.tabId}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}notifyLogin(){this.broadcast({type:"SESSION_STARTED",tabId:this.tabId,timestamp:Date.now()})}notifyLogout(){this.broadcast({type:"SESSION_ENDED",tabId:this.tabId,timestamp:Date.now()})}notifyTokenRefreshed(){this.broadcast({type:"TOKEN_REFRESHED",tabId:this.tabId,timestamp:Date.now()})}ping(){this.broadcast({type:"SESSION_PING",tabId:this.tabId,timestamp:Date.now()})}broadcast(e){this.isInitialized||this.initialize();try{this.broadcastChannel&&(this.broadcastChannel.postMessage(e),c.debug(`Crudify: CrossTab broadcast ${e.type}`))}catch(t){c.warn("Crudify: Failed to broadcast cross-tab message",{message:t instanceof Error?t.message:String(t)})}}handleMessage(e){e.tabId!==this.tabId&&(c.debug(`Crudify: CrossTab received ${e.type} from ${e.tabId}`),e.type==="SESSION_PING"&&this.broadcast({type:"SESSION_PONG",tabId:this.tabId,timestamp:Date.now(),payload:{respondingTo:e.tabId}}),this.listeners.forEach(t=>{try{t(e)}catch(i){c.error("Crudify: CrossTab listener error",{message:i instanceof Error?i.message:String(i)})}}))}};K.instance=null;var Ee=K,B=Ee.getInstance();import L from"@nocios/crudify-sdk";var oe="crudify_auth",Se=r=>{if(r==="dev"||typeof window>"u"||!window.location)return"";if(!r){let e=window.location.hostname;return e?e.endsWith(".nocios.link")||e==="nocios.link"?".nocios.link":e.endsWith(".crudia.com")||e==="crudia.com"?".crudia.com":"":""}return r==="prod"||r==="api"?".crudia.com":".nocios.link"},Ot=(r,e,t)=>{if(typeof document>"u"){c.debug("[CookieSync] No document available (SSR), skipping cookie set");return}if(!r){c.warn("[CookieSync] Attempted to set cookie with empty token");return}try{let i=Se(t),n=Date.now(),o=Math.max(0,Math.floor((e-n)/1e3)),l=[`${oe}=${encodeURIComponent(r)}`,"path=/","SameSite=Lax",`max-age=${o}`];typeof window<"u"&&window.location.protocol==="https:"&&l.push("Secure"),i&&l.push(`domain=${i}`),document.cookie=l.join("; "),c.debug("[CookieSync] Cookie set successfully",{domain:i||"(current host)",maxAgeSeconds:o,tokenLength:r.length})}catch(i){c.error("[CookieSync] Failed to set cookie",i instanceof Error?i:{message:String(i)})}},Ft=r=>{if(typeof document>"u"){c.debug("[CookieSync] No document available (SSR), skipping cookie clear");return}try{let e=Se(r),t=[`${oe}=`,"path=/","max-age=0","expires=Thu, 01 Jan 1970 00:00:00 GMT"];e&&t.push(`domain=${e}`),document.cookie=t.join("; "),document.cookie=`${oe}=; path=/; max-age=0; expires=Thu, 01 Jan 1970 00:00:00 GMT`,c.debug("[CookieSync] Cookie cleared successfully",{domain:e||"(current host)"})}catch(e){c.error("[CookieSync] Failed to clear cookie",e instanceof Error?e:{message:String(e)})}},zt=()=>{if(typeof document>"u")return null;try{let e=document.cookie.split(";").map(i=>i.trim()).find(i=>i.startsWith(`${oe}=`));if(!e)return null;let t=e.split("=")[1];return t?decodeURIComponent(t):null}catch(r){return c.error("[CookieSync] Failed to read cookie",r instanceof Error?r:{message:String(r)}),null}},Q={setCrossSubdomainCookie:Ot,clearCrossSubdomainCookie:Ft,getCrossSubdomainCookie:zt,getCookieDomain:Se};var se=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(e={}){if(!this.initialized){if(this.config={storageType:"localStorage",autoRestore:!0,enableLogging:!1,env:"stg",...e},v.setStorageType(this.config.storageType||"localStorage"),this.config.publicApiKey&&!this.crudifyInitialized&&await this.ensureCrudifyInitialized(),L.setTokenInvalidationCallback(()=>{this.log("Tokens invalidated by crudify-core"),H.emit("SESSION_EXPIRED",{message:"Your session has expired. Please log in again.",source:"crudify-core.clearTokensAndRefreshState"})}),this.config.apiEndpointAdmin&&this.config.apiKeyEndpointAdmin){let t=await v.getTokens();t?await v.saveTokens({...t,apiEndpointAdmin:this.config.apiEndpointAdmin,apiKeyEndpointAdmin:this.config.apiKeyEndpointAdmin}):await v.saveTokens({accessToken:"",refreshToken:"",expiresAt:0,refreshExpiresAt:0,apiEndpointAdmin:this.config.apiEndpointAdmin,apiKeyEndpointAdmin:this.config.apiKeyEndpointAdmin})}this.config.autoRestore&&await this.restoreSession(),this.initialized=!0}}async login(e,t){try{let i=await L.login(e,t);if(!i.success)return{success:!1,error:this.formatError(i.errors),rawResponse:i};let n=await v.getTokens(),o=i.data,l={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 v.saveTokens(l),v.markSuccessfulLogin(),this.lastActivityTime=Date.now(),Q.setCrossSubdomainCookie(l.accessToken,l.expiresAt,this.config.env),B.notifyLogin(),this.config.onLoginSuccess?.(l),{success:!0,tokens:l,data:o}}catch(i){return c.error("[SessionManager] Login error",i instanceof Error?i:{message:String(i)}),{success:!1,error:i instanceof Error?i.message:"Unknown error"}}}async logout(){try{this.log("Logging out..."),H.emit("LOGOUT",{message:"User logged out",source:"SessionManager.logout"}),Q.clearCrossSubdomainCookie(this.config.env),await L.logout(),await v.clearTokens(),B.notifyLogout(),this.log("Logout successful"),this.config.onLogout?.()}catch(e){this.log("Logout error",{error:e instanceof Error?e.message:String(e)}),await v.clearTokens(),B.notifyLogout()}}async restoreSession(){try{this.log("Attempting to restore session...");let e=await v.getTokens();if(!e)return this.log("No valid tokens found in storage"),!1;if(Date.now()>=e.refreshExpiresAt)return this.log("Refresh token expired, clearing storage"),await v.clearTokens(),!1;if(L.setTokens({accessToken:e.accessToken,refreshToken:e.refreshToken,expiresAt:e.expiresAt,refreshExpiresAt:e.refreshExpiresAt}),L.getTokenData().isValid===!1){if(this.log("Restored access token is invalid or expired"),Date.now()<e.refreshExpiresAt&&(this.log("Access token expired but refresh is valid, attempting refresh..."),await this.refreshTokens())){this.log("Session restored successfully via token refresh");let n=await v.getTokens();return n&&this.config.onSessionRestored?.(n),!0}return await v.clearTokens(),await L.logout(),!1}return this.log("Session restored successfully"),this.lastActivityTime=Date.now(),this.config.onSessionRestored?.(e),!0}catch(e){return this.log("Session restore error",{error:e instanceof Error?e.message:String(e)}),await v.clearTokens(),await L.logout(),!1}}async isAuthenticated(){return L.isLogin()||await v.hasValidTokens()}async getTokenInfo(){let e=L.getTokenData(),t=await v.getExpirationInfo(),i=await v.getTokens();return{isLoggedIn:await this.isAuthenticated(),crudifyTokens:e,storageInfo:t,hasValidTokens:await v.hasValidTokens(),apiEndpointAdmin:i?.apiEndpointAdmin,apiKeyEndpointAdmin:i?.apiKeyEndpointAdmin}}async refreshTokens(){if(this.isRefreshingLocally&&this.refreshPromise)return this.log("Refresh already in progress, waiting for existing promise..."),this.refreshPromise;this.isRefreshingLocally=!0,this.refreshPromise=this._performRefresh();try{return await this.refreshPromise}finally{this.isRefreshingLocally=!1,this.refreshPromise=null}}async _performRefresh(){try{this.log("Starting token refresh...");let e=await L.refreshAccessToken();if(!e.success)return this.log("Token refresh failed",{errors:e.errors}),await v.clearTokens(),this.config.showNotification?.(this.getSessionExpiredMessage(),"warning"),this.config.onSessionExpired?.(),!1;let t=e.data,i={accessToken:t.token,refreshToken:t.refreshToken,expiresAt:t.expiresAt,refreshExpiresAt:t.refreshExpiresAt};return await v.saveTokens(i),this.log("Tokens refreshed and saved successfully"),Q.setCrossSubdomainCookie(i.accessToken,i.expiresAt,this.config.env),this.lastActivityTime=Date.now(),B.notifyTokenRefreshed(),!0}catch(e){return this.log("Token refresh error",{error:e instanceof Error?e.message:String(e)}),await v.clearTokens(),this.config.showNotification?.(this.getSessionExpiredMessage(),"warning"),this.config.onSessionExpired?.(),!1}}isRefreshing(){return this.isRefreshingLocally}setupResponseInterceptor(){L.setResponseInterceptor(async e=>{this.updateLastActivity();let t=this.detectAuthorizationError(e);if(t.isAuthError){if(this.log("\u{1F6A8} Authorization error detected:",{errorType:t.errorType,shouldLogout:t.shouldTriggerLogout}),t.isRefreshTokenInvalid||t.isTokenRefreshFailed)return this.log("Refresh token invalid, emitting TOKEN_REFRESH_FAILED event"),H.emit("TOKEN_REFRESH_FAILED",{message:t.userFriendlyMessage,error:t.errorDetails,source:"SessionManager.setupResponseInterceptor"}),e;t.shouldTriggerLogout&&(await v.hasValidTokens()&&!t.isIrrecoverable?(this.log("Access token expired, emitting TOKEN_EXPIRED event"),H.emit("TOKEN_EXPIRED",{message:"Access token expired, refresh needed",error:t.errorDetails,source:"SessionManager.setupResponseInterceptor"})):(this.log("No valid tokens or irrecoverable error, emitting SESSION_EXPIRED event"),H.emit("SESSION_EXPIRED",{message:t.userFriendlyMessage,error:t.errorDetails,source:"SessionManager.setupResponseInterceptor"})))}return e}),this.log("Response interceptor configured (non-blocking mode)")}async ensureCrudifyInitialized(){if(!this.crudifyInitialized)try{this.log("Initializing crudify SDK...");let e=L.getTokenData();if(e&&e.endpoint){this.log("Crudify already initialized by another service"),this.crudifyInitialized=!0;return}let t=this.config.env||"stg";L.config(t);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(e){throw c.error("[SessionManager] Failed to initialize crudify",e instanceof Error?e:{message:String(e)}),e}}detectAuthorizationError(e){let t={isAuthError:!1,isRefreshTokenInvalid:!1,isTokenRefreshFailed:!1,isTokenExpired:!1,isUnauthorized:!1,isIrrecoverable:!1,shouldTriggerLogout:!1,errorType:"",errorDetails:null,userFriendlyMessage:""};if(e.errors&&Array.isArray(e.errors)){let i=e.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&&(t.isAuthError=!0,t.errorType="GraphQL Array",t.errorDetails=i,t.shouldTriggerLogout=!0,t.userFriendlyMessage="Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente.",(i.message?.includes("TOKEN")||i.message?.includes("Token"))&&(t.isTokenExpired=!0),i.extensions?.code==="UNAUTHENTICATED"&&(t.isUnauthorized=!0))}if(!t.isAuthError&&e.errors&&typeof e.errors=="object"&&!Array.isArray(e.errors)){let n=Object.values(e.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"&&(t.isAuthError=!0,t.errorType="GraphQL Object",t.errorDetails=e.errors,t.shouldTriggerLogout=!0,n.includes("TOKEN_REFRESH_FAILED")?(t.isTokenRefreshFailed=!0,t.isRefreshTokenInvalid=!0,t.isIrrecoverable=!0,t.userFriendlyMessage="Tu sesi\xF3n ha caducado. Por favor, inicia sesi\xF3n nuevamente."):n.includes("TOKEN_HAS_EXPIRED")||n.includes("SESSION_EXPIRED")?(t.isTokenExpired=!0,t.userFriendlyMessage="Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente."):n.includes("INVALID_TOKEN")?(t.isTokenExpired=!0,t.isIrrecoverable=!0,t.userFriendlyMessage="Token inv\xE1lido. Por favor, inicia sesi\xF3n nuevamente."):t.userFriendlyMessage="Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente.")}if(!t.isAuthError&&e.data?.response?.status){let i=e.data.response.status.toUpperCase();(i==="UNAUTHORIZED"||i==="UNAUTHENTICATED")&&(t.isAuthError=!0,t.errorType="Status",t.errorDetails=e.data.response,t.isUnauthorized=!0,t.shouldTriggerLogout=!0,t.isIrrecoverable=!0,t.userFriendlyMessage="Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente.")}if(!t.isAuthError&&e.data?.response?.data)try{let i=typeof e.data.response.data=="string"?JSON.parse(e.data.response.data):e.data.response.data;(i.error==="REFRESH_TOKEN_INVALID"||i.error==="TOKEN_EXPIRED"||i.error==="INVALID_TOKEN")&&(t.isAuthError=!0,t.errorType="Parsed Data",t.errorDetails=i,t.shouldTriggerLogout=!0,t.isIrrecoverable=!0,i.error==="REFRESH_TOKEN_INVALID"?(t.isRefreshTokenInvalid=!0,t.isTokenRefreshFailed=!0,t.userFriendlyMessage="Tu sesi\xF3n ha caducado. Por favor, inicia sesi\xF3n nuevamente."):(t.isTokenExpired=!0,t.userFriendlyMessage="Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente."))}catch{}if(!t.isAuthError&&e.errorCode){let i=String(e.errorCode).toUpperCase();(i==="UNAUTHORIZED"||i==="UNAUTHENTICATED"||i==="TOKEN_EXPIRED"||i==="INVALID_TOKEN")&&(t.isAuthError=!0,t.errorType="Error Code",t.errorDetails={errorCode:i},t.shouldTriggerLogout=!0,i==="TOKEN_EXPIRED"?t.isTokenExpired=!0:t.isUnauthorized=!0,t.userFriendlyMessage="Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente.")}return t}updateLastActivity(){this.lastActivityTime=Date.now(),this.log("Last activity updated")}getTimeSinceLastActivity(){return this.lastActivityTime===0?0:Date.now()-this.lastActivityTime}checkInactivity(){let e=this.getTimeSinceLastActivity();if(this.lastActivityTime===0)return"none";let t=1800*1e3;return e>t?(this.log(`Inactivity timeout: ${Math.floor(e/6e4)} minutes since last activity`),"logout"):"none"}async clearSession(){Q.clearCrossSubdomainCookie(this.config.env),await v.clearTokens(),await L.logout(),this.lastActivityTime=0,this.log("Session cleared completely")}getSessionExpiredMessage(){return this.config.translateFn?Fe("SESSION_EXPIRED",{translateFn:this.config.translateFn,enableDebug:this.config.enableLogging}):"Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente."}log(e,t){this.config.enableLogging&&c.debug(`[SessionManager] ${e}`,t)}formatError(e){return e?typeof e=="string"?e:typeof e=="object"?Object.values(e).flat().map(String).join(", "):"Authentication failed":"Unknown error"}};import{useEffect as $t,useCallback as j}from"react";import{useState as Ut,useCallback as ee}from"react";var Ge={isAuthenticated:!1,isLoading:!0,isLoggingOut:!1,isInitialized:!1,tokens:null,error:null};function _e(){let[r,e]=Ut(Ge),t=ee(s=>{e(f=>({...f,isLoading:s}))},[]),i=ee((s,f)=>{e(E=>({...E,isAuthenticated:s,tokens:f,error:s?null:E.error}))},[]),n=ee(s=>{e(f=>({...f,isLoggingOut:s}))},[]),o=ee(s=>{e(f=>({...f,error:s}))},[]),l=ee(s=>{e(f=>({...f,isInitialized:s}))},[]);return{state:r,setState:e,setLoading:t,setAuthenticated:i,setLoggingOut:n,setError:o,setInitialized:l}}import{useCallback as le}from"react";var ae={AGGRESSIVE:3e4,MODERATE:6e4,RELAXED:12e4},Te={AGGRESSIVE:300*1e3,MODERATE:1800*1e3},Ve=.5;function $e(r){return r?r.expiresAt-Date.now()<3e5:!1}function Ye(r){return r?Math.max(0,r.expiresAt-Date.now()):0}function We(r){return r?Math.max(0,r.refreshExpiresAt-Date.now()):0}function $(r){return r.crudifyTokens.accessToken?{accessToken:r.crudifyTokens.accessToken,refreshToken:r.crudifyTokens.refreshToken||"",expiresAt:r.crudifyTokens.expiresAt,refreshExpiresAt:r.crudifyTokens.refreshExpiresAt}:null}function Be(r){let{sessionManager:e,stateManager:t}=r,i=le(async(s,f)=>{t.setState(E=>({...E,isLoading:!0,isLoggingOut:!1,error:null}));try{let E=await e.login(s,f);return E.success&&E.tokens?t.setState(b=>({...b,isAuthenticated:!0,tokens:E.tokens,isLoading:!1,isLoggingOut:!1,error:null})):t.setState(b=>({...b,isAuthenticated:!1,tokens:null,isLoading:!1,isLoggingOut:!1,error:null})),E}catch(E){let b=E instanceof Error?E.message:"Login failed";c.error("[useSession] Login error",E instanceof Error?E:{message:b});let S=b.includes("INVALID_CREDENTIALS")||b.includes("Invalid email")||b.includes("Invalid password")||b.includes("credentials");return t.setState(m=>({...m,isAuthenticated:!1,tokens:null,isLoading:!1,isLoggingOut:!1,error:S?null:b})),{success:!1,error:b}}},[e,t]),n=le(async()=>{t.setState(s=>({...s,isLoading:!0,isLoggingOut:!0}));try{await e.logout(),t.setState(s=>({...s,isAuthenticated:!1,tokens:null,isLoading:!1,error:null}))}catch(s){t.setState(f=>({...f,isAuthenticated:!1,tokens:null,isLoading:!1,error:s instanceof Error?s.message:"Logout error"}))}},[e,t]),o=le(async()=>{try{let s=await e.refreshTokens();if(s){let f=await e.getTokenInfo();t.setState(E=>({...E,tokens:$(f),error:null}))}else t.setState(f=>({...f,isAuthenticated:!1,tokens:null,error:"Token refresh failed"}));return s}catch(s){return t.setState(f=>({...f,isAuthenticated:!1,tokens:null,error:s instanceof Error?s.message:"Token refresh failed"})),!1}},[e,t]),l=le(()=>{t.setError(null)},[t]);return{login:i,logout:n,refreshTokens:o,clearError:l}}import{useEffect as Ht,useCallback as Gt}from"react";function _t(r){return r<Te.AGGRESSIVE?ae.AGGRESSIVE:r<Te.MODERATE?ae.MODERATE:ae.RELAXED}function Xe(r){let{isAuthenticated:e,tokens:t,sessionManager:i,onTokensRefreshed:n,onSessionExpired:o,onSetLoading:l,logout:s}=r,f=Gt(()=>{i.updateLastActivity()},[i]);Ht(()=>{if(!e||!t)return;let b=ze.getInstance().subscribe(f);window.addEventListener("popstate",f);let S,m=!0,I=async()=>{if(!m)return;let k=(await i.getTokenInfo()).crudifyTokens.expiresIn||0,R=_t(k);S=setTimeout(async()=>{if(!m)return;if(i.isRefreshing()){I();return}let x=await i.getTokenInfo(),O=x.crudifyTokens.expiresIn||0,z=((x.crudifyTokens.expiresAt||0)-(Date.now()-O))*Ve;if(O>0&&O<=z)if(l(!0),await i.refreshTokens()){let Z=await i.getTokenInfo();n($(Z)),l(!1)}else n(null),o(),l(!1);i.getTimeSinceLastActivity()>18e5?await s():m&&I()},R)};return I(),()=>{m=!1,clearTimeout(S),window.removeEventListener("popstate",f),b()}},[e,t,i,f,n,o,l,s])}import{useEffect as Vt}from"react";function Ze(r){let{sessionManager:e,onTokensUpdated:t,onSessionExpired:i,onSetLoading:n,onSetError:o}=r;Vt(()=>{let l=H.subscribe(async s=>{if(s.type==="TOKEN_EXPIRED"){if(e.isRefreshing())return;n(!0);try{if(await e.refreshTokens()){let E=await e.getTokenInfo();t($(E)),n(!1)}else H.emit("SESSION_EXPIRED",{message:"Failed to refresh token after detecting expiration",source:"useSession.TOKEN_EXPIRED handler"})}catch(f){H.emit("SESSION_EXPIRED",{message:f instanceof Error?f.message:"Unknown error during refresh",source:"useSession.TOKEN_EXPIRED handler (error)"})}}(s.type==="SESSION_EXPIRED"||s.type==="TOKEN_REFRESH_FAILED")&&(t(null),n(!1),o(s.details?.message?.toString()||"Session expired"),i())});return()=>l()},[e,t,i,n,o])}import{useEffect as qe}from"react";function je(r){let{isAuthenticated:e,onTokensUpdated:t,onSessionExpired:i}=r;qe(()=>{let n=async l=>{switch(l.type){case"SESSION_STARTED":case"TOKEN_REFRESHED":try{await v.ensureInitialized();let s=await v.getTokens();s&&(c.debug(`[useCrossTabSync] Syncing ${l.type} from tab ${l.tabId}`),t(s))}catch(s){c.warn("[useCrossTabSync] Failed to read tokens after cross-tab event",{error:s instanceof Error?s.message:String(s)})}break;case"SESSION_ENDED":try{await v.hasValidTokens()||(c.debug(`[useCrossTabSync] Syncing SESSION_ENDED from tab ${l.tabId}`),t(null),e&&i())}catch(s){c.warn("[useCrossTabSync] Failed to verify tokens after logout event",{error:s instanceof Error?s.message:String(s)})}break;case"SESSION_PING":case"SESSION_PONG":break}},o=B.subscribe(n);return()=>o()},[e,t,i]),qe(()=>{let n=v.subscribeToChanges(async(o,l,s)=>{if(l===v.SYNC_EVENTS.TOKENS_CLEARED){if(await v.hasValidTokens())return;s&&e?(t(null),i()):s&&t(null)}else l===v.SYNC_EVENTS.TOKENS_UPDATED&&o&&t(o)});return()=>n()},[e,t,i])}async function Je(r){let{sessionManager:e,options:t,stateActions:i}=r;try{i.setState(s=>({...s,isLoading:!0,error:null}));let n={autoRestore:t.autoRestore??!0,enableLogging:t.enableLogging??!1,showNotification:t.showNotification,translateFn:t.translateFn,apiEndpointAdmin:t.apiEndpointAdmin,apiKeyEndpointAdmin:t.apiKeyEndpointAdmin,publicApiKey:t.publicApiKey,env:t.env||"stg",onSessionExpired:()=>{i.setState(s=>({...s,isAuthenticated:!1,tokens:null,error:"Session expired"})),t.onSessionExpired?.()},onSessionRestored:s=>{i.setState(f=>({...f,isAuthenticated:!0,tokens:s,error:null})),t.onSessionRestored?.(s)},onLoginSuccess:s=>{i.setState(f=>({...f,isAuthenticated:!0,tokens:s,error:null}))},onLogout:()=>{i.setState(s=>({...s,isAuthenticated:!1,tokens:null,error:null}))}};await e.initialize(n),e.setupResponseInterceptor();let o=await e.isAuthenticated(),l=await e.getTokenInfo();i.setState(s=>({...s,isAuthenticated:o,isInitialized:!0,isLoading:!1,isLoggingOut:!1,tokens:$(l)}))}catch(n){let o=n instanceof Error?n.message:"Initialization failed";c.error("[useSession] Initialize failed",n instanceof Error?n:{message:o}),i.setState(l=>({...l,isLoading:!1,isInitialized:!0,isLoggingOut:!1,error:o}))}}function ve(r={}){let e=se.getInstance(),t=_e(),{state:i}=t,{login:n,logout:o,refreshTokens:l,clearError:s}=Be({sessionManager:e,stateManager:t}),f=j(g=>{t.setAuthenticated(!!g,g)},[t]),E=j(()=>{t.setAuthenticated(!1,null),r.onSessionExpired?.()},[t,r.onSessionExpired]),b=j(g=>{t.setLoading(g)},[t]),S=j(g=>{t.setError(g)},[t]);$t(()=>{Je({sessionManager:e,options:r,stateActions:t})},[]),Xe({isAuthenticated:i.isAuthenticated,tokens:i.tokens,sessionManager:e,onTokensRefreshed:f,onSessionExpired:E,onSetLoading:b,logout:o}),Ze({sessionManager:e,onTokensUpdated:f,onSessionExpired:E,onSetLoading:b,onSetError:S}),je({isAuthenticated:i.isAuthenticated,onTokensUpdated:f,onSessionExpired:E});let m=j(()=>{e.updateLastActivity()},[e]),I=j(async()=>e.getTokenInfo(),[e]);return{...i,login:n,logout:o,refreshTokens:l,clearError:s,getTokenInfo:I,updateActivity:m,isExpiringSoon:$e(i.tokens),expiresIn:Ye(i.tokens),refreshExpiresIn:We(i.tokens)}}import{useState as Qe,createContext as Yt,useContext as Wt,useCallback as ce,useEffect as Bt}from"react";import{Snackbar as Xt,Alert as Zt,Box as qt,Portal as jt}from"@mui/material";import{v4 as Jt}from"uuid";import Qt from"dompurify";import{jsx as X,jsxs as ii}from"react/jsx-runtime";var et=Yt(null),ei=r=>Qt.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}),be=({children:r,maxNotifications:e=5,defaultAutoHideDuration:t=6e3,position:i={vertical:"top",horizontal:"right"},enabled:n=!1,allowHtml:o=!1})=>{let[l,s]=Qe([]),f=ce((m,I="info",g)=>{if(!n)return"";if(!m||typeof m!="string")return c.warn("GlobalNotificationProvider: Invalid message provided"),"";m.length>1e3&&(c.warn("GlobalNotificationProvider: Message too long, truncating"),m=m.substring(0,1e3)+"...");let k=Jt(),R={id:k,message:m,severity:I,autoHideDuration:g?.autoHideDuration??t,persistent:g?.persistent??!1,allowHtml:g?.allowHtml??o};return s(x=>[...x.length>=e?x.slice(-(e-1)):x,R]),k},[e,t,n,o]),E=ce(m=>{s(I=>I.filter(g=>g.id!==m))},[]),b=ce(()=>{s([])},[]),S={showNotification:f,hideNotification:E,clearAllNotifications:b};return ii(et.Provider,{value:S,children:[r,n&&X(jt,{children:X(qt,{sx:{position:"fixed",zIndex:9999,[i.vertical]:(i.vertical==="top",24),[i.horizontal]:i.horizontal==="right"||i.horizontal==="left"?24:"50%",...i.horizontal==="center"&&{transform:"translateX(-50%)"},display:"flex",flexDirection:i.vertical==="top"?"column":"column-reverse",gap:1,maxWidth:"400px",width:"auto"},children:l.map(m=>X(ti,{notification:m,onClose:()=>E(m.id)},m.id))})})]})},ti=({notification:r,onClose:e})=>{let[t,i]=Qe(!0),n=ce((o,l)=>{l!=="clickaway"&&(i(!1),setTimeout(e,300))},[e]);return Bt(()=>{if(!r.persistent&&r.autoHideDuration){let o=setTimeout(()=>{n()},r.autoHideDuration);return()=>clearTimeout(o)}},[r.autoHideDuration,r.persistent,n]),X(Xt,{open:t,onClose:n,sx:{position:"relative","& .MuiSnackbarContent-root":{minWidth:"auto"}},TransitionProps:{enter:!0,exit:!0},children:X(Zt,{variant:"filled",severity:r.severity,onClose:n,sx:{width:"100%",minWidth:"280px",maxWidth:"400px",wordBreak:"break-word"},children:r.allowHtml?X("span",{dangerouslySetInnerHTML:{__html:ei(r.message)}}):X("span",{children:r.message})})})},tt=()=>{let r=Wt(et);if(!r)throw new Error("useGlobalNotification debe ser usado dentro de un GlobalNotificationProvider");return r};import{createContext as ri,useContext as ni,useEffect as oi,useState as te}from"react";import ie from"@nocios/crudify-sdk";var Ie=class r{constructor(){this.listeners=[];this.credentials=null;this.isReady=!1}static getInstance(){return r.instance||(r.instance=new r),r.instance}notifyCredentialsReady(e){this.credentials=e,this.isReady=!0,this.listeners.forEach(t=>{try{t(e)}catch(i){c.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(e=>{this.listeners.push(e)})}reset(){this.credentials=null,this.isReady=!1,this.listeners=[]}areCredentialsReady(){return this.isReady&&this.credentials!==null}},ue=Ie.getInstance();import{jsx as si}from"react/jsx-runtime";var it=ri(void 0),rt=({config:r,children:e})=>{let[t,i]=te(!0),[n,o]=te(null),[l,s]=te(!1),[f,E]=te(""),[b,S]=te();oi(()=>{if(!r.publicApiKey){o("No publicApiKey provided"),i(!1),s(!1);return}let I=`${r.publicApiKey}-${r.env}`;if(I===f&&l){i(!1);return}(async()=>{i(!0),o(null),s(!1);try{ie.config(r.env||"prod");let k=await ie.init(r.publicApiKey,"none");if(S(k),typeof ie.transaction=="function"&&typeof ie.login=="function")s(!0),E(I),k.apiEndpointAdmin&&k.apiKeyEndpointAdmin&&ue.notifyCredentialsReady({apiUrl:k.apiEndpointAdmin,apiKey:k.apiKeyEndpointAdmin});else throw new Error("Crudify methods not properly initialized")}catch(k){let R=k instanceof Error?k.message:"Failed to initialize Crudify";c.error("[CrudifyProvider] Initialization error",k instanceof Error?k:{message:String(k)}),o(R),s(!1)}finally{i(!1)}})()},[r.publicApiKey,r.env,f,l]);let m={crudify:l?ie:null,isLoading:t,error:n,isInitialized:l,adminCredentials:b};return si(it.Provider,{value:m,children:e})},nt=()=>{let r=ni(it);if(r===void 0)throw new Error("useCrudify must be used within a CrudifyProvider");return r};import ai,{createContext as li,useContext as ci,useMemo as ke}from"react";import{Fragment as di,jsx as P,jsxs as G}from"react/jsx-runtime";var st=li(void 0);function ot({children:r,options:e={},config:t,showNotifications:i=!1,notificationOptions:n={}}){let o;try{let{showNotification:g}=tt();o=g}catch{}let l={};try{let g=nt();g.isInitialized&&g.adminCredentials&&(l=g.adminCredentials)}catch{}let s=ke(()=>{let g=he({publicApiKey:t?.publicApiKey,env:t?.env,enableDebug:e?.enableLogging});return{publicApiKey:g.publicApiKey,env:g.env||"prod"}},[t,e?.enableLogging]),f=ai.useMemo(()=>({...e,showNotification:o,apiEndpointAdmin:l.apiEndpointAdmin,apiKeyEndpointAdmin:l.apiKeyEndpointAdmin,publicApiKey:s.publicApiKey,env:s.env,onSessionExpired:()=>{e.onSessionExpired?.()}}),[e,o,l.apiEndpointAdmin,l.apiKeyEndpointAdmin,s]),E=ve(f),b=ke(()=>{let g=he({publicApiKey:t?.publicApiKey,env:t?.env,appName:t?.appName,logo:t?.logo,loginActions:t?.loginActions,enableDebug:e?.enableLogging});return{publicApiKey:g.publicApiKey,env:g.env,appName:g.appName,loginActions:g.loginActions,logo:g.logo}},[t,e?.enableLogging]),S=ke(()=>{if(!E.tokens?.accessToken||!E.isAuthenticated)return null;try{let g=Ue(E.tokens.accessToken);if(g&&g.sub&&g.email&&g.subscriber){let k={_id:g.sub,email:g.email,subscriberKey:g.subscriber};return Object.keys(g).forEach(R=>{["sub","email","subscriber"].includes(R)||(k[R]=g[R])}),k}}catch(g){c.error("Error decoding JWT token for sessionData",g instanceof Error?g:{message:String(g)})}return null},[E.tokens?.accessToken,E.isAuthenticated]),m={...E,sessionData:S,config:b},I={enabled:i,maxNotifications:n.maxNotifications||5,defaultAutoHideDuration:n.defaultAutoHideDuration||6e3,position:n.position||{vertical:"top",horizontal:"right"}};return P(st.Provider,{value:m,children:r})}function Jr(r){let e={enabled:r.showNotifications,maxNotifications:r.notificationOptions?.maxNotifications||5,defaultAutoHideDuration:r.notificationOptions?.defaultAutoHideDuration||6e3,position:r.notificationOptions?.position||{vertical:"top",horizontal:"right"},allowHtml:r.notificationOptions?.allowHtml||!1};return r.config?.publicApiKey?P(rt,{config:{publicApiKey:r.config.publicApiKey,env:r.config.env||"prod",appName:r.config.appName,loginActions:r.config.loginActions,logo:r.config.logo},children:P(be,{...e,children:P(ot,{...r})})}):P(be,{...e,children:P(ot,{...r})})}function ui(){let r=ci(st);if(r===void 0)throw new Error("useSessionContext must be used within a SessionProvider");return r}function Qr(){let r=ui();return r.isInitialized?G("div",{style:{padding:"10px",margin:"10px",border:"1px solid #ccc",borderRadius:"4px",fontSize:"12px",fontFamily:"monospace"},children:[P("h4",{children:"Session Debug Info"}),G("div",{children:[P("strong",{children:"Authenticated:"})," ",r.isAuthenticated?"Yes":"No"]}),G("div",{children:[P("strong",{children:"Loading:"})," ",r.isLoading?"Yes":"No"]}),G("div",{children:[P("strong",{children:"Error:"})," ",r.error||"None"]}),r.tokens&&G(di,{children:[G("div",{children:[P("strong",{children:"Access Token:"})," ",r.tokens.accessToken.substring(0,20),"..."]}),G("div",{children:[P("strong",{children:"Refresh Token:"})," ",r.tokens.refreshToken.substring(0,20),"..."]}),G("div",{children:[P("strong",{children:"Access Expires In:"})," ",Math.round(r.expiresIn/1e3/60)," minutes"]}),G("div",{children:[P("strong",{children:"Refresh Expires In:"})," ",Math.round(r.refreshExpiresIn/1e3/60/60)," hours"]}),G("div",{children:[P("strong",{children:"Expiring Soon:"})," ",r.isExpiringSoon?"Yes":"No"]})]})]}):P("div",{children:"Session not initialized"})}import{useState as de,useEffect as at,useCallback as lt,useRef as fe}from"react";import fi from"@nocios/crudify-sdk";var sn=(r={})=>{let{autoFetch:e=!0,retryOnError:t=!1,maxRetries:i=3}=r,[n,o]=de(null),[l,s]=de(!1),[f,E]=de(null),[b,S]=de({}),m=fe(null),I=fe(!0),g=fe(0),k=fe(0),R=lt(()=>{o(null),E(null),s(!1),S({})},[]),x=lt(async()=>{let O=Ke();if(!O){I.current&&(E("No user email available"),s(!1));return}m.current&&m.current.abort();let w=new AbortController;m.current=w;let F=++g.current;try{I.current&&(s(!0),E(null));let z=await fi.readItems("users",{filter:{email:O},pagination:{limit:1}});if(F===g.current&&I.current&&!w.signal.aborted){let D=z.data;if(z.success&&D&&D.length>0){let T=D[0];o(T);let Z={fullProfile:T,totalFields:Object.keys(T).length,displayData:{id:T.id,email:T.email,username:T.username,firstName:T.firstName,lastName:T.lastName,fullName:T.fullName||`${T.firstName||""} ${T.lastName||""}`.trim(),role:T.role,permissions:T.permissions||[],isActive:T.isActive,lastLogin:T.lastLogin,createdAt:T.createdAt,updatedAt:T.updatedAt,...Object.keys(T).filter(V=>!["id","email","username","firstName","lastName","fullName","role","permissions","isActive","lastLogin","createdAt","updatedAt"].includes(V)).reduce((V,ne)=>({...V,[ne]:T[ne]}),{})}};S(Z),E(null),k.current=0}else E("User profile not found"),o(null),S({})}}catch(z){if(F===g.current&&I.current){let D=z;if(D.name==="AbortError")return;t&&k.current<i&&(D.message?.includes("Network Error")||D.message?.includes("Failed to fetch"))?(k.current++,setTimeout(()=>{I.current&&x()},1e3*k.current)):(E("Failed to load user profile"),o(null),S({}))}}finally{F===g.current&&I.current&&s(!1),m.current===w&&(m.current=null)}},[t,i]);return at(()=>{e&&x()},[e,x]),at(()=>(I.current=!0,()=>{I.current=!1,m.current&&(m.current.abort(),m.current=null)}),[]),{userProfile:n,loading:l,error:f,extendedData:b,refreshProfile:x,clearProfile:R}};import{useState as Ae,useEffect as gi,useCallback as ge,useRef as pi}from"react";import mi from"@nocios/crudify-sdk";var un=(r,e={})=>{let{autoFetch:t=!0,onSuccess:i,onError:n}=e,{prefix:o,padding:l=0,separator:s=""}=r,[f,E]=Ae(""),[b,S]=Ae(!1),[m,I]=Ae(null),g=pi(!1),k=ge(w=>{let F=String(w).padStart(l,"0");return`${o}${s}${F}`},[o,l,s]),R=ge(async()=>{S(!0),I(null);try{let w=await mi.getNextSequence(o),F=w.data;if(w.success&&F?.value){let z=k(F.value);E(z),i?.(z)}else{let z=w.errors?._error?.[0]||"Failed to generate code";I(z),n?.(z)}}catch(w){let F=w instanceof Error?w.message:"Unknown error";I(F),n?.(F)}finally{S(!1)}},[o,k,i,n]),x=ge(async()=>{await R()},[R]),O=ge(()=>{I(null)},[]);return gi(()=>{t&&!f&&!g.current&&(g.current=!0,R())},[t,f,R]),{value:f,loading:b,error:m,regenerate:x,clearError:O}};import xe from"@nocios/crudify-sdk";var we=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(e){let{priority:t,publicApiKey:i,env:n,enableLogging:o,requestedBy:l}=e;if(this.state.status==="INITIALIZED"){this.state.publicApiKey!==i&&c.warn(`[CrudifyInitialization] ${l} attempted to initialize with different key. Already initialized with key: ${this.state.publicApiKey?.slice(0,10)}... by ${this.state.initializedBy}`);return}if(this.initializationPromise)return o&&c.debug(`[CrudifyInitialization] ${l} waiting for ongoing initialization...`),this.initializationPromise;if(t==="LOW"&&this.highPriorityInitializerPresent&&this.state.status==="UNINITIALIZED"){if(o&&c.debug(`[CrudifyInitialization] ${l} (LOW priority) waiting for HIGH priority initializer...`),this.waitingForHighPriority.add(l),await this.waitForHighPriorityOrTimeout(o),this.waitingForHighPriority.delete(l),this.getState().status==="INITIALIZED"){o&&c.debug(`[CrudifyInitialization] ${l} found initialization completed by HIGH priority`);return}o&&c.warn(`[CrudifyInitialization] ${l} timeout waiting for HIGH priority, initializing with LOW priority`)}t==="HIGH"&&this.state.status==="INITIALIZING"&&this.state.priority==="LOW"&&(c.warn(`[CrudifyInitialization] HIGH priority request from ${l} interrupting LOW priority initialization by ${this.state.initializedBy}`),this.state.status="UNINITIALIZED",this.initializationPromise=null),o&&c.debug(`[CrudifyInitialization] ${l} starting initialization (${t} priority)...`),this.state.status="INITIALIZING",this.state.priority=t,this.state.initializedBy=l,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&&c.info(`[CrudifyInitialization] Successfully initialized by ${l} (${t} priority)`)}catch(s){throw this.state.status="ERROR",this.state.error=s instanceof Error?s:new Error(String(s)),this.initializationPromise=null,c.error(`[CrudifyInitialization] Initialization failed for ${l}`,s instanceof Error?s:{message:String(s)}),s}}async waitForHighPriorityOrTimeout(e){return new Promise(t=>{let n=0,o=setInterval(()=>{if(n+=10,this.state.status==="INITIALIZED"&&this.state.priority==="HIGH"){clearInterval(o),t();return}if(this.state.status==="INITIALIZING"&&this.state.priority==="HIGH"){n=0;return}n>=this.HIGH_PRIORITY_WAIT_TIMEOUT&&(clearInterval(o),e&&c.debug(`[CrudifyInitialization] Timeout waiting for HIGH priority (${this.HIGH_PRIORITY_WAIT_TIMEOUT}ms)`),t())},10)})}async performInitialization(e,t,i){let n=xe.getTokenData();if(n&&n.endpoint){i&&c.debug("[CrudifyInitialization] SDK already initialized externally");return}xe.config(t);let o=i?"debug":"none",l=await xe.init(e,o);if(l.success===!1)throw new Error(`Crudify initialization failed: ${JSON.stringify(l.errors||"Unknown error")}`);l.apiEndpointAdmin&&l.apiKeyEndpointAdmin&&ue.notifyCredentialsReady({apiUrl:l.apiEndpointAdmin,apiKey:l.apiKeyEndpointAdmin})}reset(){this.state={status:"UNINITIALIZED",priority:null,publicApiKey:null,env:null,error:null,initializedBy:null},this.initializationPromise=null,this.highPriorityInitializerPresent=!1,this.waitingForHighPriority.clear()}isInitialized(){return this.state.status==="INITIALIZED"}getDiagnostics(){return{...this.state,waitingCount:this.waitingForHighPriority.size,waitingComponents:Array.from(this.waitingForHighPriority),hasActivePromise:this.initializationPromise!==null}}},re=we.getInstance();import{useState as pe,useCallback as N,useRef as yi,useMemo as J}from"react";import me from"@nocios/crudify-sdk";var ut=r=>{let e=new Uint8Array(r);return crypto.getRandomValues(e),Array.from(e,t=>t.toString(36).padStart(2,"0")).join("").substring(0,r)},ct=()=>`file_${Date.now()}_${ut(7)}`,hi=r=>{let e=r.lastIndexOf("."),t=e>0?r.substring(e):"",i=Date.now(),n=ut(6);return`${i}_${n}${t}`},Ce=(r,e)=>{if(r.startsWith("http://")||r.startsWith("https://"))try{let t=new URL(r);return t.pathname.startsWith("/")?t.pathname.substring(1):t.pathname}catch{if(e&&r.startsWith(e))return r.substring(e.length)}return e&&r.startsWith(e)?r.substring(e.length):r},Tn=(r={})=>{let{acceptedTypes:e,maxFileSize:t=10*1024*1024,maxFiles:i,minFiles:n=0,visibility:o="private",onUploadComplete:l,onUploadError:s,onFileRemoved:f,onFilesChange:E,mode:b="edit"}=r,[S,m]=pe([]),[I,g]=pe(!1),[k,R]=pe(!1),[x,O]=pe([]),w=yi(new Map),F=N(()=>{g(!0)},[]),z=N(()=>{R(!0),g(!0)},[]),D=N((u,p)=>{m(d=>d.map(h=>h.id===u?{...h,...p}:h))},[]),T=N(u=>{E?.(u)},[E]),Z=N(u=>e&&e.length>0&&!e.includes(u.type)?{valid:!1,error:`File type not allowed: ${u.type}`}:u.size>t?{valid:!1,error:`File exceeds maximum size of ${(t/1048576).toFixed(1)}MB`}:{valid:!0},[e,t]),V=N(async(u,p)=>{try{if(!re.isInitialized())throw new Error("Crudify is not initialized. Please wait for the application to finish loading.");let d=hi(p.name),y=await me.generateSignedUrl({fileName:d,contentType:p.type,visibility:o});if(!y.success||!y.data)throw new Error("Failed to get upload URL");let h=y.data,{uploadUrl:C,s3Key:A,publicUrl:M}=h;if(!C||!A)throw new Error("Incomplete signed URL response");let Y=A.indexOf("/"),Pt=Y>0?A.substring(Y+1):A;D(u.id,{status:"uploading",progress:0}),await new Promise((ye,W)=>{let U=new XMLHttpRequest;U.upload.addEventListener("progress",_=>{if(_.lengthComputable){let Lt=Math.round(_.loaded/_.total*100);D(u.id,{progress:Lt})}}),U.addEventListener("load",()=>{U.status>=200&&U.status<300?ye():W(new Error(`Upload failed with status ${U.status}`))}),U.addEventListener("error",()=>{W(new Error("Network error during upload"))}),U.addEventListener("abort",()=>{W(new Error("Upload cancelled"))}),U.open("PUT",C),U.setRequestHeader("Content-Type",p.type),U.send(p)});let Dt={status:"completed",progress:100,filePath:Pt,visibility:o,publicUrl:o==="public"?M:void 0,file:void 0};m(ye=>{let W=ye.map(_=>_.id===u.id?{..._,...Dt}:_);T(W);let U=W.find(_=>_.id===u.id);return U&&l?.(U),W})}catch(d){let y=d instanceof Error?d.message:"Unknown error";D(u.id,{status:"error",progress:0,errorMessage:y}),m(h=>{let C=h.find(A=>A.id===u.id);return C&&s?.(C,y),h})}},[D,l,s,o]),ne=N(async u=>{let p=Array.from(u),d=[];m(y=>{if(i!==void 0){let A=y.filter(Y=>Y.status!=="pendingDeletion"&&Y.status!=="error").length,M=i-A;if(M<=0)return c.warn(`File limit of ${i} already reached`),y;p.length>M&&(p=p.slice(0,M),c.warn(`Only ${M} files will be added to not exceed limit`))}let h=[];for(let A of p){let M=Z(A),Y={id:ct(),name:A.name,size:A.size,contentType:A.type,status:M.valid?"pending":"error",progress:0,createdAt:Date.now(),file:M.valid?A:void 0,errorMessage:M.error,isExisting:!1};h.push(Y)}d=h;let C=[...y,...h];return T(C),C}),setTimeout(()=>{let y=d.filter(h=>h.status==="pending"&&h.file);for(let h of y)if(h.file){let C=V(h,h.file);w.current.set(h.id,C),C.finally(()=>{w.current.delete(h.id)})}},0)},[i,Z,V,T]),dt=N(async u=>{let p=S.find(y=>y.id===u);if(!p)return{needsConfirmation:!1,isExisting:!1};let d=p.isExisting===!0;return b==="create"||!d?{needsConfirmation:!0,isExisting:d}:(O(y=>[...y,u]),m(y=>{let h=y.map(A=>A.id===u?{...A,status:"pendingDeletion"}:A),C=h.filter(A=>A.status!=="pendingDeletion");return T(C),h}),{needsConfirmation:!1,isExisting:d})},[S,b,T]),ft=N(async u=>{let p=S.find(d=>d.id===u);if(!p)return{success:!1,error:"File not found"};if(!p.filePath)return m(d=>{let y=d.filter(h=>h.id!==u);return T(y),y}),{success:!0};try{if(!re.isInitialized())return{success:!1,error:"Crudify not initialized"};let d=Ce(p.filePath);return(await me.disableFile({filePath:d})).success?(m(h=>{let C=h.filter(A=>A.id!==u);return T(C),C}),f?.(p),{success:!0}):{success:!1,error:"Failed to delete file"}}catch(d){return{success:!1,error:d instanceof Error?d.message:"Unknown error"}}},[S,T,f]),gt=N(u=>{let p=S.find(d=>d.id===u);return!p||!p.isExisting?!1:(O(d=>d.filter(y=>y!==u)),m(d=>{let y=d.map(h=>h.id===u?{...h,status:"completed"}:h);return T(y),y}),!0)},[S,T]),pt=N(()=>{x.length!==0&&(m(u=>{let p=u.map(d=>x.includes(d.id)?{...d,status:"completed"}:d);return T(p),p}),O([]))},[x,T]),mt=N(async()=>{if(x.length===0)return{success:!0,errors:[]};let u=[],p=[];if(!re.isInitialized())return{success:!1,errors:["Crudify is not initialized. Please wait for the application to finish loading."]};for(let d of x){let y=S.find(h=>h.id===d);if(!y?.filePath){p.push(d);continue}try{let h=Ce(y.filePath);(await me.disableFile({filePath:h})).success?(p.push(d),f?.(y)):u.push(`Failed to delete ${y.name}`)}catch(h){u.push(`Error deleting ${y.name}: ${h instanceof Error?h.message:"Unknown error"}`)}}return p.length>0&&(m(d=>d.filter(h=>!p.includes(h.id))),O(d=>d.filter(y=>!p.includes(y)))),{success:u.length===0,errors:u}},[S,x,f]),yt=N(()=>{m([]),T([])},[T]),ht=N(async u=>{let p=S.find(y=>y.id===u);if(!p||p.status!=="error"||!p.file){c.warn("Cannot retry: file not found or no original file");return}D(u,{status:"pending",progress:0,errorMessage:void 0});let d=V(p,p.file);w.current.set(u,d),d.finally(()=>{w.current.delete(u)})},[S,D,V]),Et=N(async()=>{let u=Array.from(w.current.values());return u.length>0&&await Promise.allSettled(u),new Promise(p=>{setTimeout(()=>{m(d=>{let y=d.filter(h=>h.status==="completed"&&h.filePath).map(h=>h.filePath);return p(y),d})},0)})},[]),St=u=>{let p=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"}[p]||"application/octet-stream"},Tt=N((u,p)=>{let d=u.map(y=>{let h=Ce(y.filePath,p),C=h.includes("/public/")||h.startsWith("public/")?"public":"private",A=y.contentType||St(y.name);return{id:ct(),name:y.name,size:y.size||0,contentType:A,status:"completed",progress:100,filePath:h,visibility:C,createdAt:Date.now(),isExisting:!0}});m(d),T(d)},[T]),vt=N(async u=>{let p=S.find(d=>d.id===u);if(!p||!p.filePath)return null;if(p.visibility==="public"&&p.publicUrl)return p.publicUrl;try{if(!re.isInitialized())return null;let d=await me.getFileUrl({filePath:p.filePath,expiresIn:3600}),y=d.data;return d.success&&y?.url?y.url:null}catch{return null}},[S]),bt=J(()=>S.some(u=>u.status==="uploading"||u.status==="pending"),[S]),It=J(()=>S.filter(u=>u.status==="uploading"||u.status==="pending").length,[S]),kt=J(()=>S.filter(u=>u.status==="completed"&&u.filePath).map(u=>u.filePath),[S]),q=J(()=>S.filter(u=>u.status!=="pendingDeletion"),[S]),At=J(()=>q.filter(u=>u.status==="completed"||u.status==="pending"||u.status==="uploading").length,[q]),{isValid:xt,validationError:wt,validationErrorKey:Ct,validationErrorParams:Rt}=J(()=>{let u=q.filter(d=>d.status==="completed").length;if(u<n){let d=n===1?"file.validation.minFilesRequired":"file.validation.minFilesRequiredPlural";return{isValid:!1,validationError:d,validationErrorKey:d,validationErrorParams:{count:n}}}return i!==void 0&&u>i?{isValid:!1,validationError:"file.validation.maxFilesExceeded",validationErrorKey:"file.validation.maxFilesExceeded",validationErrorParams:{count:i}}:q.some(d=>d.status==="error")?{isValid:!1,validationError:"file.validation.filesWithErrors",validationErrorKey:"file.validation.filesWithErrors",validationErrorParams:{}}:{isValid:!0,validationError:null,validationErrorKey:null,validationErrorParams:{}}},[q,n,i]),Nt=x.length>0;return{files:S,activeFiles:q,activeFileCount:At,isUploading:bt,pendingCount:It,addFiles:ne,removeFile:dt,deleteFileImmediately:ft,restoreFile:gt,clearFiles:yt,retryUpload:ht,isValid:xt,validationError:wt,validationErrorKey:Ct,validationErrorParams:Rt,waitForUploads:Et,completedFilePaths:kt,initializeFiles:Tt,isTouched:I,markAsTouched:F,isSubmitted:k,markAsSubmitted:z,getPreviewUrl:vt,pendingDeletions:x,hasPendingDeletions:Nt,commitDeletions:mt,restorePendingDeletions:pt}};export{v as a,Ee as b,B as c,se as d,ve as e,be as f,tt as g,ue as h,rt as i,nt as j,Jr as k,ui as l,Qr as m,sn as n,un as o,we as p,re as q,Tn as r};
|
package/dist/chunk-QM34W6EU.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }var _chunkCR5KJUSTjs = require('./chunk-CR5KJUST.js');var Me="crudify_storage_version",He=2,a=class a{static setStorageType(e){a.storageType=e}static async initialize(){if(!(a.encryptionKey&&a.salt))return a.initPromise||(a.initPromise=(async()=>{let t=null;for(let i=1;i<=3;i++)try{a.checkStorageVersion(),a.salt=a.getOrCreateSalt(),a.fingerprint=await a.generateFingerprint(),a.encryptionKey=await _chunkCR5KJUSTjs.h.call(void 0, a.fingerprint,a.salt);return}catch(n){t=n instanceof Error?n:new Error(String(n)),i<3&&await new Promise(o=>setTimeout(o,100*i))}throw _chunkCR5KJUSTjs.a.error("Crudify: Failed to initialize encryption after retries",_nullishCoalesce(t, () => ({message:"Unknown error"}))),t})()),a.initPromise}static checkStorageVersion(){try{if(parseInt(localStorage.getItem(Me)||"1",10)<He){let t=a.getStorage();t&&t.removeItem(a.TOKEN_KEY),localStorage.removeItem(a.ENCRYPTION_KEY_STORAGE),localStorage.removeItem(a.SALT_KEY),localStorage.setItem(Me,He.toString()),_chunkCR5KJUSTjs.a.info("Crudify: Storage upgraded to v2, tokens cleared for security")}}catch (e2){}}static getOrCreateSalt(){try{let t=localStorage.getItem(a.SALT_KEY);if(t){let i=atob(t),n=new Uint8Array(i.length);for(let o=0;o<i.length;o++)n[o]=i.charCodeAt(o);return n}}catch (e3){}let e=_chunkCR5KJUSTjs.k.call(void 0, );try{let t="";for(let i=0;i<e.length;i++)t+=String.fromCharCode(e[i]);localStorage.setItem(a.SALT_KEY,btoa(t))}catch (e4){_chunkCR5KJUSTjs.a.warn("Crudify: Cannot persist salt, encryption may not persist across sessions")}return e}static async generateFingerprint(){try{let n=localStorage.getItem(a.ENCRYPTION_KEY_STORAGE);if(n&&n.length>=32)return n}catch (e5){}let t=[navigator.userAgent,navigator.language,navigator.platform||"unknown",String(screen.width),String(screen.height),String(screen.colorDepth||24),String(new Date().getTimezoneOffset()),"crudify-session-v3"].join("|"),i=await _chunkCR5KJUSTjs.g.call(void 0, t);try{localStorage.setItem(a.ENCRYPTION_KEY_STORAGE,i)}catch (e6){_chunkCR5KJUSTjs.a.warn("Crudify: Cannot persist encryption key hash, session may not survive page reload")}return i}static isStorageAvailable(e){try{let t=window[e],i="__storage_test__";return t.setItem(i,"test"),t.removeItem(i),!0}catch (e7){return!1}}static getStorage(){return a.storageType==="none"?null:a.isStorageAvailable(a.storageType)?window[a.storageType]:(_chunkCR5KJUSTjs.a.warn(`Crudify: ${a.storageType} not available, tokens won't persist`),null)}static async encryptData(e){if(await a.initialize(),!a.encryptionKey||!a.salt)throw new Error("Encryption not initialized");return _chunkCR5KJUSTjs.i.call(void 0, e,a.encryptionKey,a.salt)}static async decryptData(e){if(await a.initialize(),!a.fingerprint)throw new Error("Encryption not initialized");return _chunkCR5KJUSTjs.l.call(void 0, e)?_chunkCR5KJUSTjs.j.call(void 0, e,a.fingerprint):(_chunkCR5KJUSTjs.a.warn("Crudify: Legacy encrypted data detected, cannot decrypt"),null)}static async saveTokens(e){let t=a.getStorage();if(t)try{let i={accessToken:e.accessToken,refreshToken:e.refreshToken,expiresAt:e.expiresAt,refreshExpiresAt:e.refreshExpiresAt,savedAt:Date.now()},n=await a.encryptData(JSON.stringify(i));t.setItem(a.TOKEN_KEY,n),_chunkCR5KJUSTjs.a.debug("Crudify: Tokens saved successfully")}catch(i){_chunkCR5KJUSTjs.a.error("Crudify: Failed to save tokens",i instanceof Error?i:{message:String(i)})}}static async getTokens(){let e=a.getStorage();if(!e)return null;try{let t=e.getItem(a.TOKEN_KEY);if(!t)return null;let i=await a.decryptData(t);if(!i)return _chunkCR5KJUSTjs.a.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?(_chunkCR5KJUSTjs.a.warn("Crudify: Incomplete token data found, clearing storage"),await a.clearTokens(),null):Date.now()>=n.refreshExpiresAt?(_chunkCR5KJUSTjs.a.info("Crudify: Refresh token expired, clearing storage"),await a.clearTokens(),null):{accessToken:n.accessToken,refreshToken:n.refreshToken,expiresAt:n.expiresAt,refreshExpiresAt:n.refreshExpiresAt}}catch(t){return _chunkCR5KJUSTjs.a.error("Crudify: Failed to retrieve tokens",t instanceof Error?t:{message:String(t)}),await a.clearTokens(),null}}static async clearTokens(){let e=a.getStorage();if(e)try{e.removeItem(a.TOKEN_KEY),_chunkCR5KJUSTjs.a.debug("Crudify: Tokens cleared from storage")}catch(t){_chunkCR5KJUSTjs.a.error("Crudify: Failed to clear tokens",t instanceof Error?t:{message:String(t)})}}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 (e8){}_chunkCR5KJUSTjs.a.info("Crudify: Encryption key rotated successfully")}catch(e){_chunkCR5KJUSTjs.a.error("Crudify: Failed to rotate encryption key",e instanceof Error?e:{message:String(e)})}}static async hasValidTokens(){return await a.getTokens()!==null}static async ensureInitialized(){await a.initialize()}static async getExpirationInfo(){let e=await a.getTokens();if(!e)return null;let t=Date.now();return{accessExpired:t>=e.expiresAt,refreshExpired:t>=e.refreshExpiresAt,accessExpiresIn:Math.max(0,e.expiresAt-t),refreshExpiresIn:Math.max(0,e.refreshExpiresAt-t)}}static async updateAccessToken(e,t){let i=await a.getTokens();if(!i){_chunkCR5KJUSTjs.a.warn("Crudify: Cannot update access token, no existing tokens found");return}await a.saveTokens({...i,accessToken:e,expiresAt:t})}static createSyncEvent(e,t,i){return{type:e,tokens:t,hadPreviousTokens:i}}static markLocalChange(){a.ignoreNextStorageEvent=!0,a.ignoreStorageEventTimeout&&clearTimeout(a.ignoreStorageEventTimeout),a.ignoreStorageEventTimeout=setTimeout(()=>{a.ignoreNextStorageEvent=!1},100)}static markSuccessfulLogin(){a.lastSuccessfulLoginTime=Date.now()}static isWithinLoginGracePeriod(){return a.lastSuccessfulLoginTime===0?!1:Date.now()-a.lastSuccessfulLoginTime<a.LOGIN_GRACE_PERIOD_MS}static subscribeToChanges(e){let t=async i=>{if(i.key!==a.TOKEN_KEY)return;if(a.ignoreNextStorageEvent){a.ignoreNextStorageEvent=!1;return}if(i.newValue===null&&a.isWithinLoginGracePeriod())return;if(i.newValue===null){let l=_optionalChain([a, 'access', _2 => _2.getStorage, 'call', _3 => _3(), 'optionalAccess', _4 => _4.getItem, 'call', _5 => _5(a.TOKEN_KEY)]);if(l!==null&&l!=="")return}let n=i.oldValue!==null&&i.oldValue!=="";if(i.newValue===null){_chunkCR5KJUSTjs.a.debug("Crudify: Tokens removed in another tab"),e(null,a.SYNC_EVENTS.TOKENS_CLEARED,n);return}if(i.newValue){_chunkCR5KJUSTjs.a.debug("Crudify: Tokens updated in another tab");let o=await a.getTokens();e(o,a.SYNC_EVENTS.TOKENS_UPDATED,n)}};return window.addEventListener("storage",t),()=>{window.removeEventListener("storage",t)}}};a.TOKEN_KEY="crudify_tokens",a.ENCRYPTION_KEY_STORAGE="crudify_enc_key",a.SALT_KEY="crudify_enc_salt",a.encryptionKey=null,a.salt=null,a.fingerprint=null,a.storageType="localStorage",a.initPromise=null,a.lastSuccessfulLoginTime=0,a.LOGIN_GRACE_PERIOD_MS=5e3,a.SYNC_EVENTS={TOKENS_CLEARED:"TOKENS_CLEARED",TOKENS_UPDATED:"TOKENS_UPDATED"},a.ignoreNextStorageEvent=!1,a.ignoreStorageEventTimeout=null;var v=a;var K=class K{constructor(){this.broadcastChannel=null;this.CHANNEL_NAME="crudify-session-sync";this.listeners=new Set;this.isInitialized=!1;this.tabId=K.generateTabId(),this.initialize()}static generateTabId(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,9);return`tab_${e}_${t}`}static getInstance(){return K.instance||(K.instance=new K),K.instance}static resetInstance(){K.instance&&(K.instance.destroy(),K.instance=null)}initialize(){if(!this.isInitialized)try{typeof BroadcastChannel<"u"?(this.broadcastChannel=new BroadcastChannel(this.CHANNEL_NAME),this.broadcastChannel.onmessage=e=>{this.handleMessage(e.data)},this.broadcastChannel.onmessageerror=()=>{_chunkCR5KJUSTjs.a.warn("Crudify: CrossTabSync message error")},_chunkCR5KJUSTjs.a.debug("Crudify: CrossTabSync initialized with BroadcastChannel")):_chunkCR5KJUSTjs.a.debug("Crudify: BroadcastChannel not available, using localStorage fallback"),this.isInitialized=!0}catch(e){_chunkCR5KJUSTjs.a.warn("Crudify: Failed to initialize CrossTabSync",{message:e instanceof Error?e.message:String(e)})}}destroy(){this.broadcastChannel&&(this.broadcastChannel.close(),this.broadcastChannel=null),this.listeners.clear(),this.isInitialized=!1}getTabId(){return this.tabId}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}notifyLogin(){this.broadcast({type:"SESSION_STARTED",tabId:this.tabId,timestamp:Date.now()})}notifyLogout(){this.broadcast({type:"SESSION_ENDED",tabId:this.tabId,timestamp:Date.now()})}notifyTokenRefreshed(){this.broadcast({type:"TOKEN_REFRESHED",tabId:this.tabId,timestamp:Date.now()})}ping(){this.broadcast({type:"SESSION_PING",tabId:this.tabId,timestamp:Date.now()})}broadcast(e){this.isInitialized||this.initialize();try{this.broadcastChannel&&(this.broadcastChannel.postMessage(e),_chunkCR5KJUSTjs.a.debug(`Crudify: CrossTab broadcast ${e.type}`))}catch(t){_chunkCR5KJUSTjs.a.warn("Crudify: Failed to broadcast cross-tab message",{message:t instanceof Error?t.message:String(t)})}}handleMessage(e){e.tabId!==this.tabId&&(_chunkCR5KJUSTjs.a.debug(`Crudify: CrossTab received ${e.type} from ${e.tabId}`),e.type==="SESSION_PING"&&this.broadcast({type:"SESSION_PONG",tabId:this.tabId,timestamp:Date.now(),payload:{respondingTo:e.tabId}}),this.listeners.forEach(t=>{try{t(e)}catch(i){_chunkCR5KJUSTjs.a.error("Crudify: CrossTab listener error",{message:i instanceof Error?i.message:String(i)})}}))}};K.instance=null;var Ee=K,B= exports.c =Ee.getInstance();var _crudifysdk = require('@nocios/crudify-sdk'); var _crudifysdk2 = _interopRequireDefault(_crudifysdk);var oe="crudify_auth",Se=r=>{if(r==="dev"||typeof window>"u"||!window.location)return"";if(!r){let e=window.location.hostname;return e?e.endsWith(".nocios.link")||e==="nocios.link"?".nocios.link":e.endsWith(".crudia.com")||e==="crudia.com"?".crudia.com":"":""}return r==="prod"||r==="api"?".crudia.com":".nocios.link"},Ot=(r,e,t)=>{if(typeof document>"u"){_chunkCR5KJUSTjs.a.debug("[CookieSync] No document available (SSR), skipping cookie set");return}if(!r){_chunkCR5KJUSTjs.a.warn("[CookieSync] Attempted to set cookie with empty token");return}try{let i=Se(t),n=Date.now(),o=Math.max(0,Math.floor((e-n)/1e3)),l=[`${oe}=${encodeURIComponent(r)}`,"path=/","SameSite=Lax",`max-age=${o}`];typeof window<"u"&&window.location.protocol==="https:"&&l.push("Secure"),i&&l.push(`domain=${i}`),document.cookie=l.join("; "),_chunkCR5KJUSTjs.a.debug("[CookieSync] Cookie set successfully",{domain:i||"(current host)",maxAgeSeconds:o,tokenLength:r.length})}catch(i){_chunkCR5KJUSTjs.a.error("[CookieSync] Failed to set cookie",i instanceof Error?i:{message:String(i)})}},Ft=r=>{if(typeof document>"u"){_chunkCR5KJUSTjs.a.debug("[CookieSync] No document available (SSR), skipping cookie clear");return}try{let e=Se(r),t=[`${oe}=`,"path=/","max-age=0","expires=Thu, 01 Jan 1970 00:00:00 GMT"];e&&t.push(`domain=${e}`),document.cookie=t.join("; "),document.cookie=`${oe}=; path=/; max-age=0; expires=Thu, 01 Jan 1970 00:00:00 GMT`,_chunkCR5KJUSTjs.a.debug("[CookieSync] Cookie cleared successfully",{domain:e||"(current host)"})}catch(e){_chunkCR5KJUSTjs.a.error("[CookieSync] Failed to clear cookie",e instanceof Error?e:{message:String(e)})}},zt=()=>{if(typeof document>"u")return null;try{let e=document.cookie.split(";").map(i=>i.trim()).find(i=>i.startsWith(`${oe}=`));if(!e)return null;let t=e.split("=")[1];return t?decodeURIComponent(t):null}catch(r){return _chunkCR5KJUSTjs.a.error("[CookieSync] Failed to read cookie",r instanceof Error?r:{message:String(r)}),null}},Q={setCrossSubdomainCookie:Ot,clearCrossSubdomainCookie:Ft,getCrossSubdomainCookie:zt,getCookieDomain:Se};var se=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(e={}){if(!this.initialized){if(this.config={storageType:"localStorage",autoRestore:!0,enableLogging:!1,env:"stg",...e},v.setStorageType(this.config.storageType||"localStorage"),this.config.publicApiKey&&!this.crudifyInitialized&&await this.ensureCrudifyInitialized(),_crudifysdk2.default.setTokenInvalidationCallback(()=>{this.log("Tokens invalidated by crudify-core"),_chunkCR5KJUSTjs.f.emit("SESSION_EXPIRED",{message:"Your session has expired. Please log in again.",source:"crudify-core.clearTokensAndRefreshState"})}),this.config.apiEndpointAdmin&&this.config.apiKeyEndpointAdmin){let t=await v.getTokens();t?await v.saveTokens({...t,apiEndpointAdmin:this.config.apiEndpointAdmin,apiKeyEndpointAdmin:this.config.apiKeyEndpointAdmin}):await v.saveTokens({accessToken:"",refreshToken:"",expiresAt:0,refreshExpiresAt:0,apiEndpointAdmin:this.config.apiEndpointAdmin,apiKeyEndpointAdmin:this.config.apiKeyEndpointAdmin})}this.config.autoRestore&&await this.restoreSession(),this.initialized=!0}}async login(e,t){try{let i=await _crudifysdk2.default.login(e,t);if(!i.success)return{success:!1,error:this.formatError(i.errors),rawResponse:i};let n=await v.getTokens(),o=i.data,l={accessToken:o.token,refreshToken:o.refreshToken,expiresAt:o.expiresAt,refreshExpiresAt:o.refreshExpiresAt,apiEndpointAdmin:_optionalChain([n, 'optionalAccess', _6 => _6.apiEndpointAdmin])||this.config.apiEndpointAdmin,apiKeyEndpointAdmin:_optionalChain([n, 'optionalAccess', _7 => _7.apiKeyEndpointAdmin])||this.config.apiKeyEndpointAdmin};return await v.saveTokens(l),v.markSuccessfulLogin(),this.lastActivityTime=Date.now(),Q.setCrossSubdomainCookie(l.accessToken,l.expiresAt,this.config.env),B.notifyLogin(),_optionalChain([this, 'access', _8 => _8.config, 'access', _9 => _9.onLoginSuccess, 'optionalCall', _10 => _10(l)]),{success:!0,tokens:l,data:o}}catch(i){return _chunkCR5KJUSTjs.a.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..."),_chunkCR5KJUSTjs.f.emit("LOGOUT",{message:"User logged out",source:"SessionManager.logout"}),Q.clearCrossSubdomainCookie(this.config.env),await _crudifysdk2.default.logout(),await v.clearTokens(),B.notifyLogout(),this.log("Logout successful"),_optionalChain([this, 'access', _11 => _11.config, 'access', _12 => _12.onLogout, 'optionalCall', _13 => _13()])}catch(e){this.log("Logout error",{error:e instanceof Error?e.message:String(e)}),await v.clearTokens(),B.notifyLogout()}}async restoreSession(){try{this.log("Attempting to restore session...");let e=await v.getTokens();if(!e)return this.log("No valid tokens found in storage"),!1;if(Date.now()>=e.refreshExpiresAt)return this.log("Refresh token expired, clearing storage"),await v.clearTokens(),!1;if(_crudifysdk2.default.setTokens({accessToken:e.accessToken,refreshToken:e.refreshToken,expiresAt:e.expiresAt,refreshExpiresAt:e.refreshExpiresAt}),_crudifysdk2.default.getTokenData().isValid===!1){if(this.log("Restored access token is invalid or expired"),Date.now()<e.refreshExpiresAt&&(this.log("Access token expired but refresh is valid, attempting refresh..."),await this.refreshTokens())){this.log("Session restored successfully via token refresh");let n=await v.getTokens();return n&&_optionalChain([this, 'access', _14 => _14.config, 'access', _15 => _15.onSessionRestored, 'optionalCall', _16 => _16(n)]),!0}return await v.clearTokens(),await _crudifysdk2.default.logout(),!1}return this.log("Session restored successfully"),this.lastActivityTime=Date.now(),_optionalChain([this, 'access', _17 => _17.config, 'access', _18 => _18.onSessionRestored, 'optionalCall', _19 => _19(e)]),!0}catch(e){return this.log("Session restore error",{error:e instanceof Error?e.message:String(e)}),await v.clearTokens(),await _crudifysdk2.default.logout(),!1}}async isAuthenticated(){return _crudifysdk2.default.isLogin()||await v.hasValidTokens()}async getTokenInfo(){let e=_crudifysdk2.default.getTokenData(),t=await v.getExpirationInfo(),i=await v.getTokens();return{isLoggedIn:await this.isAuthenticated(),crudifyTokens:e,storageInfo:t,hasValidTokens:await v.hasValidTokens(),apiEndpointAdmin:_optionalChain([i, 'optionalAccess', _20 => _20.apiEndpointAdmin]),apiKeyEndpointAdmin:_optionalChain([i, 'optionalAccess', _21 => _21.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 e=await _crudifysdk2.default.refreshAccessToken();if(!e.success)return this.log("Token refresh failed",{errors:e.errors}),await v.clearTokens(),_optionalChain([this, 'access', _22 => _22.config, 'access', _23 => _23.showNotification, 'optionalCall', _24 => _24(this.getSessionExpiredMessage(),"warning")]),_optionalChain([this, 'access', _25 => _25.config, 'access', _26 => _26.onSessionExpired, 'optionalCall', _27 => _27()]),!1;let t=e.data,i={accessToken:t.token,refreshToken:t.refreshToken,expiresAt:t.expiresAt,refreshExpiresAt:t.refreshExpiresAt};return await v.saveTokens(i),this.log("Tokens refreshed and saved successfully"),Q.setCrossSubdomainCookie(i.accessToken,i.expiresAt,this.config.env),this.lastActivityTime=Date.now(),B.notifyTokenRefreshed(),!0}catch(e){return this.log("Token refresh error",{error:e instanceof Error?e.message:String(e)}),await v.clearTokens(),_optionalChain([this, 'access', _28 => _28.config, 'access', _29 => _29.showNotification, 'optionalCall', _30 => _30(this.getSessionExpiredMessage(),"warning")]),_optionalChain([this, 'access', _31 => _31.config, 'access', _32 => _32.onSessionExpired, 'optionalCall', _33 => _33()]),!1}}isRefreshing(){return this.isRefreshingLocally}setupResponseInterceptor(){_crudifysdk2.default.setResponseInterceptor(async e=>{this.updateLastActivity();let t=this.detectAuthorizationError(e);if(t.isAuthError){if(this.log("\u{1F6A8} Authorization error detected:",{errorType:t.errorType,shouldLogout:t.shouldTriggerLogout}),t.isRefreshTokenInvalid||t.isTokenRefreshFailed)return this.log("Refresh token invalid, emitting TOKEN_REFRESH_FAILED event"),_chunkCR5KJUSTjs.f.emit("TOKEN_REFRESH_FAILED",{message:t.userFriendlyMessage,error:t.errorDetails,source:"SessionManager.setupResponseInterceptor"}),e;t.shouldTriggerLogout&&(await v.hasValidTokens()&&!t.isIrrecoverable?(this.log("Access token expired, emitting TOKEN_EXPIRED event"),_chunkCR5KJUSTjs.f.emit("TOKEN_EXPIRED",{message:"Access token expired, refresh needed",error:t.errorDetails,source:"SessionManager.setupResponseInterceptor"})):(this.log("No valid tokens or irrecoverable error, emitting SESSION_EXPIRED event"),_chunkCR5KJUSTjs.f.emit("SESSION_EXPIRED",{message:t.userFriendlyMessage,error:t.errorDetails,source:"SessionManager.setupResponseInterceptor"})))}return e}),this.log("Response interceptor configured (non-blocking mode)")}async ensureCrudifyInitialized(){if(!this.crudifyInitialized)try{this.log("Initializing crudify SDK...");let e=_crudifysdk2.default.getTokenData();if(e&&e.endpoint){this.log("Crudify already initialized by another service"),this.crudifyInitialized=!0;return}let t=this.config.env||"stg";_crudifysdk2.default.config(t);let i=this.config.publicApiKey,n=this.config.enableLogging?"debug":"none",o=await _crudifysdk2.default.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(e){throw _chunkCR5KJUSTjs.a.error("[SessionManager] Failed to initialize crudify",e instanceof Error?e:{message:String(e)}),e}}detectAuthorizationError(e){let t={isAuthError:!1,isRefreshTokenInvalid:!1,isTokenRefreshFailed:!1,isTokenExpired:!1,isUnauthorized:!1,isIrrecoverable:!1,shouldTriggerLogout:!1,errorType:"",errorDetails:null,userFriendlyMessage:""};if(e.errors&&Array.isArray(e.errors)){let i=e.errors.find(n=>n.errorType==="Unauthorized"||_optionalChain([n, 'access', _34 => _34.message, 'optionalAccess', _35 => _35.includes, 'call', _36 => _36("Unauthorized")])||_optionalChain([n, 'access', _37 => _37.message, 'optionalAccess', _38 => _38.includes, 'call', _39 => _39("Not Authorized")])||_optionalChain([n, 'access', _40 => _40.message, 'optionalAccess', _41 => _41.includes, 'call', _42 => _42("NOT_AUTHORIZED")])||_optionalChain([n, 'access', _43 => _43.message, 'optionalAccess', _44 => _44.includes, 'call', _45 => _45("Token")])||_optionalChain([n, 'access', _46 => _46.message, 'optionalAccess', _47 => _47.includes, 'call', _48 => _48("TOKEN")])||_optionalChain([n, 'access', _49 => _49.message, 'optionalAccess', _50 => _50.includes, 'call', _51 => _51("Authentication")])||_optionalChain([n, 'access', _52 => _52.message, 'optionalAccess', _53 => _53.includes, 'call', _54 => _54("UNAUTHENTICATED")])||_optionalChain([n, 'access', _55 => _55.extensions, 'optionalAccess', _56 => _56.code])==="UNAUTHENTICATED"||_optionalChain([n, 'access', _57 => _57.extensions, 'optionalAccess', _58 => _58.code])==="FORBIDDEN");i&&(t.isAuthError=!0,t.errorType="GraphQL Array",t.errorDetails=i,t.shouldTriggerLogout=!0,t.userFriendlyMessage="Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente.",(_optionalChain([i, 'access', _59 => _59.message, 'optionalAccess', _60 => _60.includes, 'call', _61 => _61("TOKEN")])||_optionalChain([i, 'access', _62 => _62.message, 'optionalAccess', _63 => _63.includes, 'call', _64 => _64("Token")]))&&(t.isTokenExpired=!0),_optionalChain([i, 'access', _65 => _65.extensions, 'optionalAccess', _66 => _66.code])==="UNAUTHENTICATED"&&(t.isUnauthorized=!0))}if(!t.isAuthError&&e.errors&&typeof e.errors=="object"&&!Array.isArray(e.errors)){let n=Object.values(e.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"&&(t.isAuthError=!0,t.errorType="GraphQL Object",t.errorDetails=e.errors,t.shouldTriggerLogout=!0,n.includes("TOKEN_REFRESH_FAILED")?(t.isTokenRefreshFailed=!0,t.isRefreshTokenInvalid=!0,t.isIrrecoverable=!0,t.userFriendlyMessage="Tu sesi\xF3n ha caducado. Por favor, inicia sesi\xF3n nuevamente."):n.includes("TOKEN_HAS_EXPIRED")||n.includes("SESSION_EXPIRED")?(t.isTokenExpired=!0,t.userFriendlyMessage="Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente."):n.includes("INVALID_TOKEN")?(t.isTokenExpired=!0,t.isIrrecoverable=!0,t.userFriendlyMessage="Token inv\xE1lido. Por favor, inicia sesi\xF3n nuevamente."):t.userFriendlyMessage="Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente.")}if(!t.isAuthError&&_optionalChain([e, 'access', _67 => _67.data, 'optionalAccess', _68 => _68.response, 'optionalAccess', _69 => _69.status])){let i=e.data.response.status.toUpperCase();(i==="UNAUTHORIZED"||i==="UNAUTHENTICATED")&&(t.isAuthError=!0,t.errorType="Status",t.errorDetails=e.data.response,t.isUnauthorized=!0,t.shouldTriggerLogout=!0,t.isIrrecoverable=!0,t.userFriendlyMessage="Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente.")}if(!t.isAuthError&&_optionalChain([e, 'access', _70 => _70.data, 'optionalAccess', _71 => _71.response, 'optionalAccess', _72 => _72.data]))try{let i=typeof e.data.response.data=="string"?JSON.parse(e.data.response.data):e.data.response.data;(i.error==="REFRESH_TOKEN_INVALID"||i.error==="TOKEN_EXPIRED"||i.error==="INVALID_TOKEN")&&(t.isAuthError=!0,t.errorType="Parsed Data",t.errorDetails=i,t.shouldTriggerLogout=!0,t.isIrrecoverable=!0,i.error==="REFRESH_TOKEN_INVALID"?(t.isRefreshTokenInvalid=!0,t.isTokenRefreshFailed=!0,t.userFriendlyMessage="Tu sesi\xF3n ha caducado. Por favor, inicia sesi\xF3n nuevamente."):(t.isTokenExpired=!0,t.userFriendlyMessage="Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente."))}catch (e9){}if(!t.isAuthError&&e.errorCode){let i=String(e.errorCode).toUpperCase();(i==="UNAUTHORIZED"||i==="UNAUTHENTICATED"||i==="TOKEN_EXPIRED"||i==="INVALID_TOKEN")&&(t.isAuthError=!0,t.errorType="Error Code",t.errorDetails={errorCode:i},t.shouldTriggerLogout=!0,i==="TOKEN_EXPIRED"?t.isTokenExpired=!0:t.isUnauthorized=!0,t.userFriendlyMessage="Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente.")}return t}updateLastActivity(){this.lastActivityTime=Date.now(),this.log("Last activity updated")}getTimeSinceLastActivity(){return this.lastActivityTime===0?0:Date.now()-this.lastActivityTime}checkInactivity(){let e=this.getTimeSinceLastActivity();if(this.lastActivityTime===0)return"none";let t=1800*1e3;return e>t?(this.log(`Inactivity timeout: ${Math.floor(e/6e4)} minutes since last activity`),"logout"):"none"}async clearSession(){Q.clearCrossSubdomainCookie(this.config.env),await v.clearTokens(),await _crudifysdk2.default.logout(),this.lastActivityTime=0,this.log("Session cleared completely")}getSessionExpiredMessage(){return this.config.translateFn?_chunkCR5KJUSTjs.m.call(void 0, "SESSION_EXPIRED",{translateFn:this.config.translateFn,enableDebug:this.config.enableLogging}):"Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente."}log(e,t){this.config.enableLogging&&_chunkCR5KJUSTjs.a.debug(`[SessionManager] ${e}`,t)}formatError(e){return e?typeof e=="string"?e:typeof e=="object"?Object.values(e).flat().map(String).join(", "):"Authentication failed":"Unknown error"}};var _react = require('react'); var _react2 = _interopRequireDefault(_react);var Ge={isAuthenticated:!1,isLoading:!0,isLoggingOut:!1,isInitialized:!1,tokens:null,error:null};function _e(){let[r,e]=_react.useState.call(void 0, Ge),t=_react.useCallback.call(void 0, s=>{e(f=>({...f,isLoading:s}))},[]),i=_react.useCallback.call(void 0, (s,f)=>{e(E=>({...E,isAuthenticated:s,tokens:f,error:s?null:E.error}))},[]),n=_react.useCallback.call(void 0, s=>{e(f=>({...f,isLoggingOut:s}))},[]),o=_react.useCallback.call(void 0, s=>{e(f=>({...f,error:s}))},[]),l=_react.useCallback.call(void 0, s=>{e(f=>({...f,isInitialized:s}))},[]);return{state:r,setState:e,setLoading:t,setAuthenticated:i,setLoggingOut:n,setError:o,setInitialized:l}}var ae={AGGRESSIVE:3e4,MODERATE:6e4,RELAXED:12e4},Te={AGGRESSIVE:300*1e3,MODERATE:1800*1e3},Ve=.5;function $e(r){return r?r.expiresAt-Date.now()<3e5:!1}function Ye(r){return r?Math.max(0,r.expiresAt-Date.now()):0}function We(r){return r?Math.max(0,r.refreshExpiresAt-Date.now()):0}function $(r){return r.crudifyTokens.accessToken?{accessToken:r.crudifyTokens.accessToken,refreshToken:r.crudifyTokens.refreshToken||"",expiresAt:r.crudifyTokens.expiresAt,refreshExpiresAt:r.crudifyTokens.refreshExpiresAt}:null}function Be(r){let{sessionManager:e,stateManager:t}=r,i=_react.useCallback.call(void 0, async(s,f)=>{t.setState(E=>({...E,isLoading:!0,isLoggingOut:!1,error:null}));try{let E=await e.login(s,f);return E.success&&E.tokens?t.setState(b=>({...b,isAuthenticated:!0,tokens:E.tokens,isLoading:!1,isLoggingOut:!1,error:null})):t.setState(b=>({...b,isAuthenticated:!1,tokens:null,isLoading:!1,isLoggingOut:!1,error:null})),E}catch(E){let b=E instanceof Error?E.message:"Login failed";_chunkCR5KJUSTjs.a.error("[useSession] Login error",E instanceof Error?E:{message:b});let S=b.includes("INVALID_CREDENTIALS")||b.includes("Invalid email")||b.includes("Invalid password")||b.includes("credentials");return t.setState(m=>({...m,isAuthenticated:!1,tokens:null,isLoading:!1,isLoggingOut:!1,error:S?null:b})),{success:!1,error:b}}},[e,t]),n=_react.useCallback.call(void 0, async()=>{t.setState(s=>({...s,isLoading:!0,isLoggingOut:!0}));try{await e.logout(),t.setState(s=>({...s,isAuthenticated:!1,tokens:null,isLoading:!1,error:null}))}catch(s){t.setState(f=>({...f,isAuthenticated:!1,tokens:null,isLoading:!1,error:s instanceof Error?s.message:"Logout error"}))}},[e,t]),o=_react.useCallback.call(void 0, async()=>{try{let s=await e.refreshTokens();if(s){let f=await e.getTokenInfo();t.setState(E=>({...E,tokens:$(f),error:null}))}else t.setState(f=>({...f,isAuthenticated:!1,tokens:null,error:"Token refresh failed"}));return s}catch(s){return t.setState(f=>({...f,isAuthenticated:!1,tokens:null,error:s instanceof Error?s.message:"Token refresh failed"})),!1}},[e,t]),l=_react.useCallback.call(void 0, ()=>{t.setError(null)},[t]);return{login:i,logout:n,refreshTokens:o,clearError:l}}function _t(r){return r<Te.AGGRESSIVE?ae.AGGRESSIVE:r<Te.MODERATE?ae.MODERATE:ae.RELAXED}function Xe(r){let{isAuthenticated:e,tokens:t,sessionManager:i,onTokensRefreshed:n,onSessionExpired:o,onSetLoading:l,logout:s}=r,f=_react.useCallback.call(void 0, ()=>{i.updateLastActivity()},[i]);_react.useEffect.call(void 0, ()=>{if(!e||!t)return;let b=_chunkCR5KJUSTjs.q.getInstance().subscribe(f);window.addEventListener("popstate",f);let S,m=!0,I=async()=>{if(!m)return;let k=(await i.getTokenInfo()).crudifyTokens.expiresIn||0,R=_t(k);S=setTimeout(async()=>{if(!m)return;if(i.isRefreshing()){I();return}let x=await i.getTokenInfo(),O=x.crudifyTokens.expiresIn||0,z=((x.crudifyTokens.expiresAt||0)-(Date.now()-O))*Ve;if(O>0&&O<=z)if(l(!0),await i.refreshTokens()){let Z=await i.getTokenInfo();n($(Z)),l(!1)}else n(null),o(),l(!1);i.getTimeSinceLastActivity()>18e5?await s():m&&I()},R)};return I(),()=>{m=!1,clearTimeout(S),window.removeEventListener("popstate",f),b()}},[e,t,i,f,n,o,l,s])}function Ze(r){let{sessionManager:e,onTokensUpdated:t,onSessionExpired:i,onSetLoading:n,onSetError:o}=r;_react.useEffect.call(void 0, ()=>{let l=_chunkCR5KJUSTjs.f.subscribe(async s=>{if(s.type==="TOKEN_EXPIRED"){if(e.isRefreshing())return;n(!0);try{if(await e.refreshTokens()){let E=await e.getTokenInfo();t($(E)),n(!1)}else _chunkCR5KJUSTjs.f.emit("SESSION_EXPIRED",{message:"Failed to refresh token after detecting expiration",source:"useSession.TOKEN_EXPIRED handler"})}catch(f){_chunkCR5KJUSTjs.f.emit("SESSION_EXPIRED",{message:f instanceof Error?f.message:"Unknown error during refresh",source:"useSession.TOKEN_EXPIRED handler (error)"})}}(s.type==="SESSION_EXPIRED"||s.type==="TOKEN_REFRESH_FAILED")&&(t(null),n(!1),o(_optionalChain([s, 'access', _73 => _73.details, 'optionalAccess', _74 => _74.message, 'optionalAccess', _75 => _75.toString, 'call', _76 => _76()])||"Session expired"),i())});return()=>l()},[e,t,i,n,o])}function je(r){let{isAuthenticated:e,onTokensUpdated:t,onSessionExpired:i}=r;_react.useEffect.call(void 0, ()=>{let n=async l=>{switch(l.type){case"SESSION_STARTED":case"TOKEN_REFRESHED":try{await v.ensureInitialized();let s=await v.getTokens();s&&(_chunkCR5KJUSTjs.a.debug(`[useCrossTabSync] Syncing ${l.type} from tab ${l.tabId}`),t(s))}catch(s){_chunkCR5KJUSTjs.a.warn("[useCrossTabSync] Failed to read tokens after cross-tab event",{error:s instanceof Error?s.message:String(s)})}break;case"SESSION_ENDED":try{await v.hasValidTokens()||(_chunkCR5KJUSTjs.a.debug(`[useCrossTabSync] Syncing SESSION_ENDED from tab ${l.tabId}`),t(null),e&&i())}catch(s){_chunkCR5KJUSTjs.a.warn("[useCrossTabSync] Failed to verify tokens after logout event",{error:s instanceof Error?s.message:String(s)})}break;case"SESSION_PING":case"SESSION_PONG":break}},o=B.subscribe(n);return()=>o()},[e,t,i]),_react.useEffect.call(void 0, ()=>{let n=v.subscribeToChanges(async(o,l,s)=>{if(l===v.SYNC_EVENTS.TOKENS_CLEARED){if(await v.hasValidTokens())return;s&&e?(t(null),i()):s&&t(null)}else l===v.SYNC_EVENTS.TOKENS_UPDATED&&o&&t(o)});return()=>n()},[e,t,i])}async function Je(r){let{sessionManager:e,options:t,stateActions:i}=r;try{i.setState(s=>({...s,isLoading:!0,error:null}));let n={autoRestore:_nullishCoalesce(t.autoRestore, () => (!0)),enableLogging:_nullishCoalesce(t.enableLogging, () => (!1)),showNotification:t.showNotification,translateFn:t.translateFn,apiEndpointAdmin:t.apiEndpointAdmin,apiKeyEndpointAdmin:t.apiKeyEndpointAdmin,publicApiKey:t.publicApiKey,env:t.env||"stg",onSessionExpired:()=>{i.setState(s=>({...s,isAuthenticated:!1,tokens:null,error:"Session expired"})),_optionalChain([t, 'access', _77 => _77.onSessionExpired, 'optionalCall', _78 => _78()])},onSessionRestored:s=>{i.setState(f=>({...f,isAuthenticated:!0,tokens:s,error:null})),_optionalChain([t, 'access', _79 => _79.onSessionRestored, 'optionalCall', _80 => _80(s)])},onLoginSuccess:s=>{i.setState(f=>({...f,isAuthenticated:!0,tokens:s,error:null}))},onLogout:()=>{i.setState(s=>({...s,isAuthenticated:!1,tokens:null,error:null}))}};await e.initialize(n),e.setupResponseInterceptor();let o=await e.isAuthenticated(),l=await e.getTokenInfo();i.setState(s=>({...s,isAuthenticated:o,isInitialized:!0,isLoading:!1,isLoggingOut:!1,tokens:$(l)}))}catch(n){let o=n instanceof Error?n.message:"Initialization failed";_chunkCR5KJUSTjs.a.error("[useSession] Initialize failed",n instanceof Error?n:{message:o}),i.setState(l=>({...l,isLoading:!1,isInitialized:!0,isLoggingOut:!1,error:o}))}}function ve(r={}){let e=se.getInstance(),t=_e(),{state:i}=t,{login:n,logout:o,refreshTokens:l,clearError:s}=Be({sessionManager:e,stateManager:t}),f=_react.useCallback.call(void 0, g=>{t.setAuthenticated(!!g,g)},[t]),E=_react.useCallback.call(void 0, ()=>{t.setAuthenticated(!1,null),_optionalChain([r, 'access', _81 => _81.onSessionExpired, 'optionalCall', _82 => _82()])},[t,r.onSessionExpired]),b=_react.useCallback.call(void 0, g=>{t.setLoading(g)},[t]),S=_react.useCallback.call(void 0, g=>{t.setError(g)},[t]);_react.useEffect.call(void 0, ()=>{Je({sessionManager:e,options:r,stateActions:t})},[]),Xe({isAuthenticated:i.isAuthenticated,tokens:i.tokens,sessionManager:e,onTokensRefreshed:f,onSessionExpired:E,onSetLoading:b,logout:o}),Ze({sessionManager:e,onTokensUpdated:f,onSessionExpired:E,onSetLoading:b,onSetError:S}),je({isAuthenticated:i.isAuthenticated,onTokensUpdated:f,onSessionExpired:E});let m=_react.useCallback.call(void 0, ()=>{e.updateLastActivity()},[e]),I=_react.useCallback.call(void 0, async()=>e.getTokenInfo(),[e]);return{...i,login:n,logout:o,refreshTokens:l,clearError:s,getTokenInfo:I,updateActivity:m,isExpiringSoon:$e(i.tokens),expiresIn:Ye(i.tokens),refreshExpiresIn:We(i.tokens)}}var _material = require('@mui/material');var _uuid = require('uuid');var _dompurify = require('dompurify'); var _dompurify2 = _interopRequireDefault(_dompurify);var _jsxruntime = require('react/jsx-runtime');var et=_react.createContext.call(void 0, null),ei=r=>_dompurify2.default.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}),be= exports.f =({children:r,maxNotifications:e=5,defaultAutoHideDuration:t=6e3,position:i={vertical:"top",horizontal:"right"},enabled:n=!1,allowHtml:o=!1})=>{let[l,s]=_react.useState.call(void 0, []),f=_react.useCallback.call(void 0, (m,I="info",g)=>{if(!n)return"";if(!m||typeof m!="string")return _chunkCR5KJUSTjs.a.warn("GlobalNotificationProvider: Invalid message provided"),"";m.length>1e3&&(_chunkCR5KJUSTjs.a.warn("GlobalNotificationProvider: Message too long, truncating"),m=m.substring(0,1e3)+"...");let k=_uuid.v4.call(void 0, ),R={id:k,message:m,severity:I,autoHideDuration:_nullishCoalesce(_optionalChain([g, 'optionalAccess', _83 => _83.autoHideDuration]), () => (t)),persistent:_nullishCoalesce(_optionalChain([g, 'optionalAccess', _84 => _84.persistent]), () => (!1)),allowHtml:_nullishCoalesce(_optionalChain([g, 'optionalAccess', _85 => _85.allowHtml]), () => (o))};return s(x=>[...x.length>=e?x.slice(-(e-1)):x,R]),k},[e,t,n,o]),E=_react.useCallback.call(void 0, m=>{s(I=>I.filter(g=>g.id!==m))},[]),b=_react.useCallback.call(void 0, ()=>{s([])},[]),S={showNotification:f,hideNotification:E,clearAllNotifications:b};return _jsxruntime.jsxs.call(void 0, et.Provider,{value:S,children:[r,n&&_jsxruntime.jsx.call(void 0, _material.Portal,{children:_jsxruntime.jsx.call(void 0, _material.Box,{sx:{position:"fixed",zIndex:9999,[i.vertical]:(i.vertical==="top",24),[i.horizontal]:i.horizontal==="right"||i.horizontal==="left"?24:"50%",...i.horizontal==="center"&&{transform:"translateX(-50%)"},display:"flex",flexDirection:i.vertical==="top"?"column":"column-reverse",gap:1,maxWidth:"400px",width:"auto"},children:l.map(m=>_jsxruntime.jsx.call(void 0, ti,{notification:m,onClose:()=>E(m.id)},m.id))})})]})},ti=({notification:r,onClose:e})=>{let[t,i]=_react.useState.call(void 0, !0),n=_react.useCallback.call(void 0, (o,l)=>{l!=="clickaway"&&(i(!1),setTimeout(e,300))},[e]);return _react.useEffect.call(void 0, ()=>{if(!r.persistent&&r.autoHideDuration){let o=setTimeout(()=>{n()},r.autoHideDuration);return()=>clearTimeout(o)}},[r.autoHideDuration,r.persistent,n]),_jsxruntime.jsx.call(void 0, _material.Snackbar,{open:t,onClose:n,sx:{position:"relative","& .MuiSnackbarContent-root":{minWidth:"auto"}},TransitionProps:{enter:!0,exit:!0},children:_jsxruntime.jsx.call(void 0, _material.Alert,{variant:"filled",severity:r.severity,onClose:n,sx:{width:"100%",minWidth:"280px",maxWidth:"400px",wordBreak:"break-word"},children:r.allowHtml?_jsxruntime.jsx.call(void 0, "span",{dangerouslySetInnerHTML:{__html:ei(r.message)}}):_jsxruntime.jsx.call(void 0, "span",{children:r.message})})})},tt= exports.g =()=>{let r=_react.useContext.call(void 0, et);if(!r)throw new Error("useGlobalNotification debe ser usado dentro de un GlobalNotificationProvider");return r};var Ie=class r{constructor(){this.listeners=[];this.credentials=null;this.isReady=!1}static getInstance(){return r.instance||(r.instance=new r),r.instance}notifyCredentialsReady(e){this.credentials=e,this.isReady=!0,this.listeners.forEach(t=>{try{t(e)}catch(i){_chunkCR5KJUSTjs.a.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(e=>{this.listeners.push(e)})}reset(){this.credentials=null,this.isReady=!1,this.listeners=[]}areCredentialsReady(){return this.isReady&&this.credentials!==null}},ue= exports.h =Ie.getInstance();var it=_react.createContext.call(void 0, void 0),rt= exports.i =({config:r,children:e})=>{let[t,i]=_react.useState.call(void 0, !0),[n,o]=_react.useState.call(void 0, null),[l,s]=_react.useState.call(void 0, !1),[f,E]=_react.useState.call(void 0, ""),[b,S]=_react.useState.call(void 0, );_react.useEffect.call(void 0, ()=>{if(!r.publicApiKey){o("No publicApiKey provided"),i(!1),s(!1);return}let I=`${r.publicApiKey}-${r.env}`;if(I===f&&l){i(!1);return}(async()=>{i(!0),o(null),s(!1);try{_crudifysdk2.default.config(r.env||"prod");let k=await _crudifysdk2.default.init(r.publicApiKey,"none");if(S(k),typeof _crudifysdk2.default.transaction=="function"&&typeof _crudifysdk2.default.login=="function")s(!0),E(I),k.apiEndpointAdmin&&k.apiKeyEndpointAdmin&&ue.notifyCredentialsReady({apiUrl:k.apiEndpointAdmin,apiKey:k.apiKeyEndpointAdmin});else throw new Error("Crudify methods not properly initialized")}catch(k){let R=k instanceof Error?k.message:"Failed to initialize Crudify";_chunkCR5KJUSTjs.a.error("[CrudifyProvider] Initialization error",k instanceof Error?k:{message:String(k)}),o(R),s(!1)}finally{i(!1)}})()},[r.publicApiKey,r.env,f,l]);let m={crudify:l?_crudifysdk2.default:null,isLoading:t,error:n,isInitialized:l,adminCredentials:b};return _jsxruntime.jsx.call(void 0, it.Provider,{value:m,children:e})},nt= exports.j =()=>{let r=_react.useContext.call(void 0, it);if(r===void 0)throw new Error("useCrudify must be used within a CrudifyProvider");return r};var st=_react.createContext.call(void 0, void 0);function ot({children:r,options:e={},config:t,showNotifications:i=!1,notificationOptions:n={}}){let o;try{let{showNotification:g}=tt();o=g}catch (e10){}let l={};try{let g=nt();g.isInitialized&&g.adminCredentials&&(l=g.adminCredentials)}catch (e11){}let s=_react.useMemo.call(void 0, ()=>{let g=_chunkCR5KJUSTjs.d.call(void 0, {publicApiKey:_optionalChain([t, 'optionalAccess', _86 => _86.publicApiKey]),env:_optionalChain([t, 'optionalAccess', _87 => _87.env]),enableDebug:_optionalChain([e, 'optionalAccess', _88 => _88.enableLogging])});return{publicApiKey:g.publicApiKey,env:g.env||"prod"}},[t,_optionalChain([e, 'optionalAccess', _89 => _89.enableLogging])]),f=_react2.default.useMemo(()=>({...e,showNotification:o,apiEndpointAdmin:l.apiEndpointAdmin,apiKeyEndpointAdmin:l.apiKeyEndpointAdmin,publicApiKey:s.publicApiKey,env:s.env,onSessionExpired:()=>{_optionalChain([e, 'access', _90 => _90.onSessionExpired, 'optionalCall', _91 => _91()])}}),[e,o,l.apiEndpointAdmin,l.apiKeyEndpointAdmin,s]),E=ve(f),b=_react.useMemo.call(void 0, ()=>{let g=_chunkCR5KJUSTjs.d.call(void 0, {publicApiKey:_optionalChain([t, 'optionalAccess', _92 => _92.publicApiKey]),env:_optionalChain([t, 'optionalAccess', _93 => _93.env]),appName:_optionalChain([t, 'optionalAccess', _94 => _94.appName]),logo:_optionalChain([t, 'optionalAccess', _95 => _95.logo]),loginActions:_optionalChain([t, 'optionalAccess', _96 => _96.loginActions]),enableDebug:_optionalChain([e, 'optionalAccess', _97 => _97.enableLogging])});return{publicApiKey:g.publicApiKey,env:g.env,appName:g.appName,loginActions:g.loginActions,logo:g.logo}},[t,_optionalChain([e, 'optionalAccess', _98 => _98.enableLogging])]),S=_react.useMemo.call(void 0, ()=>{if(!_optionalChain([E, 'access', _99 => _99.tokens, 'optionalAccess', _100 => _100.accessToken])||!E.isAuthenticated)return null;try{let g=_chunkCR5KJUSTjs.r.call(void 0, E.tokens.accessToken);if(g&&g.sub&&g.email&&g.subscriber){let k={_id:g.sub,email:g.email,subscriberKey:g.subscriber};return Object.keys(g).forEach(R=>{["sub","email","subscriber"].includes(R)||(k[R]=g[R])}),k}}catch(g){_chunkCR5KJUSTjs.a.error("Error decoding JWT token for sessionData",g instanceof Error?g:{message:String(g)})}return null},[_optionalChain([E, 'access', _101 => _101.tokens, 'optionalAccess', _102 => _102.accessToken]),E.isAuthenticated]),m={...E,sessionData:S,config:b},I={enabled:i,maxNotifications:n.maxNotifications||5,defaultAutoHideDuration:n.defaultAutoHideDuration||6e3,position:n.position||{vertical:"top",horizontal:"right"}};return _jsxruntime.jsx.call(void 0, st.Provider,{value:m,children:r})}function Jr(r){let e={enabled:r.showNotifications,maxNotifications:_optionalChain([r, 'access', _103 => _103.notificationOptions, 'optionalAccess', _104 => _104.maxNotifications])||5,defaultAutoHideDuration:_optionalChain([r, 'access', _105 => _105.notificationOptions, 'optionalAccess', _106 => _106.defaultAutoHideDuration])||6e3,position:_optionalChain([r, 'access', _107 => _107.notificationOptions, 'optionalAccess', _108 => _108.position])||{vertical:"top",horizontal:"right"},allowHtml:_optionalChain([r, 'access', _109 => _109.notificationOptions, 'optionalAccess', _110 => _110.allowHtml])||!1};return _optionalChain([r, 'access', _111 => _111.config, 'optionalAccess', _112 => _112.publicApiKey])?_jsxruntime.jsx.call(void 0, rt,{config:{publicApiKey:r.config.publicApiKey,env:r.config.env||"prod",appName:r.config.appName,loginActions:r.config.loginActions,logo:r.config.logo},children:_jsxruntime.jsx.call(void 0, be,{...e,children:_jsxruntime.jsx.call(void 0, ot,{...r})})}):_jsxruntime.jsx.call(void 0, be,{...e,children:_jsxruntime.jsx.call(void 0, ot,{...r})})}function ui(){let r=_react.useContext.call(void 0, st);if(r===void 0)throw new Error("useSessionContext must be used within a SessionProvider");return r}function Qr(){let r=ui();return r.isInitialized?_jsxruntime.jsxs.call(void 0, "div",{style:{padding:"10px",margin:"10px",border:"1px solid #ccc",borderRadius:"4px",fontSize:"12px",fontFamily:"monospace"},children:[_jsxruntime.jsx.call(void 0, "h4",{children:"Session Debug Info"}),_jsxruntime.jsxs.call(void 0, "div",{children:[_jsxruntime.jsx.call(void 0, "strong",{children:"Authenticated:"})," ",r.isAuthenticated?"Yes":"No"]}),_jsxruntime.jsxs.call(void 0, "div",{children:[_jsxruntime.jsx.call(void 0, "strong",{children:"Loading:"})," ",r.isLoading?"Yes":"No"]}),_jsxruntime.jsxs.call(void 0, "div",{children:[_jsxruntime.jsx.call(void 0, "strong",{children:"Error:"})," ",r.error||"None"]}),r.tokens&&_jsxruntime.jsxs.call(void 0, _jsxruntime.Fragment,{children:[_jsxruntime.jsxs.call(void 0, "div",{children:[_jsxruntime.jsx.call(void 0, "strong",{children:"Access Token:"})," ",r.tokens.accessToken.substring(0,20),"..."]}),_jsxruntime.jsxs.call(void 0, "div",{children:[_jsxruntime.jsx.call(void 0, "strong",{children:"Refresh Token:"})," ",r.tokens.refreshToken.substring(0,20),"..."]}),_jsxruntime.jsxs.call(void 0, "div",{children:[_jsxruntime.jsx.call(void 0, "strong",{children:"Access Expires In:"})," ",Math.round(r.expiresIn/1e3/60)," minutes"]}),_jsxruntime.jsxs.call(void 0, "div",{children:[_jsxruntime.jsx.call(void 0, "strong",{children:"Refresh Expires In:"})," ",Math.round(r.refreshExpiresIn/1e3/60/60)," hours"]}),_jsxruntime.jsxs.call(void 0, "div",{children:[_jsxruntime.jsx.call(void 0, "strong",{children:"Expiring Soon:"})," ",r.isExpiringSoon?"Yes":"No"]})]})]}):_jsxruntime.jsx.call(void 0, "div",{children:"Session not initialized"})}var sn=(r={})=>{let{autoFetch:e=!0,retryOnError:t=!1,maxRetries:i=3}=r,[n,o]=_react.useState.call(void 0, null),[l,s]=_react.useState.call(void 0, !1),[f,E]=_react.useState.call(void 0, null),[b,S]=_react.useState.call(void 0, {}),m=_react.useRef.call(void 0, null),I=_react.useRef.call(void 0, !0),g=_react.useRef.call(void 0, 0),k=_react.useRef.call(void 0, 0),R=_react.useCallback.call(void 0, ()=>{o(null),E(null),s(!1),S({})},[]),x=_react.useCallback.call(void 0, async()=>{let O=_chunkCR5KJUSTjs.s.call(void 0, );if(!O){I.current&&(E("No user email available"),s(!1));return}m.current&&m.current.abort();let w=new AbortController;m.current=w;let F=++g.current;try{I.current&&(s(!0),E(null));let z=await _crudifysdk2.default.readItems("users",{filter:{email:O},pagination:{limit:1}});if(F===g.current&&I.current&&!w.signal.aborted){let D=z.data;if(z.success&&D&&D.length>0){let T=D[0];o(T);let Z={fullProfile:T,totalFields:Object.keys(T).length,displayData:{id:T.id,email:T.email,username:T.username,firstName:T.firstName,lastName:T.lastName,fullName:T.fullName||`${T.firstName||""} ${T.lastName||""}`.trim(),role:T.role,permissions:T.permissions||[],isActive:T.isActive,lastLogin:T.lastLogin,createdAt:T.createdAt,updatedAt:T.updatedAt,...Object.keys(T).filter(V=>!["id","email","username","firstName","lastName","fullName","role","permissions","isActive","lastLogin","createdAt","updatedAt"].includes(V)).reduce((V,ne)=>({...V,[ne]:T[ne]}),{})}};S(Z),E(null),k.current=0}else E("User profile not found"),o(null),S({})}}catch(z){if(F===g.current&&I.current){let D=z;if(D.name==="AbortError")return;t&&k.current<i&&(_optionalChain([D, 'access', _113 => _113.message, 'optionalAccess', _114 => _114.includes, 'call', _115 => _115("Network Error")])||_optionalChain([D, 'access', _116 => _116.message, 'optionalAccess', _117 => _117.includes, 'call', _118 => _118("Failed to fetch")]))?(k.current++,setTimeout(()=>{I.current&&x()},1e3*k.current)):(E("Failed to load user profile"),o(null),S({}))}}finally{F===g.current&&I.current&&s(!1),m.current===w&&(m.current=null)}},[t,i]);return _react.useEffect.call(void 0, ()=>{e&&x()},[e,x]),_react.useEffect.call(void 0, ()=>(I.current=!0,()=>{I.current=!1,m.current&&(m.current.abort(),m.current=null)}),[]),{userProfile:n,loading:l,error:f,extendedData:b,refreshProfile:x,clearProfile:R}};var un=(r,e={})=>{let{autoFetch:t=!0,onSuccess:i,onError:n}=e,{prefix:o,padding:l=0,separator:s=""}=r,[f,E]=_react.useState.call(void 0, ""),[b,S]=_react.useState.call(void 0, !1),[m,I]=_react.useState.call(void 0, null),g=_react.useRef.call(void 0, !1),k=_react.useCallback.call(void 0, w=>{let F=String(w).padStart(l,"0");return`${o}${s}${F}`},[o,l,s]),R=_react.useCallback.call(void 0, async()=>{S(!0),I(null);try{let w=await _crudifysdk2.default.getNextSequence(o),F=w.data;if(w.success&&_optionalChain([F, 'optionalAccess', _119 => _119.value])){let z=k(F.value);E(z),_optionalChain([i, 'optionalCall', _120 => _120(z)])}else{let z=_optionalChain([w, 'access', _121 => _121.errors, 'optionalAccess', _122 => _122._error, 'optionalAccess', _123 => _123[0]])||"Failed to generate code";I(z),_optionalChain([n, 'optionalCall', _124 => _124(z)])}}catch(w){let F=w instanceof Error?w.message:"Unknown error";I(F),_optionalChain([n, 'optionalCall', _125 => _125(F)])}finally{S(!1)}},[o,k,i,n]),x=_react.useCallback.call(void 0, async()=>{await R()},[R]),O=_react.useCallback.call(void 0, ()=>{I(null)},[]);return _react.useEffect.call(void 0, ()=>{t&&!f&&!g.current&&(g.current=!0,R())},[t,f,R]),{value:f,loading:b,error:m,regenerate:x,clearError:O}};var we=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(e){let{priority:t,publicApiKey:i,env:n,enableLogging:o,requestedBy:l}=e;if(this.state.status==="INITIALIZED"){this.state.publicApiKey!==i&&_chunkCR5KJUSTjs.a.warn(`[CrudifyInitialization] ${l} attempted to initialize with different key. Already initialized with key: ${_optionalChain([this, 'access', _126 => _126.state, 'access', _127 => _127.publicApiKey, 'optionalAccess', _128 => _128.slice, 'call', _129 => _129(0,10)])}... by ${this.state.initializedBy}`);return}if(this.initializationPromise)return o&&_chunkCR5KJUSTjs.a.debug(`[CrudifyInitialization] ${l} waiting for ongoing initialization...`),this.initializationPromise;if(t==="LOW"&&this.highPriorityInitializerPresent&&this.state.status==="UNINITIALIZED"){if(o&&_chunkCR5KJUSTjs.a.debug(`[CrudifyInitialization] ${l} (LOW priority) waiting for HIGH priority initializer...`),this.waitingForHighPriority.add(l),await this.waitForHighPriorityOrTimeout(o),this.waitingForHighPriority.delete(l),this.getState().status==="INITIALIZED"){o&&_chunkCR5KJUSTjs.a.debug(`[CrudifyInitialization] ${l} found initialization completed by HIGH priority`);return}o&&_chunkCR5KJUSTjs.a.warn(`[CrudifyInitialization] ${l} timeout waiting for HIGH priority, initializing with LOW priority`)}t==="HIGH"&&this.state.status==="INITIALIZING"&&this.state.priority==="LOW"&&(_chunkCR5KJUSTjs.a.warn(`[CrudifyInitialization] HIGH priority request from ${l} interrupting LOW priority initialization by ${this.state.initializedBy}`),this.state.status="UNINITIALIZED",this.initializationPromise=null),o&&_chunkCR5KJUSTjs.a.debug(`[CrudifyInitialization] ${l} starting initialization (${t} priority)...`),this.state.status="INITIALIZING",this.state.priority=t,this.state.initializedBy=l,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&&_chunkCR5KJUSTjs.a.info(`[CrudifyInitialization] Successfully initialized by ${l} (${t} priority)`)}catch(s){throw this.state.status="ERROR",this.state.error=s instanceof Error?s:new Error(String(s)),this.initializationPromise=null,_chunkCR5KJUSTjs.a.error(`[CrudifyInitialization] Initialization failed for ${l}`,s instanceof Error?s:{message:String(s)}),s}}async waitForHighPriorityOrTimeout(e){return new Promise(t=>{let n=0,o=setInterval(()=>{if(n+=10,this.state.status==="INITIALIZED"&&this.state.priority==="HIGH"){clearInterval(o),t();return}if(this.state.status==="INITIALIZING"&&this.state.priority==="HIGH"){n=0;return}n>=this.HIGH_PRIORITY_WAIT_TIMEOUT&&(clearInterval(o),e&&_chunkCR5KJUSTjs.a.debug(`[CrudifyInitialization] Timeout waiting for HIGH priority (${this.HIGH_PRIORITY_WAIT_TIMEOUT}ms)`),t())},10)})}async performInitialization(e,t,i){let n=_crudifysdk2.default.getTokenData();if(n&&n.endpoint){i&&_chunkCR5KJUSTjs.a.debug("[CrudifyInitialization] SDK already initialized externally");return}_crudifysdk2.default.config(t);let o=i?"debug":"none",l=await _crudifysdk2.default.init(e,o);if(l.success===!1)throw new Error(`Crudify initialization failed: ${JSON.stringify(l.errors||"Unknown error")}`);l.apiEndpointAdmin&&l.apiKeyEndpointAdmin&&ue.notifyCredentialsReady({apiUrl:l.apiEndpointAdmin,apiKey:l.apiKeyEndpointAdmin})}reset(){this.state={status:"UNINITIALIZED",priority:null,publicApiKey:null,env:null,error:null,initializedBy:null},this.initializationPromise=null,this.highPriorityInitializerPresent=!1,this.waitingForHighPriority.clear()}isInitialized(){return this.state.status==="INITIALIZED"}getDiagnostics(){return{...this.state,waitingCount:this.waitingForHighPriority.size,waitingComponents:Array.from(this.waitingForHighPriority),hasActivePromise:this.initializationPromise!==null}}},re= exports.q =we.getInstance();var ut=r=>{let e=new Uint8Array(r);return crypto.getRandomValues(e),Array.from(e,t=>t.toString(36).padStart(2,"0")).join("").substring(0,r)},ct=()=>`file_${Date.now()}_${ut(7)}`,hi=r=>{let e=r.lastIndexOf("."),t=e>0?r.substring(e):"",i=Date.now(),n=ut(6);return`${i}_${n}${t}`},Ce=(r,e)=>{if(r.startsWith("http://")||r.startsWith("https://"))try{let t=new URL(r);return t.pathname.startsWith("/")?t.pathname.substring(1):t.pathname}catch (e12){if(e&&r.startsWith(e))return r.substring(e.length)}return e&&r.startsWith(e)?r.substring(e.length):r},Tn= exports.r =(r={})=>{let{acceptedTypes:e,maxFileSize:t=10*1024*1024,maxFiles:i,minFiles:n=0,visibility:o="private",onUploadComplete:l,onUploadError:s,onFileRemoved:f,onFilesChange:E,mode:b="edit"}=r,[S,m]=_react.useState.call(void 0, []),[I,g]=_react.useState.call(void 0, !1),[k,R]=_react.useState.call(void 0, !1),[x,O]=_react.useState.call(void 0, []),w=_react.useRef.call(void 0, new Map),F=_react.useCallback.call(void 0, ()=>{g(!0)},[]),z=_react.useCallback.call(void 0, ()=>{R(!0),g(!0)},[]),D=_react.useCallback.call(void 0, (u,p)=>{m(d=>d.map(h=>h.id===u?{...h,...p}:h))},[]),T=_react.useCallback.call(void 0, u=>{_optionalChain([E, 'optionalCall', _130 => _130(u)])},[E]),Z=_react.useCallback.call(void 0, u=>e&&e.length>0&&!e.includes(u.type)?{valid:!1,error:`File type not allowed: ${u.type}`}:u.size>t?{valid:!1,error:`File exceeds maximum size of ${(t/1048576).toFixed(1)}MB`}:{valid:!0},[e,t]),V=_react.useCallback.call(void 0, async(u,p)=>{try{if(!re.isInitialized())throw new Error("Crudify is not initialized. Please wait for the application to finish loading.");let d=hi(p.name),y=await _crudifysdk2.default.generateSignedUrl({fileName:d,contentType:p.type,visibility:o});if(!y.success||!y.data)throw new Error("Failed to get upload URL");let h=y.data,{uploadUrl:C,s3Key:A,publicUrl:M}=h;if(!C||!A)throw new Error("Incomplete signed URL response");let Y=A.indexOf("/"),Pt=Y>0?A.substring(Y+1):A;D(u.id,{status:"uploading",progress:0}),await new Promise((ye,W)=>{let U=new XMLHttpRequest;U.upload.addEventListener("progress",_=>{if(_.lengthComputable){let Lt=Math.round(_.loaded/_.total*100);D(u.id,{progress:Lt})}}),U.addEventListener("load",()=>{U.status>=200&&U.status<300?ye():W(new Error(`Upload failed with status ${U.status}`))}),U.addEventListener("error",()=>{W(new Error("Network error during upload"))}),U.addEventListener("abort",()=>{W(new Error("Upload cancelled"))}),U.open("PUT",C),U.setRequestHeader("Content-Type",p.type),U.send(p)});let Dt={status:"completed",progress:100,filePath:Pt,visibility:o,publicUrl:o==="public"?M:void 0,file:void 0};m(ye=>{let W=ye.map(_=>_.id===u.id?{..._,...Dt}:_);T(W);let U=W.find(_=>_.id===u.id);return U&&_optionalChain([l, 'optionalCall', _131 => _131(U)]),W})}catch(d){let y=d instanceof Error?d.message:"Unknown error";D(u.id,{status:"error",progress:0,errorMessage:y}),m(h=>{let C=h.find(A=>A.id===u.id);return C&&_optionalChain([s, 'optionalCall', _132 => _132(C,y)]),h})}},[D,l,s,o]),ne=_react.useCallback.call(void 0, async u=>{let p=Array.from(u),d=[];m(y=>{if(i!==void 0){let A=y.filter(Y=>Y.status!=="pendingDeletion"&&Y.status!=="error").length,M=i-A;if(M<=0)return _chunkCR5KJUSTjs.a.warn(`File limit of ${i} already reached`),y;p.length>M&&(p=p.slice(0,M),_chunkCR5KJUSTjs.a.warn(`Only ${M} files will be added to not exceed limit`))}let h=[];for(let A of p){let M=Z(A),Y={id:ct(),name:A.name,size:A.size,contentType:A.type,status:M.valid?"pending":"error",progress:0,createdAt:Date.now(),file:M.valid?A:void 0,errorMessage:M.error,isExisting:!1};h.push(Y)}d=h;let C=[...y,...h];return T(C),C}),setTimeout(()=>{let y=d.filter(h=>h.status==="pending"&&h.file);for(let h of y)if(h.file){let C=V(h,h.file);w.current.set(h.id,C),C.finally(()=>{w.current.delete(h.id)})}},0)},[i,Z,V,T]),dt=_react.useCallback.call(void 0, async u=>{let p=S.find(y=>y.id===u);if(!p)return{needsConfirmation:!1,isExisting:!1};let d=p.isExisting===!0;return b==="create"||!d?{needsConfirmation:!0,isExisting:d}:(O(y=>[...y,u]),m(y=>{let h=y.map(A=>A.id===u?{...A,status:"pendingDeletion"}:A),C=h.filter(A=>A.status!=="pendingDeletion");return T(C),h}),{needsConfirmation:!1,isExisting:d})},[S,b,T]),ft=_react.useCallback.call(void 0, async u=>{let p=S.find(d=>d.id===u);if(!p)return{success:!1,error:"File not found"};if(!p.filePath)return m(d=>{let y=d.filter(h=>h.id!==u);return T(y),y}),{success:!0};try{if(!re.isInitialized())return{success:!1,error:"Crudify not initialized"};let d=Ce(p.filePath);return(await _crudifysdk2.default.disableFile({filePath:d})).success?(m(h=>{let C=h.filter(A=>A.id!==u);return T(C),C}),_optionalChain([f, 'optionalCall', _133 => _133(p)]),{success:!0}):{success:!1,error:"Failed to delete file"}}catch(d){return{success:!1,error:d instanceof Error?d.message:"Unknown error"}}},[S,T,f]),gt=_react.useCallback.call(void 0, u=>{let p=S.find(d=>d.id===u);return!p||!p.isExisting?!1:(O(d=>d.filter(y=>y!==u)),m(d=>{let y=d.map(h=>h.id===u?{...h,status:"completed"}:h);return T(y),y}),!0)},[S,T]),pt=_react.useCallback.call(void 0, ()=>{x.length!==0&&(m(u=>{let p=u.map(d=>x.includes(d.id)?{...d,status:"completed"}:d);return T(p),p}),O([]))},[x,T]),mt=_react.useCallback.call(void 0, async()=>{if(x.length===0)return{success:!0,errors:[]};let u=[],p=[];if(!re.isInitialized())return{success:!1,errors:["Crudify is not initialized. Please wait for the application to finish loading."]};for(let d of x){let y=S.find(h=>h.id===d);if(!_optionalChain([y, 'optionalAccess', _134 => _134.filePath])){p.push(d);continue}try{let h=Ce(y.filePath);(await _crudifysdk2.default.disableFile({filePath:h})).success?(p.push(d),_optionalChain([f, 'optionalCall', _135 => _135(y)])):u.push(`Failed to delete ${y.name}`)}catch(h){u.push(`Error deleting ${y.name}: ${h instanceof Error?h.message:"Unknown error"}`)}}return p.length>0&&(m(d=>d.filter(h=>!p.includes(h.id))),O(d=>d.filter(y=>!p.includes(y)))),{success:u.length===0,errors:u}},[S,x,f]),yt=_react.useCallback.call(void 0, ()=>{m([]),T([])},[T]),ht=_react.useCallback.call(void 0, async u=>{let p=S.find(y=>y.id===u);if(!p||p.status!=="error"||!p.file){_chunkCR5KJUSTjs.a.warn("Cannot retry: file not found or no original file");return}D(u,{status:"pending",progress:0,errorMessage:void 0});let d=V(p,p.file);w.current.set(u,d),d.finally(()=>{w.current.delete(u)})},[S,D,V]),Et=_react.useCallback.call(void 0, async()=>{let u=Array.from(w.current.values());return u.length>0&&await Promise.allSettled(u),new Promise(p=>{setTimeout(()=>{m(d=>{let y=d.filter(h=>h.status==="completed"&&h.filePath).map(h=>h.filePath);return p(y),d})},0)})},[]),St=u=>{let p=_optionalChain([u, 'access', _136 => _136.split, 'call', _137 => _137("."), 'access', _138 => _138.pop, 'call', _139 => _139(), 'optionalAccess', _140 => _140.toLowerCase, 'call', _141 => _141()])||"";return{jpg:"image/jpeg",jpeg:"image/jpeg",png:"image/png",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",bmp:"image/bmp",ico:"image/x-icon",pdf:"application/pdf",doc:"application/msword",docx:"application/vnd.openxmlformats-officedocument.wordprocessingml.document",xls:"application/vnd.ms-excel",xlsx:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",ppt:"application/vnd.ms-powerpoint",pptx:"application/vnd.openxmlformats-officedocument.presentationml.presentation",txt:"text/plain",csv:"text/csv",mp3:"audio/mpeg",wav:"audio/wav",mp4:"video/mp4",webm:"video/webm",zip:"application/zip",rar:"application/x-rar-compressed",json:"application/json",xml:"application/xml"}[p]||"application/octet-stream"},Tt=_react.useCallback.call(void 0, (u,p)=>{let d=u.map(y=>{let h=Ce(y.filePath,p),C=h.includes("/public/")||h.startsWith("public/")?"public":"private",A=y.contentType||St(y.name);return{id:ct(),name:y.name,size:y.size||0,contentType:A,status:"completed",progress:100,filePath:h,visibility:C,createdAt:Date.now(),isExisting:!0}});m(d),T(d)},[T]),vt=_react.useCallback.call(void 0, async u=>{let p=S.find(d=>d.id===u);if(!p||!p.filePath)return null;if(p.visibility==="public"&&p.publicUrl)return p.publicUrl;try{if(!re.isInitialized())return null;let d=await _crudifysdk2.default.getFileUrl({filePath:p.filePath,expiresIn:3600}),y=d.data;return d.success&&_optionalChain([y, 'optionalAccess', _142 => _142.url])?y.url:null}catch (e13){return null}},[S]),bt=_react.useMemo.call(void 0, ()=>S.some(u=>u.status==="uploading"||u.status==="pending"),[S]),It=_react.useMemo.call(void 0, ()=>S.filter(u=>u.status==="uploading"||u.status==="pending").length,[S]),kt=_react.useMemo.call(void 0, ()=>S.filter(u=>u.status==="completed"&&u.filePath).map(u=>u.filePath),[S]),q=_react.useMemo.call(void 0, ()=>S.filter(u=>u.status!=="pendingDeletion"),[S]),At=_react.useMemo.call(void 0, ()=>q.filter(u=>u.status==="completed"||u.status==="pending"||u.status==="uploading").length,[q]),{isValid:xt,validationError:wt,validationErrorKey:Ct,validationErrorParams:Rt}=_react.useMemo.call(void 0, ()=>{let u=q.filter(d=>d.status==="completed").length;if(u<n){let d=n===1?"file.validation.minFilesRequired":"file.validation.minFilesRequiredPlural";return{isValid:!1,validationError:d,validationErrorKey:d,validationErrorParams:{count:n}}}return i!==void 0&&u>i?{isValid:!1,validationError:"file.validation.maxFilesExceeded",validationErrorKey:"file.validation.maxFilesExceeded",validationErrorParams:{count:i}}:q.some(d=>d.status==="error")?{isValid:!1,validationError:"file.validation.filesWithErrors",validationErrorKey:"file.validation.filesWithErrors",validationErrorParams:{}}:{isValid:!0,validationError:null,validationErrorKey:null,validationErrorParams:{}}},[q,n,i]),Nt=x.length>0;return{files:S,activeFiles:q,activeFileCount:At,isUploading:bt,pendingCount:It,addFiles:ne,removeFile:dt,deleteFileImmediately:ft,restoreFile:gt,clearFiles:yt,retryUpload:ht,isValid:xt,validationError:wt,validationErrorKey:Ct,validationErrorParams:Rt,waitForUploads:Et,completedFilePaths:kt,initializeFiles:Tt,isTouched:I,markAsTouched:F,isSubmitted:k,markAsSubmitted:z,getPreviewUrl:vt,pendingDeletions:x,hasPendingDeletions:Nt,commitDeletions:mt,restorePendingDeletions:pt}};exports.a = v; exports.b = Ee; exports.c = B; exports.d = se; exports.e = ve; exports.f = be; exports.g = tt; exports.h = ue; exports.i = rt; exports.j = nt; exports.k = Jr; exports.l = ui; exports.m = Qr; exports.n = sn; exports.o = un; exports.p = we; exports.q = re; exports.r = Tn;
|