@nocios/crudify-ui 4.0.92 → 4.0.94
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chunk-2OSNNNID.js +1 -0
- package/dist/{chunk-YZZ6A6CR.js → chunk-3SLGRD36.js} +1 -1
- package/dist/{chunk-PVQVPSNT.mjs → chunk-5INZZQD6.mjs} +1 -1
- package/dist/{chunk-JFXC3E4B.mjs → chunk-5PZJJNHP.mjs} +1 -1
- package/dist/{chunk-2IJSKTGW.js → chunk-Q7FTH5JW.js} +1 -1
- package/dist/chunk-VVXZWBHL.mjs +1 -0
- 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-CoCUhX7W.d.mts → index-BoWx_rFw.d.mts} +16 -0
- package/dist/{index-B2ZtMz3v.d.ts → index-CQttyYlB.d.ts} +16 -0
- package/dist/index.d.mts +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +1 -1
- package/dist/index.mjs +1 -1
- package/package.json +2 -2
- package/dist/chunk-EP4KANK7.js +0 -1
- package/dist/chunk-TKYA4Q4U.mjs +0 -1
|
@@ -0,0 +1 @@
|
|
|
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 _chunk6EBMA4HZjs = require('./chunk-6EBMA4HZ.js');var _cryptojs = require('crypto-js'); var _cryptojs2 = _interopRequireDefault(_cryptojs);var a=class a{static setStorageType(e){a.storageType=e}static generateEncryptionKey(){let e=[navigator.userAgent,navigator.language,navigator.platform,screen.width,screen.height,Date.now().toString(),Math.random().toString(36)].join("|");return _cryptojs2.default.SHA256(e).toString()}static getEncryptionKey(){if(a.encryptionKey)return a.encryptionKey;let e=window.localStorage;if(!e)return a.encryptionKey=a.generateEncryptionKey(),a.encryptionKey;try{let t=e.getItem(a.ENCRYPTION_KEY_STORAGE);return(!t||t.length<32)&&(t=a.generateEncryptionKey(),e.setItem(a.ENCRYPTION_KEY_STORAGE,t)),a.encryptionKey=t,t}catch (e2){return console.warn("Crudify: Cannot persist encryption key, using temporary key"),a.encryptionKey=a.generateEncryptionKey(),a.encryptionKey}}static isStorageAvailable(e){try{let t=window[e],r="__storage_test__";return t.setItem(r,"test"),t.removeItem(r),!0}catch (e3){return!1}}static getStorage(){return a.storageType==="none"?null:a.isStorageAvailable(a.storageType)?window[a.storageType]:(console.warn(`Crudify: ${a.storageType} not available, tokens won't persist`),null)}static encrypt(e){try{let t=a.getEncryptionKey();return _cryptojs2.default.AES.encrypt(e,t).toString()}catch(t){return console.error("Crudify: Encryption failed",t),e}}static decrypt(e){try{let t=a.getEncryptionKey();return _cryptojs2.default.AES.decrypt(e,t).toString(_cryptojs2.default.enc.Utf8)||e}catch(t){return console.error("Crudify: Decryption failed",t),e}}static saveTokens(e){let t=a.getStorage();if(t)try{let r={accessToken:e.accessToken,refreshToken:e.refreshToken,expiresAt:e.expiresAt,refreshExpiresAt:e.refreshExpiresAt,savedAt:Date.now()},i=a.encrypt(JSON.stringify(r));t.setItem(a.TOKEN_KEY,i),console.debug("Crudify: Tokens saved successfully")}catch(r){console.error("Crudify: Failed to save tokens",r)}}static getTokens(){let e=a.getStorage();if(!e)return null;try{let t=e.getItem(a.TOKEN_KEY);if(!t)return null;let r=a.decrypt(t),i=JSON.parse(r);return!i.accessToken||!i.refreshToken||!i.expiresAt||!i.refreshExpiresAt?(console.warn("Crudify: Incomplete token data found, clearing storage"),a.clearTokens(),null):Date.now()>=i.refreshExpiresAt?(console.info("Crudify: Refresh token expired, clearing storage"),a.clearTokens(),null):{accessToken:i.accessToken,refreshToken:i.refreshToken,expiresAt:i.expiresAt,refreshExpiresAt:i.refreshExpiresAt}}catch(t){return console.error("Crudify: Failed to retrieve tokens",t),a.clearTokens(),null}}static clearTokens(){let e=a.getStorage();if(e)try{e.removeItem(a.TOKEN_KEY),console.debug("Crudify: Tokens cleared from storage")}catch(t){console.error("Crudify: Failed to clear tokens",t)}}static rotateEncryptionKey(){try{a.clearTokens(),a.encryptionKey=null;let e=window.localStorage;e&&e.removeItem(a.ENCRYPTION_KEY_STORAGE),console.info("Crudify: Encryption key rotated successfully")}catch(e){console.error("Crudify: Failed to rotate encryption key",e)}}static hasValidTokens(){return a.getTokens()!==null}static getExpirationInfo(){let e=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 updateAccessToken(e,t){let r=a.getTokens();if(!r){console.warn("Crudify: Cannot update access token, no existing tokens found");return}a.saveTokens({...r,accessToken:e,expiresAt:t})}};a.TOKEN_KEY="crudify_tokens",a.ENCRYPTION_KEY_STORAGE="crudify_enc_key",a.encryptionKey=null,a.storageType="localStorage";var g=a;var _crudifybrowser = require('@nocios/crudify-browser'); var _crudifybrowser2 = _interopRequireDefault(_crudifybrowser);var P=class o{constructor(){this.config={};this.initialized=!1;this.lastActivityTime=0}static getInstance(){return o.instance||(o.instance=new o),o.instance}async initialize(e={}){if(this.initialized){console.warn("SessionManager: Already initialized");return}this.config={storageType:"localStorage",autoRestore:!0,enableLogging:!1,...e},g.setStorageType(this.config.storageType||"localStorage"),this.config.enableLogging,this.config.autoRestore&&await this.restoreSession(),this.initialized=!0,this.log("SessionManager initialized successfully")}async login(e,t){try{this.log("Attempting login...");let r=await _crudifybrowser2.default.login(e,t);if(!r.success)return this.log("Login failed:",r.errors),{success:!1,error:this.formatError(r.errors),rawResponse:r};let i={accessToken:r.data.token,refreshToken:r.data.refreshToken,expiresAt:r.data.expiresAt,refreshExpiresAt:r.data.refreshExpiresAt};return g.saveTokens(i),this.lastActivityTime=Date.now(),this.log("Login successful, tokens saved"),_optionalChain([this, 'access', _2 => _2.config, 'access', _3 => _3.onLoginSuccess, 'optionalCall', _4 => _4(i)]),{success:!0,tokens:i,data:r.data}}catch(r){return this.log("Login error:",r),{success:!1,error:r instanceof Error?r.message:"Unknown error"}}}async logout(){try{this.log("Logging out..."),await _crudifybrowser2.default.logout(),g.clearTokens(),this.log("Logout successful"),_optionalChain([this, 'access', _5 => _5.config, 'access', _6 => _6.onLogout, 'optionalCall', _7 => _7()])}catch(e){this.log("Logout error:",e),g.clearTokens()}}async restoreSession(){try{this.log("Attempting to restore session...");let e=g.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"),g.clearTokens(),!1;if(_crudifybrowser2.default.setTokens({accessToken:e.accessToken,refreshToken:e.refreshToken,expiresAt:e.expiresAt,refreshExpiresAt:e.refreshExpiresAt}),_crudifybrowser2.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 i=g.getTokens();return i&&_optionalChain([this, 'access', _8 => _8.config, 'access', _9 => _9.onSessionRestored, 'optionalCall', _10 => _10(i)]),!0}return g.clearTokens(),await _crudifybrowser2.default.logout(),!1}return this.log("Session restored successfully"),this.lastActivityTime=Date.now(),_optionalChain([this, 'access', _11 => _11.config, 'access', _12 => _12.onSessionRestored, 'optionalCall', _13 => _13(e)]),!0}catch(e){return this.log("Session restore error:",e),g.clearTokens(),await _crudifybrowser2.default.logout(),!1}}isAuthenticated(){return _crudifybrowser2.default.isLogin()||g.hasValidTokens()}getTokenInfo(){let e=_crudifybrowser2.default.getTokenData(),t=g.getExpirationInfo();return{isLoggedIn:this.isAuthenticated(),crudifyTokens:e,storageInfo:t,hasValidTokens:g.hasValidTokens()}}async refreshTokens(){try{this.log("Manually refreshing tokens...");let e=await _crudifybrowser2.default.refreshAccessToken();if(!e.success)return this.log("Token refresh failed:",e.errors),g.clearTokens(),_optionalChain([this, 'access', _14 => _14.config, 'access', _15 => _15.showNotification, 'optionalCall', _16 => _16(this.getSessionExpiredMessage(),"warning")]),_optionalChain([this, 'access', _17 => _17.config, 'access', _18 => _18.onSessionExpired, 'optionalCall', _19 => _19()]),!1;let t={accessToken:e.data.token,refreshToken:e.data.refreshToken,expiresAt:e.data.expiresAt,refreshExpiresAt:e.data.refreshExpiresAt};return g.saveTokens(t),this.log("Tokens refreshed and saved successfully"),this.lastActivityTime=Date.now(),!0}catch(e){return this.log("Token refresh error:",e),g.clearTokens(),_optionalChain([this, 'access', _20 => _20.config, 'access', _21 => _21.showNotification, 'optionalCall', _22 => _22(this.getSessionExpiredMessage(),"warning")]),_optionalChain([this, 'access', _23 => _23.config, 'access', _24 => _24.onSessionExpired, 'optionalCall', _25 => _25()]),!1}}setupResponseInterceptor(){_crudifybrowser2.default.setResponseInterceptor(async e=>{this.updateLastActivity();let t=this.detectAuthorizationError(e);if(t.isAuthError){if(console.warn("\u{1F6A8} SessionManager - Authorization error detected:",{errorType:t.errorType,errorDetails:t.errorDetails,fullResponse:e}),t.isRefreshTokenInvalid||t.isTokenRefreshFailed)return this.log("Refresh token invalid or refresh already failed, clearing session"),g.clearTokens(),_optionalChain([this, 'access', _26 => _26.config, 'access', _27 => _27.showNotification, 'optionalCall', _28 => _28(this.getSessionExpiredMessage(),"warning")]),_optionalChain([this, 'access', _29 => _29.config, 'access', _30 => _30.onSessionExpired, 'optionalCall', _31 => _31()]),e;g.hasValidTokens()&&!t.isIrrecoverable?(this.log("Auth error detected, attempting token refresh..."),await this.refreshTokens()||(this.log("Token refresh failed, triggering session expired"),_optionalChain([this, 'access', _32 => _32.config, 'access', _33 => _33.onSessionExpired, 'optionalCall', _34 => _34()]))):(this.log("Auth error with no valid tokens or irrecoverable error, triggering session expired"),g.clearTokens(),_optionalChain([this, 'access', _35 => _35.config, 'access', _36 => _36.showNotification, 'optionalCall', _37 => _37(this.getSessionExpiredMessage(),"warning")]),_optionalChain([this, 'access', _38 => _38.config, 'access', _39 => _39.onSessionExpired, 'optionalCall', _40 => _40()]))}return e}),this.log("Response interceptor configured")}detectAuthorizationError(e){let t={isAuthError:!1,isRefreshTokenInvalid:!1,isTokenRefreshFailed:!1,isIrrecoverable:!1,errorType:"",errorDetails:null};if(e.errors){if(Array.isArray(e.errors))e.errors.some(i=>i.errorType==="Unauthorized"||_optionalChain([i, 'access', _41 => _41.message, 'optionalAccess', _42 => _42.includes, 'call', _43 => _43("Unauthorized")])||_optionalChain([i, 'access', _44 => _44.message, 'optionalAccess', _45 => _45.includes, 'call', _46 => _46("Not Authorized")])||_optionalChain([i, 'access', _47 => _47.message, 'optionalAccess', _48 => _48.includes, 'call', _49 => _49("Token")])||_optionalChain([i, 'access', _50 => _50.extensions, 'optionalAccess', _51 => _51.code])==="UNAUTHENTICATED"||_optionalChain([i, 'access', _52 => _52.message, 'optionalAccess', _53 => _53.includes, 'call', _54 => _54("NOT_AUTHORIZED")]))&&(t.isAuthError=!0,t.errorType="GraphQL Array Format",t.errorDetails=e.errors);else if(typeof e.errors=="object"){let r=Object.values(e.errors).flat();r.some(u=>typeof u=="string"&&(u.includes("NOT_AUTHORIZED")||u.includes("TOKEN_REFRESH_FAILED")||u.includes("PLEASE_LOGIN")||u.includes("Unauthorized")||u.includes("UNAUTHENTICATED")||u.includes("Token")))&&(t.isAuthError=!0,t.errorType="GraphQL Object Format",t.errorDetails=e.errors,t.isTokenRefreshFailed=r.some(u=>typeof u=="string"&&u.includes("TOKEN_REFRESH_FAILED")))}}if(!t.isAuthError&&_optionalChain([e, 'access', _55 => _55.data, 'optionalAccess', _56 => _56.response, 'optionalAccess', _57 => _57.status])==="UNAUTHORIZED"&&(t.isAuthError=!0,t.errorType="Status UNAUTHORIZED",t.errorDetails=e.data.response,t.isIrrecoverable=!0),!t.isAuthError&&_optionalChain([e, 'access', _58 => _58.data, 'optionalAccess', _59 => _59.response, 'optionalAccess', _60 => _60.data]))try{let r=JSON.parse(e.data.response.data);(r.error==="REFRESH_TOKEN_INVALID"||r.error==="TOKEN_EXPIRED")&&(t.isAuthError=!0,t.errorType="Parsed Data Format",t.errorDetails=r,t.isRefreshTokenInvalid=!0,t.isIrrecoverable=!0)}catch (e4){}if(!t.isAuthError&&e.errorCode){let r=e.errorCode;(r==="UNAUTHORIZED"||r==="UNAUTHENTICATED"||r==="TOKEN_EXPIRED")&&(t.isAuthError=!0,t.errorType="Error Code Format",t.errorDetails={errorCode:r})}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(),t=_crudifybrowser2.default.getTokenData();if(this.lastActivityTime===0)return"none";let r=900*1e3,i=300*1e3,u=300*1e3;return e>r?(this.log(`Inactivity timeout: ${Math.floor(e/6e4)} minutes since last activity`),"logout"):e<i&&t.expiresIn<u&&t.expiresIn>0?(this.log(`User active recently (${Math.floor(e/6e4)}min ago) and token expiring soon, should refresh`),"refresh"):"none"}clearSession(){g.clearTokens(),_crudifybrowser2.default.logout(),this.lastActivityTime=0,this.log("Session cleared completely")}getSessionExpiredMessage(){return this.config.translateFn?_chunk6EBMA4HZjs.b.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&&console.log(`[SessionManager] ${e}`,...t)}formatError(e){return e?typeof e=="string"?e:typeof e=="object"?Object.values(e).flat().join(", "):"Authentication failed":"Unknown error"}};var _react = require('react'); var _react2 = _interopRequireDefault(_react);function j(o={}){let[e,t]=_react.useState.call(void 0, {isAuthenticated:!1,isLoading:!0,isInitialized:!1,tokens:null,error:null}),r=P.getInstance(),i=_react.useCallback.call(void 0, async()=>{try{t(s=>({...s,isLoading:!0,error:null}));let l={autoRestore:_nullishCoalesce(o.autoRestore, () => (!0)),enableLogging:_nullishCoalesce(o.enableLogging, () => (!1)),showNotification:o.showNotification,translateFn:o.translateFn,onSessionExpired:()=>{t(s=>({...s,isAuthenticated:!1,tokens:null,error:"Session expired"})),_optionalChain([o, 'access', _61 => _61.onSessionExpired, 'optionalCall', _62 => _62()])},onSessionRestored:s=>{t(d=>({...d,isAuthenticated:!0,tokens:s,error:null})),_optionalChain([o, 'access', _63 => _63.onSessionRestored, 'optionalCall', _64 => _64(s)])},onLoginSuccess:s=>{t(d=>({...d,isAuthenticated:!0,tokens:s,error:null}))},onLogout:()=>{t(s=>({...s,isAuthenticated:!1,tokens:null,error:null}))}};await r.initialize(l),r.setupResponseInterceptor();let n=r.isAuthenticated(),c=r.getTokenInfo();t(s=>({...s,isAuthenticated:n,isInitialized:!0,isLoading:!1,tokens:c.crudifyTokens.accessToken?{accessToken:c.crudifyTokens.accessToken,refreshToken:c.crudifyTokens.refreshToken,expiresAt:c.crudifyTokens.expiresAt,refreshExpiresAt:c.crudifyTokens.refreshExpiresAt}:null}))}catch(l){let n=l instanceof Error?l.message:"Initialization failed";t(c=>({...c,isLoading:!1,isInitialized:!0,error:n}))}},[o.autoRestore,o.enableLogging,o.onSessionExpired,o.onSessionRestored]),u=_react.useCallback.call(void 0, async(l,n)=>{t(c=>({...c,isLoading:!0,error:null}));try{let c=await r.login(l,n);return c.success&&c.tokens?t(s=>({...s,isAuthenticated:!0,tokens:c.tokens,isLoading:!1,error:null})):t(s=>({...s,isAuthenticated:!1,tokens:null,isLoading:!1,error:null})),c}catch(c){let s=c instanceof Error?c.message:"Login failed",d=s.includes("INVALID_CREDENTIALS")||s.includes("Invalid email")||s.includes("Invalid password")||s.includes("credentials");return t(T=>({...T,isAuthenticated:!1,tokens:null,isLoading:!1,error:d?null:s})),{success:!1,error:s}}},[r]),v=_react.useCallback.call(void 0, async()=>{t(l=>({...l,isLoading:!0}));try{await r.logout(),t(l=>({...l,isAuthenticated:!1,tokens:null,isLoading:!1,error:null}))}catch(l){t(n=>({...n,isAuthenticated:!1,tokens:null,isLoading:!1,error:l instanceof Error?l.message:"Logout error"}))}},[r]),p=_react.useCallback.call(void 0, async()=>{try{let l=await r.refreshTokens();if(l){let n=r.getTokenInfo();t(c=>({...c,tokens:n.crudifyTokens.accessToken?{accessToken:n.crudifyTokens.accessToken,refreshToken:n.crudifyTokens.refreshToken,expiresAt:n.crudifyTokens.expiresAt,refreshExpiresAt:n.crudifyTokens.refreshExpiresAt}:null,error:null}))}else t(n=>({...n,isAuthenticated:!1,tokens:null,error:"Token refresh failed"}));return l}catch(l){return t(n=>({...n,isAuthenticated:!1,tokens:null,error:l instanceof Error?l.message:"Token refresh failed"})),!1}},[r]),x=_react.useCallback.call(void 0, ()=>{t(l=>({...l,error:null}))},[]),k=_react.useCallback.call(void 0, ()=>r.getTokenInfo(),[r]);_react.useEffect.call(void 0, ()=>{i()},[i]),_react.useEffect.call(void 0, ()=>{if(!e.isAuthenticated||!e.tokens)return;let l=()=>{r.updateLastActivity(),o.enableLogging&&console.log("\u{1F4CD} User navigating - activity updated")};window.addEventListener("popstate",l);let n=window.history.pushState,c=window.history.replaceState;window.history.pushState=function(...d){let T=n.apply(this,d);return l(),T},window.history.replaceState=function(...d){let T=c.apply(this,d);return l(),T};let s=setInterval(async()=>{let d=r.checkInactivity();if(d==="logout")o.enableLogging&&console.log("\u23F1\uFE0F Inactivity timeout - logging out user"),await v();else if(d==="refresh"&&(o.enableLogging&&console.log("\u{1F504} User active, token expiring soon - refreshing..."),await r.refreshTokens())){let h=r.getTokenInfo();t(b=>({...b,tokens:h.crudifyTokens.accessToken?{accessToken:h.crudifyTokens.accessToken,refreshToken:h.crudifyTokens.refreshToken,expiresAt:h.crudifyTokens.expiresAt,refreshExpiresAt:h.crudifyTokens.refreshExpiresAt}:null}))}},120*1e3);return()=>{clearInterval(s),window.removeEventListener("popstate",l),window.history.pushState=n,window.history.replaceState=c}},[e.isAuthenticated,e.tokens,r,o.enableLogging,v]);let S=_react.useCallback.call(void 0, ()=>{r.updateLastActivity()},[r]);return{...e,login:u,logout:v,refreshTokens:p,clearError:x,getTokenInfo:k,updateActivity:S,isExpiringSoon:e.tokens?e.tokens.expiresAt-Date.now()<300*1e3:!1,expiresIn:e.tokens?Math.max(0,e.tokens.expiresAt-Date.now()):0,refreshExpiresIn:e.tokens?Math.max(0,e.tokens.refreshExpiresAt-Date.now()):0}}var _material = require('@mui/material');var _uuid = require('uuid');var _dompurify = require('dompurify'); var _dompurify2 = _interopRequireDefault(_dompurify);var _jsxruntime = require('react/jsx-runtime');var B=_react.createContext.call(void 0, null),ue=o=>_dompurify2.default.sanitize(o,{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}),J= exports.d =({children:o,maxNotifications:e=5,defaultAutoHideDuration:t=6e3,position:r={vertical:"top",horizontal:"right"},enabled:i=!1,allowHtml:u=!1})=>{let[v,p]=_react.useState.call(void 0, []),x=_react.useCallback.call(void 0, (n,c="info",s)=>{if(!i)return"";if(!n||typeof n!="string")return console.warn("\u26A0\uFE0F GlobalNotificationProvider: Invalid message provided"),"";n.length>1e3&&(console.warn("\u26A0\uFE0F GlobalNotificationProvider: Message too long, truncating"),n=n.substring(0,1e3)+"...");let d=_uuid.v4.call(void 0, ),T={id:d,message:n,severity:c,autoHideDuration:_nullishCoalesce(_optionalChain([s, 'optionalAccess', _65 => _65.autoHideDuration]), () => (t)),persistent:_nullishCoalesce(_optionalChain([s, 'optionalAccess', _66 => _66.persistent]), () => (!1)),allowHtml:_nullishCoalesce(_optionalChain([s, 'optionalAccess', _67 => _67.allowHtml]), () => (u))};return p(h=>[...h.length>=e?h.slice(-(e-1)):h,T]),d},[e,t,i,u]),k=_react.useCallback.call(void 0, n=>{p(c=>c.filter(s=>s.id!==n))},[]),S=_react.useCallback.call(void 0, ()=>{p([])},[]),l={showNotification:x,hideNotification:k,clearAllNotifications:S};return _jsxruntime.jsxs.call(void 0, B.Provider,{value:l,children:[o,i&&_jsxruntime.jsx.call(void 0, _material.Portal,{children:_jsxruntime.jsx.call(void 0, _material.Box,{sx:{position:"fixed",zIndex:9999,[r.vertical]:(r.vertical==="top",24),[r.horizontal]:r.horizontal==="right"||r.horizontal==="left"?24:"50%",...r.horizontal==="center"&&{transform:"translateX(-50%)"},display:"flex",flexDirection:r.vertical==="top"?"column":"column-reverse",gap:1,maxWidth:"400px",width:"auto"},children:v.map(n=>_jsxruntime.jsx.call(void 0, fe,{notification:n,onClose:()=>k(n.id)},n.id))})})]})},fe=({notification:o,onClose:e})=>{let[t,r]=_react.useState.call(void 0, !0),i=_react.useCallback.call(void 0, (u,v)=>{v!=="clickaway"&&(r(!1),setTimeout(e,300))},[e]);return _react.useEffect.call(void 0, ()=>{if(!o.persistent&&o.autoHideDuration){let u=setTimeout(()=>{i()},o.autoHideDuration);return()=>clearTimeout(u)}},[o.autoHideDuration,o.persistent,i]),_jsxruntime.jsx.call(void 0, _material.Snackbar,{open:t,onClose:i,sx:{position:"relative","& .MuiSnackbarContent-root":{minWidth:"auto"}},TransitionProps:{enter:!0,exit:!0},children:_jsxruntime.jsx.call(void 0, _material.Alert,{variant:"filled",severity:o.severity,onClose:i,sx:{width:"100%",minWidth:"280px",maxWidth:"400px",wordBreak:"break-word"},children:o.allowHtml?_jsxruntime.jsx.call(void 0, "span",{dangerouslySetInnerHTML:{__html:ue(o.message)}}):_jsxruntime.jsx.call(void 0, "span",{children:o.message})})})},_= exports.e =()=>{let o=_react.useContext.call(void 0, B);if(!o)throw new Error("useGlobalNotification debe ser usado dentro de un GlobalNotificationProvider");return o};var X=_react.createContext.call(void 0, void 0);function ye({children:o,options:e={},config:t,showNotifications:r=!1,notificationOptions:i={}}){let u;try{let{showNotification:n}=_();u=n}catch (e5){}let v=_react2.default.useMemo(()=>({...e,showNotification:u,onSessionExpired:()=>{_optionalChain([e, 'access', _68 => _68.onSessionExpired, 'optionalCall', _69 => _69()])}}),[e,u]),p=j(v),x=_react.useMemo.call(void 0, ()=>{let n,c,s,d,T,h="unknown";if(_optionalChain([t, 'optionalAccess', _70 => _70.publicApiKey])&&(n=t.publicApiKey,h="props"),_optionalChain([t, 'optionalAccess', _71 => _71.env])&&(c=t.env),_optionalChain([t, 'optionalAccess', _72 => _72.appName])&&(s=t.appName),_optionalChain([t, 'optionalAccess', _73 => _73.loginActions])&&(d=t.loginActions),_optionalChain([t, 'optionalAccess', _74 => _74.logo])&&(T=t.logo),!n){let b=_chunk6EBMA4HZjs.a.call(void 0, "publicApiKey"),N=_chunk6EBMA4HZjs.a.call(void 0, "environment"),R=_chunk6EBMA4HZjs.a.call(void 0, "appName"),E=_chunk6EBMA4HZjs.a.call(void 0, "loginActions"),f=_chunk6EBMA4HZjs.a.call(void 0, "logo");b&&(n=b,h="cookies"),N&&["dev","stg","prod"].includes(N)&&(c=N),R&&(s=decodeURIComponent(R)),E&&(d=decodeURIComponent(E).split(",").map(L=>L.trim()).filter(Boolean)),f&&(T=decodeURIComponent(f))}return{publicApiKey:n,env:c,appName:s,loginActions:d,logo:T}},[t]),k=_react.useMemo.call(void 0, ()=>{if(!_optionalChain([p, 'access', _75 => _75.tokens, 'optionalAccess', _76 => _76.accessToken])||!p.isAuthenticated)return null;try{let n=_chunk6EBMA4HZjs.f.call(void 0, p.tokens.accessToken);if(n&&n.sub&&n.email&&n.subscriber){let c={_id:n.sub,email:n.email,subscriberKey:n.subscriber};return Object.keys(n).forEach(s=>{["sub","email","subscriber"].includes(s)||(c[s]=n[s])}),c}}catch(n){console.error("Error decoding JWT token for sessionData:",n)}return null},[_optionalChain([p, 'access', _77 => _77.tokens, 'optionalAccess', _78 => _78.accessToken]),p.isAuthenticated]),S={...p,sessionData:k,config:x},l={enabled:r,maxNotifications:i.maxNotifications||5,defaultAutoHideDuration:i.defaultAutoHideDuration||6e3,position:i.position||{vertical:"top",horizontal:"right"}};return _jsxruntime.jsx.call(void 0, X.Provider,{value:S,children:o})}function Be(o){let e={enabled:o.showNotifications,maxNotifications:_optionalChain([o, 'access', _79 => _79.notificationOptions, 'optionalAccess', _80 => _80.maxNotifications])||5,defaultAutoHideDuration:_optionalChain([o, 'access', _81 => _81.notificationOptions, 'optionalAccess', _82 => _82.defaultAutoHideDuration])||6e3,position:_optionalChain([o, 'access', _83 => _83.notificationOptions, 'optionalAccess', _84 => _84.position])||{vertical:"top",horizontal:"right"},allowHtml:_optionalChain([o, 'access', _85 => _85.notificationOptions, 'optionalAccess', _86 => _86.allowHtml])||!1};return _jsxruntime.jsx.call(void 0, J,{...e,children:_jsxruntime.jsx.call(void 0, ye,{...o})})}function Z(){let o=_react.useContext.call(void 0, X);if(o===void 0)throw new Error("useSessionContext must be used within a SessionProvider");return o}function Je({children:o,fallback:e=_jsxruntime.jsx.call(void 0, "div",{children:"Please log in to access this content"}),redirectTo:t}){let{isAuthenticated:r,isLoading:i,isInitialized:u}=Z();return!u||i?_jsxruntime.jsx.call(void 0, "div",{children:"Loading..."}):r?_jsxruntime.jsx.call(void 0, _jsxruntime.Fragment,{children:o}):t?(t(),null):_jsxruntime.jsx.call(void 0, _jsxruntime.Fragment,{children:e})}function _e(){let o=Z();return o.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:"})," ",o.isAuthenticated?"Yes":"No"]}),_jsxruntime.jsxs.call(void 0, "div",{children:[_jsxruntime.jsx.call(void 0, "strong",{children:"Loading:"})," ",o.isLoading?"Yes":"No"]}),_jsxruntime.jsxs.call(void 0, "div",{children:[_jsxruntime.jsx.call(void 0, "strong",{children:"Error:"})," ",o.error||"None"]}),o.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:"})," ",o.tokens.accessToken.substring(0,20),"..."]}),_jsxruntime.jsxs.call(void 0, "div",{children:[_jsxruntime.jsx.call(void 0, "strong",{children:"Refresh Token:"})," ",o.tokens.refreshToken.substring(0,20),"..."]}),_jsxruntime.jsxs.call(void 0, "div",{children:[_jsxruntime.jsx.call(void 0, "strong",{children:"Access Expires In:"})," ",Math.round(o.expiresIn/1e3/60)," minutes"]}),_jsxruntime.jsxs.call(void 0, "div",{children:[_jsxruntime.jsx.call(void 0, "strong",{children:"Refresh Expires In:"})," ",Math.round(o.refreshExpiresIn/1e3/60/60)," hours"]}),_jsxruntime.jsxs.call(void 0, "div",{children:[_jsxruntime.jsx.call(void 0, "strong",{children:"Expiring Soon:"})," ",o.isExpiringSoon?"Yes":"No"]})]})]}):_jsxruntime.jsx.call(void 0, "div",{children:"Session not initialized"})}var et=(o={})=>{let{autoFetch:e=!0,retryOnError:t=!1,maxRetries:r=3}=o,[i,u]=_react.useState.call(void 0, null),[v,p]=_react.useState.call(void 0, !1),[x,k]=_react.useState.call(void 0, null),[S,l]=_react.useState.call(void 0, {}),n=_react.useRef.call(void 0, null),c=_react.useRef.call(void 0, !0),s=_react.useRef.call(void 0, 0),d=_react.useRef.call(void 0, 0),T=_react.useCallback.call(void 0, ()=>{u(null),k(null),p(!1),l({})},[]),h=_react.useCallback.call(void 0, async()=>{let b=_chunk6EBMA4HZjs.g.call(void 0, );if(!b){c.current&&(k("No user email available"),p(!1));return}n.current&&n.current.abort();let N=new AbortController;n.current=N;let R=++s.current;try{c.current&&(p(!0),k(null));let E=await _crudifybrowser2.default.readItems("users",{filter:{email:b},pagination:{limit:1}});if(R===s.current&&c.current&&!N.signal.aborted)if(E.success&&E.data&&E.data.length>0){let f=E.data[0];u(f);let H={fullProfile:f,totalFields:Object.keys(f).length,displayData:{id:f.id,email:f.email,username:f.username,firstName:f.firstName,lastName:f.lastName,fullName:f.fullName||`${f.firstName||""} ${f.lastName||""}`.trim(),role:f.role,permissions:f.permissions||[],isActive:f.isActive,lastLogin:f.lastLogin,createdAt:f.createdAt,updatedAt:f.updatedAt,...Object.keys(f).filter(L=>!["id","email","username","firstName","lastName","fullName","role","permissions","isActive","lastLogin","createdAt","updatedAt"].includes(L)).reduce((L,z)=>({...L,[z]:f[z]}),{})}};l(H),k(null),d.current=0}else k("User profile not found"),u(null),l({})}catch(E){if(R===s.current&&c.current){let f=E;if(f.name==="AbortError")return;t&&d.current<r&&(_optionalChain([f, 'access', _87 => _87.message, 'optionalAccess', _88 => _88.includes, 'call', _89 => _89("Network Error")])||_optionalChain([f, 'access', _90 => _90.message, 'optionalAccess', _91 => _91.includes, 'call', _92 => _92("Failed to fetch")]))?(d.current++,setTimeout(()=>{c.current&&h()},1e3*d.current)):(k("Failed to load user profile"),u(null),l({}))}}finally{R===s.current&&c.current&&p(!1),n.current===N&&(n.current=null)}},[t,r]);return _react.useEffect.call(void 0, ()=>{e&&h()},[e,h]),_react.useEffect.call(void 0, ()=>(c.current=!0,()=>{c.current=!1,n.current&&(n.current.abort(),n.current=null)}),[]),{userProfile:i,loading:v,error:x,extendedData:S,refreshProfile:h,clearProfile:T}};exports.a = g; exports.b = P; exports.c = j; exports.d = J; exports.e = _; exports.f = Be; exports.g = Z; exports.h = Je; exports.i = _e; exports.j = et;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } 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 _chunkEP4KANK7js = require('./chunk-EP4KANK7.js');var _react = require('react');var _crudifybrowser = require('@nocios/crudify-browser'); var _crudifybrowser2 = _interopRequireDefault(_crudifybrowser);var G=(S={})=>{let{autoFetch:c=!0,retryOnError:N=!1,maxRetries:g=3}=S,{isAuthenticated:T,isInitialized:I,sessionData:a,tokens:R}=_chunkEP4KANK7js.g.call(void 0, ),[E,d]=_react.useState.call(void 0, null),[y,O]=_react.useState.call(void 0, !1),[A,p]=_react.useState.call(void 0, null),u=_react.useRef.call(void 0, null),o=_react.useRef.call(void 0, !0),m=_react.useRef.call(void 0, 0),l=_react.useRef.call(void 0, 0),L=_react.useCallback.call(void 0, ()=>a&&(a.email||a["cognito:username"])||null,[a]),P=_react.useCallback.call(void 0, ()=>{d(null),p(null),O(!1),l.current=0},[]),w=_react.useCallback.call(void 0, async()=>{let x=L();if(!x){o.current&&(p("No user email available from session data"),O(!1));return}if(!I){o.current&&(p("Session not initialized"),O(!1));return}u.current&&u.current.abort();let e=new AbortController;u.current=e;let i=++m.current;try{o.current&&(O(!0),p(null));let r=await _crudifybrowser2.default.readItems("users",{filter:{email:x},pagination:{limit:1}});if(i===m.current&&o.current&&!e.signal.aborted){let t=null;if(r.success){if(Array.isArray(r.data)&&r.data.length>0)t=r.data[0];else if(_optionalChain([r, 'access', _2 => _2.data, 'optionalAccess', _3 => _3.response, 'optionalAccess', _4 => _4.data]))try{let s=r.data.response.data,n=typeof s=="string"?JSON.parse(s):s;n&&n.items&&Array.isArray(n.items)&&n.items.length>0&&(t=n.items[0])}catch (e2){}else if(r.data&&typeof r.data=="object")r.data.items&&Array.isArray(r.data.items)&&r.data.items.length>0&&(t=r.data.items[0]);else if(_optionalChain([r, 'access', _5 => _5.data, 'optionalAccess', _6 => _6.data, 'optionalAccess', _7 => _7.response, 'optionalAccess', _8 => _8.data]))try{let s=r.data.data.response.data,n=typeof s=="string"?JSON.parse(s):s;n&&n.items&&Array.isArray(n.items)&&n.items.length>0&&(t=n.items[0])}catch (e3){}}t?(d(t),p(null),l.current=0):(p("User profile not found in database"),d(null))}}catch(r){if(i===m.current&&o.current){let t=r;if(t.name==="AbortError")return;N&&l.current<g&&(_optionalChain([t, 'access', _9 => _9.message, 'optionalAccess', _10 => _10.includes, 'call', _11 => _11("Network Error")])||_optionalChain([t, 'access', _12 => _12.message, 'optionalAccess', _13 => _13.includes, 'call', _14 => _14("Failed to fetch")]))?(l.current++,setTimeout(()=>{o.current&&w()},1e3*l.current)):(p("Failed to load user profile from database"),d(null))}}finally{i===m.current&&o.current&&O(!1),u.current===e&&(u.current=null)}},[I,L,N,g]);return _react.useEffect.call(void 0, ()=>{c&&T&&I?w():T||P()},[c,T,I,w,P]),_react.useEffect.call(void 0, ()=>(o.current=!0,()=>{o.current=!1,u.current&&(u.current.abort(),u.current=null)}),[]),{user:{session:a,data:E},loading:y,error:A,refreshProfile:w,clearProfile:P}};var ee=()=>{let{isAuthenticated:S,isLoading:c,isInitialized:N,tokens:g,error:T,sessionData:I,login:a,logout:R,refreshTokens:E,clearError:d,getTokenInfo:y,isExpiringSoon:O,expiresIn:A,refreshExpiresIn:p}=_chunkEP4KANK7js.g.call(void 0, ),u=_react.useCallback.call(void 0, m=>{m?console.warn("useAuth.setToken() is deprecated. Use login() method instead for better security."):R()},[R]),o=_optionalChain([g, 'optionalAccess', _15 => _15.expiresAt])?new Date(g.expiresAt):null;return{isAuthenticated:S,loading:c,error:T,token:_optionalChain([g, 'optionalAccess', _16 => _16.accessToken])||null,user:I,tokenExpiration:o,setToken:u,logout:R,refreshToken:E,login:a,isExpiringSoon:O,expiresIn:A,refreshExpiresIn:p,getTokenInfo:y,clearError:d}};var oe=()=>{let{isInitialized:S,isLoading:c,error:N,isAuthenticated:g,login:T}=_chunkEP4KANK7js.g.call(void 0, ),I=_react.useCallback.call(void 0, ()=>S&&!c&&!N,[S,c,N]),a=_react.useCallback.call(void 0, async()=>new Promise((o,m)=>{let l=()=>{I()?o():N?m(new Error(N)):setTimeout(l,100)};l()}),[I,N]),R=_react.useCallback.call(void 0, async()=>{if(!I())throw new Error("System not ready. Check isInitialized, isLoading, and error states.")},[I]),E=_react.useCallback.call(void 0, async(o,m,l)=>(await R(),await _crudifybrowser2.default.readItems(o,m||{},l)),[R]),d=_react.useCallback.call(void 0, async(o,m,l)=>(await R(),await _crudifybrowser2.default.readItem(o,m,l)),[R]),y=_react.useCallback.call(void 0, async(o,m,l)=>(await R(),await _crudifybrowser2.default.createItem(o,m,l)),[R]),O=_react.useCallback.call(void 0, async(o,m,l)=>(await R(),await _crudifybrowser2.default.updateItem(o,m,l)),[R]),A=_react.useCallback.call(void 0, async(o,m,l)=>(await R(),await _crudifybrowser2.default.deleteItem(o,m,l)),[R]),p=_react.useCallback.call(void 0, async(o,m)=>(await R(),await _crudifybrowser2.default.transaction(o,m)),[R]),u=_react.useCallback.call(void 0, async(o,m)=>{try{let l=await T(o,m);return l.success?{success:!0,data:l.tokens}:{success:!1,errors:l.error||"Login failed"}}catch(l){return{success:!1,errors:l instanceof Error?l.message:"Login failed"}}},[T]);return{readItems:E,readItem:d,createItem:y,updateItem:O,deleteItem:A,transaction:p,login:u,isInitialized:S,isInitializing:c,initializationError:N,isReady:I,waitForReady:a}};var Y={INVALID_CREDENTIALS:"warning",UNAUTHORIZED:"warning",INVALID_API_KEY:"error",USER_NOT_FOUND:"warning",USER_NOT_ACTIVE:"warning",NO_PERMISSION:"warning",ITEM_NOT_FOUND:"info",NOT_FOUND:"info",IN_USE:"warning",FIELD_ERROR:"warning",BAD_REQUEST:"warning",INTERNAL_SERVER_ERROR:"error",DATABASE_CONNECTION_ERROR:"error",INVALID_CONFIGURATION:"error",UNKNOWN_OPERATION:"error",TOO_MANY_REQUESTS:"warning"},v={INVALID_CREDENTIALS:"errors.auth.INVALID_CREDENTIALS",UNAUTHORIZED:"errors.auth.UNAUTHORIZED",INVALID_API_KEY:"errors.auth.INVALID_API_KEY",USER_NOT_FOUND:"errors.auth.USER_NOT_FOUND",USER_NOT_ACTIVE:"errors.auth.USER_NOT_ACTIVE",NO_PERMISSION:"errors.auth.NO_PERMISSION",ITEM_NOT_FOUND:"errors.data.ITEM_NOT_FOUND",NOT_FOUND:"errors.data.NOT_FOUND",IN_USE:"errors.data.IN_USE",FIELD_ERROR:"errors.data.FIELD_ERROR",BAD_REQUEST:"errors.data.BAD_REQUEST",INTERNAL_SERVER_ERROR:"errors.system.INTERNAL_SERVER_ERROR",DATABASE_CONNECTION_ERROR:"errors.system.DATABASE_CONNECTION_ERROR",INVALID_CONFIGURATION:"errors.system.INVALID_CONFIGURATION",UNKNOWN_OPERATION:"errors.system.UNKNOWN_OPERATION",TOO_MANY_REQUESTS:"errors.system.TOO_MANY_REQUESTS"},le= exports.d =(S={})=>{let{showNotification:c}=_chunkEP4KANK7js.e.call(void 0, ),{showSuccessNotifications:N=!1,showErrorNotifications:g=!0,customErrorMessages:T={},defaultErrorMessage:I="Ha ocurrido un error inesperado",autoHideDuration:a=6e3,appStructure:R=[],translateFn:E=e=>e}=S,d=_react.useCallback.call(void 0, e=>!(!e.success&&e.errors&&(Object.keys(e.errors).some(r=>r!=="_error"&&r!=="_graphql"&&r!=="_transaction")||_optionalChain([e, 'access', _17 => _17.errors, 'access', _18 => _18._transaction, 'optionalAccess', _19 => _19.includes, 'call', _20 => _20("ONE_OR_MORE_OPERATIONS_FAILED")])||_optionalChain([e, 'access', _21 => _21.errors, 'access', _22 => _22._error, 'optionalAccess', _23 => _23.includes, 'call', _24 => _24("TOO_MANY_REQUESTS")]))||!e.success&&_optionalChain([e, 'access', _25 => _25.data, 'optionalAccess', _26 => _26.response, 'optionalAccess', _27 => _27.status])==="TOO_MANY_REQUESTS"),[]),y=_react.useCallback.call(void 0, (e,i)=>{let r=E(e);return r===e?i||E("error.unknown"):r},[E]),O=_react.useCallback.call(void 0, e=>["create","update","delete"].includes(e),[]),A=_react.useCallback.call(void 0, (e,i)=>N?O(e)&&i?!0:R.some(r=>r.key===e):!1,[N,R,O]),p=_react.useCallback.call(void 0, (e,i,r)=>{let t=_optionalChain([r, 'optionalAccess', _28 => _28.key])&&typeof r.key=="string"?r.key:e,s=`action.onSuccess.${t}`,n=y(s);if(n!==E("error.unknown")){if(O(t)&&i){let f=`action.${i}Singular`,_=y(f);if(_!==E("error.unknown"))return E(s,{item:_});{let M=`action.onSuccess.${t}WithoutItem`,k=y(M);return k!==E("error.unknown")?k:n}}return n}return E("success.transaction")},[y,E,O]),u=_react.useCallback.call(void 0, e=>{if(e.errorCode&&T[e.errorCode])return T[e.errorCode];if(e.errorCode&&v[e.errorCode])return y(v[e.errorCode]);if(e.errorCode){let i=[`errors.auth.${e.errorCode}`,`errors.data.${e.errorCode}`,`errors.system.${e.errorCode}`,`errors.${e.errorCode}`];for(let r of i){let t=y(r);if(t!==E("error.unknown"))return t}}if(typeof e.data=="string"&&e.data.startsWith("errors.")){let i=y(e.data);if(i!==E("error.unknown"))return i}if(e.errors&&Object.keys(e.errors).length>0){let i=Object.keys(e.errors);if(i.length===1&&i[0]==="_transaction"){let r=e.errors._transaction;if(_optionalChain([r, 'optionalAccess', _29 => _29.includes, 'call', _30 => _30("ONE_OR_MORE_OPERATIONS_FAILED")]))return"";if(Array.isArray(r)&&r.length>0){let t=r[0];if(typeof t=="string"&&t!=="ONE_OR_MORE_OPERATIONS_FAILED")try{let s=JSON.parse(t);if(Array.isArray(s)&&s.length>0){let n=s[0];if(_optionalChain([n, 'optionalAccess', _31 => _31.response, 'optionalAccess', _32 => _32.errorCode])){let f=n.response.errorCode;if(v[f])return y(v[f]);let _=[`errors.auth.${f}`,`errors.data.${f}`,`errors.system.${f}`,`errors.${f}`];for(let M of _){let k=y(M);if(k!==y("error.unknown"))return k}}if(_optionalChain([n, 'optionalAccess', _33 => _33.response, 'optionalAccess', _34 => _34.data]))return n.response.data}if(_optionalChain([s, 'optionalAccess', _35 => _35.response, 'optionalAccess', _36 => _36.message])){let n=s.response.message.toLowerCase();return n.includes("expired")?y("resetPassword.linkExpired","El enlace ha expirado"):n.includes("invalid")?y("resetPassword.invalidCode","C\xF3digo inv\xE1lido"):s.response.message}}catch (e4){return t.toLowerCase().includes("expired")?y("resetPassword.linkExpired","El enlace ha expirado"):t.toLowerCase().includes("invalid")?y("resetPassword.invalidCode","C\xF3digo inv\xE1lido"):t}}return y("error.transaction","Error en la operaci\xF3n")}if(i.length===1&&i[0]==="_error"){let r=e.errors._error;return Array.isArray(r)?r[0]:String(r)}return i.length===1&&i[0]==="_graphql"?y("errors.system.DATABASE_CONNECTION_ERROR"):`${y("errors.data.FIELD_ERROR")}: ${i.join(", ")}`}return I||E("error.unknown")},[T,I,E,y]),o=_react.useCallback.call(void 0, e=>e.errorCode&&Y[e.errorCode]?Y[e.errorCode]:"error",[]),m=_react.useCallback.call(void 0, async(e,i,r)=>{let t=await _crudifybrowser2.default.createItem(e,i,r);if(!t.success&&g&&d(t)){let s=u(t),n=o(t);c(s,n,{autoHideDuration:a})}else if(t.success){let s=_optionalChain([r, 'optionalAccess', _37 => _37.actionConfig]),n=_optionalChain([s, 'optionalAccess', _38 => _38.key])||"create",f=_optionalChain([s, 'optionalAccess', _39 => _39.moduleKey])||e;if(A(n,f)){let _=p(n,f,s);c(_,"success",{autoHideDuration:a})}}return t},[g,A,c,u,o,p,a,d]),l=_react.useCallback.call(void 0, async(e,i,r)=>{let t=await _crudifybrowser2.default.updateItem(e,i,r);if(!t.success&&g&&d(t)){let s=u(t),n=o(t);c(s,n,{autoHideDuration:a})}else if(t.success){let s=_optionalChain([r, 'optionalAccess', _40 => _40.actionConfig]),n=_optionalChain([s, 'optionalAccess', _41 => _41.key])||"update",f=_optionalChain([s, 'optionalAccess', _42 => _42.moduleKey])||e;if(A(n,f)){let _=p(n,f,s);c(_,"success",{autoHideDuration:a})}}return t},[g,A,c,u,o,p,a,d]),L=_react.useCallback.call(void 0, async(e,i,r)=>{let t=await _crudifybrowser2.default.deleteItem(e,i,r);if(!t.success&&g&&d(t)){let s=u(t),n=o(t);c(s,n,{autoHideDuration:a})}else if(t.success){let s=_optionalChain([r, 'optionalAccess', _43 => _43.actionConfig]),n=_optionalChain([s, 'optionalAccess', _44 => _44.key])||"delete",f=_optionalChain([s, 'optionalAccess', _45 => _45.moduleKey])||e;if(A(n,f)){let _=p(n,f,s);c(_,"success",{autoHideDuration:a})}}return t},[g,A,c,u,o,p,a,d]),P=_react.useCallback.call(void 0, async(e,i,r)=>{let t=await _crudifybrowser2.default.readItem(e,i,r);if(!t.success&&g&&d(t)){let s=u(t),n=o(t);c(s,n,{autoHideDuration:a})}return t},[g,c,u,o,a,d]),w=_react.useCallback.call(void 0, async(e,i,r)=>{let t=await _crudifybrowser2.default.readItems(e,i,r);if(!t.success&&g&&d(t)){let s=u(t),n=o(t);c(s,n,{autoHideDuration:a})}return t},[g,c,u,o,a,d]),V=_react.useCallback.call(void 0, async(e,i)=>{let r=await _crudifybrowser2.default.transaction(e,i),t=_optionalChain([i, 'optionalAccess', _46 => _46.skipNotifications])===!0;if(!t&&!r.success&&g&&d(r)){let s=u(r),n=o(r);c(s,n,{autoHideDuration:a})}else if(!t&&r.success){let s="transaction",n,f=null;if(_optionalChain([i, 'optionalAccess', _47 => _47.actionConfig])?(f=i.actionConfig,s=f.key,n=f.moduleKey):Array.isArray(e)&&e.length>0&&e[0].operation&&(s=e[0].operation,f=R.find(_=>_.key===s),f&&(n=f.moduleKey)),A(s,n)){let _=p(s,n,f);c(_,"success",{autoHideDuration:a})}}return r},[g,A,c,u,o,p,a,d,R]),x=_react.useCallback.call(void 0, (e,i)=>{if(!e.success&&g&&d(e)){let r=u(e),t=o(e);c(r,t,{autoHideDuration:a})}else e.success&&N&&i&&c(i,"success",{autoHideDuration:a});return e},[g,N,c,u,o,a,d,E]);return{createItem:m,updateItem:l,deleteItem:L,readItem:P,readItems:w,transaction:V,handleResponse:x,getErrorMessage:u,getErrorSeverity:o,shouldShowNotification:d}};exports.a = G; exports.b = ee; exports.c = oe; exports.d = le;
|
|
1
|
+
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } 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 _chunk2OSNNNIDjs = require('./chunk-2OSNNNID.js');var _react = require('react');var _crudifybrowser = require('@nocios/crudify-browser'); var _crudifybrowser2 = _interopRequireDefault(_crudifybrowser);var G=(S={})=>{let{autoFetch:c=!0,retryOnError:N=!1,maxRetries:g=3}=S,{isAuthenticated:T,isInitialized:I,sessionData:a,tokens:R}=_chunk2OSNNNIDjs.g.call(void 0, ),[E,d]=_react.useState.call(void 0, null),[y,O]=_react.useState.call(void 0, !1),[A,p]=_react.useState.call(void 0, null),u=_react.useRef.call(void 0, null),o=_react.useRef.call(void 0, !0),m=_react.useRef.call(void 0, 0),l=_react.useRef.call(void 0, 0),L=_react.useCallback.call(void 0, ()=>a&&(a.email||a["cognito:username"])||null,[a]),P=_react.useCallback.call(void 0, ()=>{d(null),p(null),O(!1),l.current=0},[]),w=_react.useCallback.call(void 0, async()=>{let x=L();if(!x){o.current&&(p("No user email available from session data"),O(!1));return}if(!I){o.current&&(p("Session not initialized"),O(!1));return}u.current&&u.current.abort();let e=new AbortController;u.current=e;let i=++m.current;try{o.current&&(O(!0),p(null));let r=await _crudifybrowser2.default.readItems("users",{filter:{email:x},pagination:{limit:1}});if(i===m.current&&o.current&&!e.signal.aborted){let t=null;if(r.success){if(Array.isArray(r.data)&&r.data.length>0)t=r.data[0];else if(_optionalChain([r, 'access', _2 => _2.data, 'optionalAccess', _3 => _3.response, 'optionalAccess', _4 => _4.data]))try{let s=r.data.response.data,n=typeof s=="string"?JSON.parse(s):s;n&&n.items&&Array.isArray(n.items)&&n.items.length>0&&(t=n.items[0])}catch (e2){}else if(r.data&&typeof r.data=="object")r.data.items&&Array.isArray(r.data.items)&&r.data.items.length>0&&(t=r.data.items[0]);else if(_optionalChain([r, 'access', _5 => _5.data, 'optionalAccess', _6 => _6.data, 'optionalAccess', _7 => _7.response, 'optionalAccess', _8 => _8.data]))try{let s=r.data.data.response.data,n=typeof s=="string"?JSON.parse(s):s;n&&n.items&&Array.isArray(n.items)&&n.items.length>0&&(t=n.items[0])}catch (e3){}}t?(d(t),p(null),l.current=0):(p("User profile not found in database"),d(null))}}catch(r){if(i===m.current&&o.current){let t=r;if(t.name==="AbortError")return;N&&l.current<g&&(_optionalChain([t, 'access', _9 => _9.message, 'optionalAccess', _10 => _10.includes, 'call', _11 => _11("Network Error")])||_optionalChain([t, 'access', _12 => _12.message, 'optionalAccess', _13 => _13.includes, 'call', _14 => _14("Failed to fetch")]))?(l.current++,setTimeout(()=>{o.current&&w()},1e3*l.current)):(p("Failed to load user profile from database"),d(null))}}finally{i===m.current&&o.current&&O(!1),u.current===e&&(u.current=null)}},[I,L,N,g]);return _react.useEffect.call(void 0, ()=>{c&&T&&I?w():T||P()},[c,T,I,w,P]),_react.useEffect.call(void 0, ()=>(o.current=!0,()=>{o.current=!1,u.current&&(u.current.abort(),u.current=null)}),[]),{user:{session:a,data:E},loading:y,error:A,refreshProfile:w,clearProfile:P}};var ee=()=>{let{isAuthenticated:S,isLoading:c,isInitialized:N,tokens:g,error:T,sessionData:I,login:a,logout:R,refreshTokens:E,clearError:d,getTokenInfo:y,isExpiringSoon:O,expiresIn:A,refreshExpiresIn:p}=_chunk2OSNNNIDjs.g.call(void 0, ),u=_react.useCallback.call(void 0, m=>{m?console.warn("useAuth.setToken() is deprecated. Use login() method instead for better security."):R()},[R]),o=_optionalChain([g, 'optionalAccess', _15 => _15.expiresAt])?new Date(g.expiresAt):null;return{isAuthenticated:S,loading:c,error:T,token:_optionalChain([g, 'optionalAccess', _16 => _16.accessToken])||null,user:I,tokenExpiration:o,setToken:u,logout:R,refreshToken:E,login:a,isExpiringSoon:O,expiresIn:A,refreshExpiresIn:p,getTokenInfo:y,clearError:d}};var oe=()=>{let{isInitialized:S,isLoading:c,error:N,isAuthenticated:g,login:T}=_chunk2OSNNNIDjs.g.call(void 0, ),I=_react.useCallback.call(void 0, ()=>S&&!c&&!N,[S,c,N]),a=_react.useCallback.call(void 0, async()=>new Promise((o,m)=>{let l=()=>{I()?o():N?m(new Error(N)):setTimeout(l,100)};l()}),[I,N]),R=_react.useCallback.call(void 0, async()=>{if(!I())throw new Error("System not ready. Check isInitialized, isLoading, and error states.")},[I]),E=_react.useCallback.call(void 0, async(o,m,l)=>(await R(),await _crudifybrowser2.default.readItems(o,m||{},l)),[R]),d=_react.useCallback.call(void 0, async(o,m,l)=>(await R(),await _crudifybrowser2.default.readItem(o,m,l)),[R]),y=_react.useCallback.call(void 0, async(o,m,l)=>(await R(),await _crudifybrowser2.default.createItem(o,m,l)),[R]),O=_react.useCallback.call(void 0, async(o,m,l)=>(await R(),await _crudifybrowser2.default.updateItem(o,m,l)),[R]),A=_react.useCallback.call(void 0, async(o,m,l)=>(await R(),await _crudifybrowser2.default.deleteItem(o,m,l)),[R]),p=_react.useCallback.call(void 0, async(o,m)=>(await R(),await _crudifybrowser2.default.transaction(o,m)),[R]),u=_react.useCallback.call(void 0, async(o,m)=>{try{let l=await T(o,m);return l.success?{success:!0,data:l.tokens}:{success:!1,errors:l.error||"Login failed"}}catch(l){return{success:!1,errors:l instanceof Error?l.message:"Login failed"}}},[T]);return{readItems:E,readItem:d,createItem:y,updateItem:O,deleteItem:A,transaction:p,login:u,isInitialized:S,isInitializing:c,initializationError:N,isReady:I,waitForReady:a}};var Y={INVALID_CREDENTIALS:"warning",UNAUTHORIZED:"warning",INVALID_API_KEY:"error",USER_NOT_FOUND:"warning",USER_NOT_ACTIVE:"warning",NO_PERMISSION:"warning",ITEM_NOT_FOUND:"info",NOT_FOUND:"info",IN_USE:"warning",FIELD_ERROR:"warning",BAD_REQUEST:"warning",INTERNAL_SERVER_ERROR:"error",DATABASE_CONNECTION_ERROR:"error",INVALID_CONFIGURATION:"error",UNKNOWN_OPERATION:"error",TOO_MANY_REQUESTS:"warning"},v={INVALID_CREDENTIALS:"errors.auth.INVALID_CREDENTIALS",UNAUTHORIZED:"errors.auth.UNAUTHORIZED",INVALID_API_KEY:"errors.auth.INVALID_API_KEY",USER_NOT_FOUND:"errors.auth.USER_NOT_FOUND",USER_NOT_ACTIVE:"errors.auth.USER_NOT_ACTIVE",NO_PERMISSION:"errors.auth.NO_PERMISSION",ITEM_NOT_FOUND:"errors.data.ITEM_NOT_FOUND",NOT_FOUND:"errors.data.NOT_FOUND",IN_USE:"errors.data.IN_USE",FIELD_ERROR:"errors.data.FIELD_ERROR",BAD_REQUEST:"errors.data.BAD_REQUEST",INTERNAL_SERVER_ERROR:"errors.system.INTERNAL_SERVER_ERROR",DATABASE_CONNECTION_ERROR:"errors.system.DATABASE_CONNECTION_ERROR",INVALID_CONFIGURATION:"errors.system.INVALID_CONFIGURATION",UNKNOWN_OPERATION:"errors.system.UNKNOWN_OPERATION",TOO_MANY_REQUESTS:"errors.system.TOO_MANY_REQUESTS"},le= exports.d =(S={})=>{let{showNotification:c}=_chunk2OSNNNIDjs.e.call(void 0, ),{showSuccessNotifications:N=!1,showErrorNotifications:g=!0,customErrorMessages:T={},defaultErrorMessage:I="Ha ocurrido un error inesperado",autoHideDuration:a=6e3,appStructure:R=[],translateFn:E=e=>e}=S,d=_react.useCallback.call(void 0, e=>!(!e.success&&e.errors&&(Object.keys(e.errors).some(r=>r!=="_error"&&r!=="_graphql"&&r!=="_transaction")||_optionalChain([e, 'access', _17 => _17.errors, 'access', _18 => _18._transaction, 'optionalAccess', _19 => _19.includes, 'call', _20 => _20("ONE_OR_MORE_OPERATIONS_FAILED")])||_optionalChain([e, 'access', _21 => _21.errors, 'access', _22 => _22._error, 'optionalAccess', _23 => _23.includes, 'call', _24 => _24("TOO_MANY_REQUESTS")]))||!e.success&&_optionalChain([e, 'access', _25 => _25.data, 'optionalAccess', _26 => _26.response, 'optionalAccess', _27 => _27.status])==="TOO_MANY_REQUESTS"),[]),y=_react.useCallback.call(void 0, (e,i)=>{let r=E(e);return r===e?i||E("error.unknown"):r},[E]),O=_react.useCallback.call(void 0, e=>["create","update","delete"].includes(e),[]),A=_react.useCallback.call(void 0, (e,i)=>N?O(e)&&i?!0:R.some(r=>r.key===e):!1,[N,R,O]),p=_react.useCallback.call(void 0, (e,i,r)=>{let t=_optionalChain([r, 'optionalAccess', _28 => _28.key])&&typeof r.key=="string"?r.key:e,s=`action.onSuccess.${t}`,n=y(s);if(n!==E("error.unknown")){if(O(t)&&i){let f=`action.${i}Singular`,_=y(f);if(_!==E("error.unknown"))return E(s,{item:_});{let M=`action.onSuccess.${t}WithoutItem`,k=y(M);return k!==E("error.unknown")?k:n}}return n}return E("success.transaction")},[y,E,O]),u=_react.useCallback.call(void 0, e=>{if(e.errorCode&&T[e.errorCode])return T[e.errorCode];if(e.errorCode&&v[e.errorCode])return y(v[e.errorCode]);if(e.errorCode){let i=[`errors.auth.${e.errorCode}`,`errors.data.${e.errorCode}`,`errors.system.${e.errorCode}`,`errors.${e.errorCode}`];for(let r of i){let t=y(r);if(t!==E("error.unknown"))return t}}if(typeof e.data=="string"&&e.data.startsWith("errors.")){let i=y(e.data);if(i!==E("error.unknown"))return i}if(e.errors&&Object.keys(e.errors).length>0){let i=Object.keys(e.errors);if(i.length===1&&i[0]==="_transaction"){let r=e.errors._transaction;if(_optionalChain([r, 'optionalAccess', _29 => _29.includes, 'call', _30 => _30("ONE_OR_MORE_OPERATIONS_FAILED")]))return"";if(Array.isArray(r)&&r.length>0){let t=r[0];if(typeof t=="string"&&t!=="ONE_OR_MORE_OPERATIONS_FAILED")try{let s=JSON.parse(t);if(Array.isArray(s)&&s.length>0){let n=s[0];if(_optionalChain([n, 'optionalAccess', _31 => _31.response, 'optionalAccess', _32 => _32.errorCode])){let f=n.response.errorCode;if(v[f])return y(v[f]);let _=[`errors.auth.${f}`,`errors.data.${f}`,`errors.system.${f}`,`errors.${f}`];for(let M of _){let k=y(M);if(k!==y("error.unknown"))return k}}if(_optionalChain([n, 'optionalAccess', _33 => _33.response, 'optionalAccess', _34 => _34.data]))return n.response.data}if(_optionalChain([s, 'optionalAccess', _35 => _35.response, 'optionalAccess', _36 => _36.message])){let n=s.response.message.toLowerCase();return n.includes("expired")?y("resetPassword.linkExpired","El enlace ha expirado"):n.includes("invalid")?y("resetPassword.invalidCode","C\xF3digo inv\xE1lido"):s.response.message}}catch (e4){return t.toLowerCase().includes("expired")?y("resetPassword.linkExpired","El enlace ha expirado"):t.toLowerCase().includes("invalid")?y("resetPassword.invalidCode","C\xF3digo inv\xE1lido"):t}}return y("error.transaction","Error en la operaci\xF3n")}if(i.length===1&&i[0]==="_error"){let r=e.errors._error;return Array.isArray(r)?r[0]:String(r)}return i.length===1&&i[0]==="_graphql"?y("errors.system.DATABASE_CONNECTION_ERROR"):`${y("errors.data.FIELD_ERROR")}: ${i.join(", ")}`}return I||E("error.unknown")},[T,I,E,y]),o=_react.useCallback.call(void 0, e=>e.errorCode&&Y[e.errorCode]?Y[e.errorCode]:"error",[]),m=_react.useCallback.call(void 0, async(e,i,r)=>{let t=await _crudifybrowser2.default.createItem(e,i,r);if(!t.success&&g&&d(t)){let s=u(t),n=o(t);c(s,n,{autoHideDuration:a})}else if(t.success){let s=_optionalChain([r, 'optionalAccess', _37 => _37.actionConfig]),n=_optionalChain([s, 'optionalAccess', _38 => _38.key])||"create",f=_optionalChain([s, 'optionalAccess', _39 => _39.moduleKey])||e;if(A(n,f)){let _=p(n,f,s);c(_,"success",{autoHideDuration:a})}}return t},[g,A,c,u,o,p,a,d]),l=_react.useCallback.call(void 0, async(e,i,r)=>{let t=await _crudifybrowser2.default.updateItem(e,i,r);if(!t.success&&g&&d(t)){let s=u(t),n=o(t);c(s,n,{autoHideDuration:a})}else if(t.success){let s=_optionalChain([r, 'optionalAccess', _40 => _40.actionConfig]),n=_optionalChain([s, 'optionalAccess', _41 => _41.key])||"update",f=_optionalChain([s, 'optionalAccess', _42 => _42.moduleKey])||e;if(A(n,f)){let _=p(n,f,s);c(_,"success",{autoHideDuration:a})}}return t},[g,A,c,u,o,p,a,d]),L=_react.useCallback.call(void 0, async(e,i,r)=>{let t=await _crudifybrowser2.default.deleteItem(e,i,r);if(!t.success&&g&&d(t)){let s=u(t),n=o(t);c(s,n,{autoHideDuration:a})}else if(t.success){let s=_optionalChain([r, 'optionalAccess', _43 => _43.actionConfig]),n=_optionalChain([s, 'optionalAccess', _44 => _44.key])||"delete",f=_optionalChain([s, 'optionalAccess', _45 => _45.moduleKey])||e;if(A(n,f)){let _=p(n,f,s);c(_,"success",{autoHideDuration:a})}}return t},[g,A,c,u,o,p,a,d]),P=_react.useCallback.call(void 0, async(e,i,r)=>{let t=await _crudifybrowser2.default.readItem(e,i,r);if(!t.success&&g&&d(t)){let s=u(t),n=o(t);c(s,n,{autoHideDuration:a})}return t},[g,c,u,o,a,d]),w=_react.useCallback.call(void 0, async(e,i,r)=>{let t=await _crudifybrowser2.default.readItems(e,i,r);if(!t.success&&g&&d(t)){let s=u(t),n=o(t);c(s,n,{autoHideDuration:a})}return t},[g,c,u,o,a,d]),V=_react.useCallback.call(void 0, async(e,i)=>{let r=await _crudifybrowser2.default.transaction(e,i),t=_optionalChain([i, 'optionalAccess', _46 => _46.skipNotifications])===!0;if(!t&&!r.success&&g&&d(r)){let s=u(r),n=o(r);c(s,n,{autoHideDuration:a})}else if(!t&&r.success){let s="transaction",n,f=null;if(_optionalChain([i, 'optionalAccess', _47 => _47.actionConfig])?(f=i.actionConfig,s=f.key,n=f.moduleKey):Array.isArray(e)&&e.length>0&&e[0].operation&&(s=e[0].operation,f=R.find(_=>_.key===s),f&&(n=f.moduleKey)),A(s,n)){let _=p(s,n,f);c(_,"success",{autoHideDuration:a})}}return r},[g,A,c,u,o,p,a,d,R]),x=_react.useCallback.call(void 0, (e,i)=>{if(!e.success&&g&&d(e)){let r=u(e),t=o(e);c(r,t,{autoHideDuration:a})}else e.success&&N&&i&&c(i,"success",{autoHideDuration:a});return e},[g,N,c,u,o,a,d,E]);return{createItem:m,updateItem:l,deleteItem:L,readItem:P,readItems:w,transaction:V,handleResponse:x,getErrorMessage:u,getErrorSeverity:o,shouldShowNotification:d}};exports.a = G; exports.b = ee; exports.c = oe; exports.d = le;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{e as $,g as D}from"./chunk-TKYA4Q4U.mjs";import{useState as K,useEffect as z,useCallback as j,useRef as F}from"react";import Q from"@nocios/crudify-browser";var G=(S={})=>{let{autoFetch:c=!0,retryOnError:N=!1,maxRetries:g=3}=S,{isAuthenticated:T,isInitialized:I,sessionData:a,tokens:R}=D(),[E,d]=K(null),[y,O]=K(!1),[A,p]=K(null),u=F(null),o=F(!0),m=F(0),l=F(0),L=j(()=>a&&(a.email||a["cognito:username"])||null,[a]),P=j(()=>{d(null),p(null),O(!1),l.current=0},[]),w=j(async()=>{let x=L();if(!x){o.current&&(p("No user email available from session data"),O(!1));return}if(!I){o.current&&(p("Session not initialized"),O(!1));return}u.current&&u.current.abort();let e=new AbortController;u.current=e;let i=++m.current;try{o.current&&(O(!0),p(null));let r=await Q.readItems("users",{filter:{email:x},pagination:{limit:1}});if(i===m.current&&o.current&&!e.signal.aborted){let t=null;if(r.success){if(Array.isArray(r.data)&&r.data.length>0)t=r.data[0];else if(r.data?.response?.data)try{let s=r.data.response.data,n=typeof s=="string"?JSON.parse(s):s;n&&n.items&&Array.isArray(n.items)&&n.items.length>0&&(t=n.items[0])}catch{}else if(r.data&&typeof r.data=="object")r.data.items&&Array.isArray(r.data.items)&&r.data.items.length>0&&(t=r.data.items[0]);else if(r.data?.data?.response?.data)try{let s=r.data.data.response.data,n=typeof s=="string"?JSON.parse(s):s;n&&n.items&&Array.isArray(n.items)&&n.items.length>0&&(t=n.items[0])}catch{}}t?(d(t),p(null),l.current=0):(p("User profile not found in database"),d(null))}}catch(r){if(i===m.current&&o.current){let t=r;if(t.name==="AbortError")return;N&&l.current<g&&(t.message?.includes("Network Error")||t.message?.includes("Failed to fetch"))?(l.current++,setTimeout(()=>{o.current&&w()},1e3*l.current)):(p("Failed to load user profile from database"),d(null))}}finally{i===m.current&&o.current&&O(!1),u.current===e&&(u.current=null)}},[I,L,N,g]);return z(()=>{c&&T&&I?w():T||P()},[c,T,I,w,P]),z(()=>(o.current=!0,()=>{o.current=!1,u.current&&(u.current.abort(),u.current=null)}),[]),{user:{session:a,data:E},loading:y,error:A,refreshProfile:w,clearProfile:P}};import{useCallback as W}from"react";var ee=()=>{let{isAuthenticated:S,isLoading:c,isInitialized:N,tokens:g,error:T,sessionData:I,login:a,logout:R,refreshTokens:E,clearError:d,getTokenInfo:y,isExpiringSoon:O,expiresIn:A,refreshExpiresIn:p}=D(),u=W(m=>{m?console.warn("useAuth.setToken() is deprecated. Use login() method instead for better security."):R()},[R]),o=g?.expiresAt?new Date(g.expiresAt):null;return{isAuthenticated:S,loading:c,error:T,token:g?.accessToken||null,user:I,tokenExpiration:o,setToken:u,logout:R,refreshToken:E,login:a,isExpiringSoon:O,expiresIn:A,refreshExpiresIn:p,getTokenInfo:y,clearError:d}};import{useCallback as h}from"react";import U from"@nocios/crudify-browser";var oe=()=>{let{isInitialized:S,isLoading:c,error:N,isAuthenticated:g,login:T}=D(),I=h(()=>S&&!c&&!N,[S,c,N]),a=h(async()=>new Promise((o,m)=>{let l=()=>{I()?o():N?m(new Error(N)):setTimeout(l,100)};l()}),[I,N]),R=h(async()=>{if(!I())throw new Error("System not ready. Check isInitialized, isLoading, and error states.")},[I]),E=h(async(o,m,l)=>(await R(),await U.readItems(o,m||{},l)),[R]),d=h(async(o,m,l)=>(await R(),await U.readItem(o,m,l)),[R]),y=h(async(o,m,l)=>(await R(),await U.createItem(o,m,l)),[R]),O=h(async(o,m,l)=>(await R(),await U.updateItem(o,m,l)),[R]),A=h(async(o,m,l)=>(await R(),await U.deleteItem(o,m,l)),[R]),p=h(async(o,m)=>(await R(),await U.transaction(o,m)),[R]),u=h(async(o,m)=>{try{let l=await T(o,m);return l.success?{success:!0,data:l.tokens}:{success:!1,errors:l.error||"Login failed"}}catch(l){return{success:!1,errors:l instanceof Error?l.message:"Login failed"}}},[T]);return{readItems:E,readItem:d,createItem:y,updateItem:O,deleteItem:A,transaction:p,login:u,isInitialized:S,isInitializing:c,initializationError:N,isReady:I,waitForReady:a}};import{useCallback as C}from"react";import b from"@nocios/crudify-browser";var Y={INVALID_CREDENTIALS:"warning",UNAUTHORIZED:"warning",INVALID_API_KEY:"error",USER_NOT_FOUND:"warning",USER_NOT_ACTIVE:"warning",NO_PERMISSION:"warning",ITEM_NOT_FOUND:"info",NOT_FOUND:"info",IN_USE:"warning",FIELD_ERROR:"warning",BAD_REQUEST:"warning",INTERNAL_SERVER_ERROR:"error",DATABASE_CONNECTION_ERROR:"error",INVALID_CONFIGURATION:"error",UNKNOWN_OPERATION:"error",TOO_MANY_REQUESTS:"warning"},v={INVALID_CREDENTIALS:"errors.auth.INVALID_CREDENTIALS",UNAUTHORIZED:"errors.auth.UNAUTHORIZED",INVALID_API_KEY:"errors.auth.INVALID_API_KEY",USER_NOT_FOUND:"errors.auth.USER_NOT_FOUND",USER_NOT_ACTIVE:"errors.auth.USER_NOT_ACTIVE",NO_PERMISSION:"errors.auth.NO_PERMISSION",ITEM_NOT_FOUND:"errors.data.ITEM_NOT_FOUND",NOT_FOUND:"errors.data.NOT_FOUND",IN_USE:"errors.data.IN_USE",FIELD_ERROR:"errors.data.FIELD_ERROR",BAD_REQUEST:"errors.data.BAD_REQUEST",INTERNAL_SERVER_ERROR:"errors.system.INTERNAL_SERVER_ERROR",DATABASE_CONNECTION_ERROR:"errors.system.DATABASE_CONNECTION_ERROR",INVALID_CONFIGURATION:"errors.system.INVALID_CONFIGURATION",UNKNOWN_OPERATION:"errors.system.UNKNOWN_OPERATION",TOO_MANY_REQUESTS:"errors.system.TOO_MANY_REQUESTS"},le=(S={})=>{let{showNotification:c}=$(),{showSuccessNotifications:N=!1,showErrorNotifications:g=!0,customErrorMessages:T={},defaultErrorMessage:I="Ha ocurrido un error inesperado",autoHideDuration:a=6e3,appStructure:R=[],translateFn:E=e=>e}=S,d=C(e=>!(!e.success&&e.errors&&(Object.keys(e.errors).some(r=>r!=="_error"&&r!=="_graphql"&&r!=="_transaction")||e.errors._transaction?.includes("ONE_OR_MORE_OPERATIONS_FAILED")||e.errors._error?.includes("TOO_MANY_REQUESTS"))||!e.success&&e.data?.response?.status==="TOO_MANY_REQUESTS"),[]),y=C((e,i)=>{let r=E(e);return r===e?i||E("error.unknown"):r},[E]),O=C(e=>["create","update","delete"].includes(e),[]),A=C((e,i)=>N?O(e)&&i?!0:R.some(r=>r.key===e):!1,[N,R,O]),p=C((e,i,r)=>{let t=r?.key&&typeof r.key=="string"?r.key:e,s=`action.onSuccess.${t}`,n=y(s);if(n!==E("error.unknown")){if(O(t)&&i){let f=`action.${i}Singular`,_=y(f);if(_!==E("error.unknown"))return E(s,{item:_});{let M=`action.onSuccess.${t}WithoutItem`,k=y(M);return k!==E("error.unknown")?k:n}}return n}return E("success.transaction")},[y,E,O]),u=C(e=>{if(e.errorCode&&T[e.errorCode])return T[e.errorCode];if(e.errorCode&&v[e.errorCode])return y(v[e.errorCode]);if(e.errorCode){let i=[`errors.auth.${e.errorCode}`,`errors.data.${e.errorCode}`,`errors.system.${e.errorCode}`,`errors.${e.errorCode}`];for(let r of i){let t=y(r);if(t!==E("error.unknown"))return t}}if(typeof e.data=="string"&&e.data.startsWith("errors.")){let i=y(e.data);if(i!==E("error.unknown"))return i}if(e.errors&&Object.keys(e.errors).length>0){let i=Object.keys(e.errors);if(i.length===1&&i[0]==="_transaction"){let r=e.errors._transaction;if(r?.includes("ONE_OR_MORE_OPERATIONS_FAILED"))return"";if(Array.isArray(r)&&r.length>0){let t=r[0];if(typeof t=="string"&&t!=="ONE_OR_MORE_OPERATIONS_FAILED")try{let s=JSON.parse(t);if(Array.isArray(s)&&s.length>0){let n=s[0];if(n?.response?.errorCode){let f=n.response.errorCode;if(v[f])return y(v[f]);let _=[`errors.auth.${f}`,`errors.data.${f}`,`errors.system.${f}`,`errors.${f}`];for(let M of _){let k=y(M);if(k!==y("error.unknown"))return k}}if(n?.response?.data)return n.response.data}if(s?.response?.message){let n=s.response.message.toLowerCase();return n.includes("expired")?y("resetPassword.linkExpired","El enlace ha expirado"):n.includes("invalid")?y("resetPassword.invalidCode","C\xF3digo inv\xE1lido"):s.response.message}}catch{return t.toLowerCase().includes("expired")?y("resetPassword.linkExpired","El enlace ha expirado"):t.toLowerCase().includes("invalid")?y("resetPassword.invalidCode","C\xF3digo inv\xE1lido"):t}}return y("error.transaction","Error en la operaci\xF3n")}if(i.length===1&&i[0]==="_error"){let r=e.errors._error;return Array.isArray(r)?r[0]:String(r)}return i.length===1&&i[0]==="_graphql"?y("errors.system.DATABASE_CONNECTION_ERROR"):`${y("errors.data.FIELD_ERROR")}: ${i.join(", ")}`}return I||E("error.unknown")},[T,I,E,y]),o=C(e=>e.errorCode&&Y[e.errorCode]?Y[e.errorCode]:"error",[]),m=C(async(e,i,r)=>{let t=await b.createItem(e,i,r);if(!t.success&&g&&d(t)){let s=u(t),n=o(t);c(s,n,{autoHideDuration:a})}else if(t.success){let s=r?.actionConfig,n=s?.key||"create",f=s?.moduleKey||e;if(A(n,f)){let _=p(n,f,s);c(_,"success",{autoHideDuration:a})}}return t},[g,A,c,u,o,p,a,d]),l=C(async(e,i,r)=>{let t=await b.updateItem(e,i,r);if(!t.success&&g&&d(t)){let s=u(t),n=o(t);c(s,n,{autoHideDuration:a})}else if(t.success){let s=r?.actionConfig,n=s?.key||"update",f=s?.moduleKey||e;if(A(n,f)){let _=p(n,f,s);c(_,"success",{autoHideDuration:a})}}return t},[g,A,c,u,o,p,a,d]),L=C(async(e,i,r)=>{let t=await b.deleteItem(e,i,r);if(!t.success&&g&&d(t)){let s=u(t),n=o(t);c(s,n,{autoHideDuration:a})}else if(t.success){let s=r?.actionConfig,n=s?.key||"delete",f=s?.moduleKey||e;if(A(n,f)){let _=p(n,f,s);c(_,"success",{autoHideDuration:a})}}return t},[g,A,c,u,o,p,a,d]),P=C(async(e,i,r)=>{let t=await b.readItem(e,i,r);if(!t.success&&g&&d(t)){let s=u(t),n=o(t);c(s,n,{autoHideDuration:a})}return t},[g,c,u,o,a,d]),w=C(async(e,i,r)=>{let t=await b.readItems(e,i,r);if(!t.success&&g&&d(t)){let s=u(t),n=o(t);c(s,n,{autoHideDuration:a})}return t},[g,c,u,o,a,d]),V=C(async(e,i)=>{let r=await b.transaction(e,i),t=i?.skipNotifications===!0;if(!t&&!r.success&&g&&d(r)){let s=u(r),n=o(r);c(s,n,{autoHideDuration:a})}else if(!t&&r.success){let s="transaction",n,f=null;if(i?.actionConfig?(f=i.actionConfig,s=f.key,n=f.moduleKey):Array.isArray(e)&&e.length>0&&e[0].operation&&(s=e[0].operation,f=R.find(_=>_.key===s),f&&(n=f.moduleKey)),A(s,n)){let _=p(s,n,f);c(_,"success",{autoHideDuration:a})}}return r},[g,A,c,u,o,p,a,d,R]),x=C((e,i)=>{if(!e.success&&g&&d(e)){let r=u(e),t=o(e);c(r,t,{autoHideDuration:a})}else e.success&&N&&i&&c(i,"success",{autoHideDuration:a});return e},[g,N,c,u,o,a,d,E]);return{createItem:m,updateItem:l,deleteItem:L,readItem:P,readItems:w,transaction:V,handleResponse:x,getErrorMessage:u,getErrorSeverity:o,shouldShowNotification:d}};export{G as a,ee as b,oe as c,le as d};
|
|
1
|
+
import{e as $,g as D}from"./chunk-VVXZWBHL.mjs";import{useState as K,useEffect as z,useCallback as j,useRef as F}from"react";import Q from"@nocios/crudify-browser";var G=(S={})=>{let{autoFetch:c=!0,retryOnError:N=!1,maxRetries:g=3}=S,{isAuthenticated:T,isInitialized:I,sessionData:a,tokens:R}=D(),[E,d]=K(null),[y,O]=K(!1),[A,p]=K(null),u=F(null),o=F(!0),m=F(0),l=F(0),L=j(()=>a&&(a.email||a["cognito:username"])||null,[a]),P=j(()=>{d(null),p(null),O(!1),l.current=0},[]),w=j(async()=>{let x=L();if(!x){o.current&&(p("No user email available from session data"),O(!1));return}if(!I){o.current&&(p("Session not initialized"),O(!1));return}u.current&&u.current.abort();let e=new AbortController;u.current=e;let i=++m.current;try{o.current&&(O(!0),p(null));let r=await Q.readItems("users",{filter:{email:x},pagination:{limit:1}});if(i===m.current&&o.current&&!e.signal.aborted){let t=null;if(r.success){if(Array.isArray(r.data)&&r.data.length>0)t=r.data[0];else if(r.data?.response?.data)try{let s=r.data.response.data,n=typeof s=="string"?JSON.parse(s):s;n&&n.items&&Array.isArray(n.items)&&n.items.length>0&&(t=n.items[0])}catch{}else if(r.data&&typeof r.data=="object")r.data.items&&Array.isArray(r.data.items)&&r.data.items.length>0&&(t=r.data.items[0]);else if(r.data?.data?.response?.data)try{let s=r.data.data.response.data,n=typeof s=="string"?JSON.parse(s):s;n&&n.items&&Array.isArray(n.items)&&n.items.length>0&&(t=n.items[0])}catch{}}t?(d(t),p(null),l.current=0):(p("User profile not found in database"),d(null))}}catch(r){if(i===m.current&&o.current){let t=r;if(t.name==="AbortError")return;N&&l.current<g&&(t.message?.includes("Network Error")||t.message?.includes("Failed to fetch"))?(l.current++,setTimeout(()=>{o.current&&w()},1e3*l.current)):(p("Failed to load user profile from database"),d(null))}}finally{i===m.current&&o.current&&O(!1),u.current===e&&(u.current=null)}},[I,L,N,g]);return z(()=>{c&&T&&I?w():T||P()},[c,T,I,w,P]),z(()=>(o.current=!0,()=>{o.current=!1,u.current&&(u.current.abort(),u.current=null)}),[]),{user:{session:a,data:E},loading:y,error:A,refreshProfile:w,clearProfile:P}};import{useCallback as W}from"react";var ee=()=>{let{isAuthenticated:S,isLoading:c,isInitialized:N,tokens:g,error:T,sessionData:I,login:a,logout:R,refreshTokens:E,clearError:d,getTokenInfo:y,isExpiringSoon:O,expiresIn:A,refreshExpiresIn:p}=D(),u=W(m=>{m?console.warn("useAuth.setToken() is deprecated. Use login() method instead for better security."):R()},[R]),o=g?.expiresAt?new Date(g.expiresAt):null;return{isAuthenticated:S,loading:c,error:T,token:g?.accessToken||null,user:I,tokenExpiration:o,setToken:u,logout:R,refreshToken:E,login:a,isExpiringSoon:O,expiresIn:A,refreshExpiresIn:p,getTokenInfo:y,clearError:d}};import{useCallback as h}from"react";import U from"@nocios/crudify-browser";var oe=()=>{let{isInitialized:S,isLoading:c,error:N,isAuthenticated:g,login:T}=D(),I=h(()=>S&&!c&&!N,[S,c,N]),a=h(async()=>new Promise((o,m)=>{let l=()=>{I()?o():N?m(new Error(N)):setTimeout(l,100)};l()}),[I,N]),R=h(async()=>{if(!I())throw new Error("System not ready. Check isInitialized, isLoading, and error states.")},[I]),E=h(async(o,m,l)=>(await R(),await U.readItems(o,m||{},l)),[R]),d=h(async(o,m,l)=>(await R(),await U.readItem(o,m,l)),[R]),y=h(async(o,m,l)=>(await R(),await U.createItem(o,m,l)),[R]),O=h(async(o,m,l)=>(await R(),await U.updateItem(o,m,l)),[R]),A=h(async(o,m,l)=>(await R(),await U.deleteItem(o,m,l)),[R]),p=h(async(o,m)=>(await R(),await U.transaction(o,m)),[R]),u=h(async(o,m)=>{try{let l=await T(o,m);return l.success?{success:!0,data:l.tokens}:{success:!1,errors:l.error||"Login failed"}}catch(l){return{success:!1,errors:l instanceof Error?l.message:"Login failed"}}},[T]);return{readItems:E,readItem:d,createItem:y,updateItem:O,deleteItem:A,transaction:p,login:u,isInitialized:S,isInitializing:c,initializationError:N,isReady:I,waitForReady:a}};import{useCallback as C}from"react";import b from"@nocios/crudify-browser";var Y={INVALID_CREDENTIALS:"warning",UNAUTHORIZED:"warning",INVALID_API_KEY:"error",USER_NOT_FOUND:"warning",USER_NOT_ACTIVE:"warning",NO_PERMISSION:"warning",ITEM_NOT_FOUND:"info",NOT_FOUND:"info",IN_USE:"warning",FIELD_ERROR:"warning",BAD_REQUEST:"warning",INTERNAL_SERVER_ERROR:"error",DATABASE_CONNECTION_ERROR:"error",INVALID_CONFIGURATION:"error",UNKNOWN_OPERATION:"error",TOO_MANY_REQUESTS:"warning"},v={INVALID_CREDENTIALS:"errors.auth.INVALID_CREDENTIALS",UNAUTHORIZED:"errors.auth.UNAUTHORIZED",INVALID_API_KEY:"errors.auth.INVALID_API_KEY",USER_NOT_FOUND:"errors.auth.USER_NOT_FOUND",USER_NOT_ACTIVE:"errors.auth.USER_NOT_ACTIVE",NO_PERMISSION:"errors.auth.NO_PERMISSION",ITEM_NOT_FOUND:"errors.data.ITEM_NOT_FOUND",NOT_FOUND:"errors.data.NOT_FOUND",IN_USE:"errors.data.IN_USE",FIELD_ERROR:"errors.data.FIELD_ERROR",BAD_REQUEST:"errors.data.BAD_REQUEST",INTERNAL_SERVER_ERROR:"errors.system.INTERNAL_SERVER_ERROR",DATABASE_CONNECTION_ERROR:"errors.system.DATABASE_CONNECTION_ERROR",INVALID_CONFIGURATION:"errors.system.INVALID_CONFIGURATION",UNKNOWN_OPERATION:"errors.system.UNKNOWN_OPERATION",TOO_MANY_REQUESTS:"errors.system.TOO_MANY_REQUESTS"},le=(S={})=>{let{showNotification:c}=$(),{showSuccessNotifications:N=!1,showErrorNotifications:g=!0,customErrorMessages:T={},defaultErrorMessage:I="Ha ocurrido un error inesperado",autoHideDuration:a=6e3,appStructure:R=[],translateFn:E=e=>e}=S,d=C(e=>!(!e.success&&e.errors&&(Object.keys(e.errors).some(r=>r!=="_error"&&r!=="_graphql"&&r!=="_transaction")||e.errors._transaction?.includes("ONE_OR_MORE_OPERATIONS_FAILED")||e.errors._error?.includes("TOO_MANY_REQUESTS"))||!e.success&&e.data?.response?.status==="TOO_MANY_REQUESTS"),[]),y=C((e,i)=>{let r=E(e);return r===e?i||E("error.unknown"):r},[E]),O=C(e=>["create","update","delete"].includes(e),[]),A=C((e,i)=>N?O(e)&&i?!0:R.some(r=>r.key===e):!1,[N,R,O]),p=C((e,i,r)=>{let t=r?.key&&typeof r.key=="string"?r.key:e,s=`action.onSuccess.${t}`,n=y(s);if(n!==E("error.unknown")){if(O(t)&&i){let f=`action.${i}Singular`,_=y(f);if(_!==E("error.unknown"))return E(s,{item:_});{let M=`action.onSuccess.${t}WithoutItem`,k=y(M);return k!==E("error.unknown")?k:n}}return n}return E("success.transaction")},[y,E,O]),u=C(e=>{if(e.errorCode&&T[e.errorCode])return T[e.errorCode];if(e.errorCode&&v[e.errorCode])return y(v[e.errorCode]);if(e.errorCode){let i=[`errors.auth.${e.errorCode}`,`errors.data.${e.errorCode}`,`errors.system.${e.errorCode}`,`errors.${e.errorCode}`];for(let r of i){let t=y(r);if(t!==E("error.unknown"))return t}}if(typeof e.data=="string"&&e.data.startsWith("errors.")){let i=y(e.data);if(i!==E("error.unknown"))return i}if(e.errors&&Object.keys(e.errors).length>0){let i=Object.keys(e.errors);if(i.length===1&&i[0]==="_transaction"){let r=e.errors._transaction;if(r?.includes("ONE_OR_MORE_OPERATIONS_FAILED"))return"";if(Array.isArray(r)&&r.length>0){let t=r[0];if(typeof t=="string"&&t!=="ONE_OR_MORE_OPERATIONS_FAILED")try{let s=JSON.parse(t);if(Array.isArray(s)&&s.length>0){let n=s[0];if(n?.response?.errorCode){let f=n.response.errorCode;if(v[f])return y(v[f]);let _=[`errors.auth.${f}`,`errors.data.${f}`,`errors.system.${f}`,`errors.${f}`];for(let M of _){let k=y(M);if(k!==y("error.unknown"))return k}}if(n?.response?.data)return n.response.data}if(s?.response?.message){let n=s.response.message.toLowerCase();return n.includes("expired")?y("resetPassword.linkExpired","El enlace ha expirado"):n.includes("invalid")?y("resetPassword.invalidCode","C\xF3digo inv\xE1lido"):s.response.message}}catch{return t.toLowerCase().includes("expired")?y("resetPassword.linkExpired","El enlace ha expirado"):t.toLowerCase().includes("invalid")?y("resetPassword.invalidCode","C\xF3digo inv\xE1lido"):t}}return y("error.transaction","Error en la operaci\xF3n")}if(i.length===1&&i[0]==="_error"){let r=e.errors._error;return Array.isArray(r)?r[0]:String(r)}return i.length===1&&i[0]==="_graphql"?y("errors.system.DATABASE_CONNECTION_ERROR"):`${y("errors.data.FIELD_ERROR")}: ${i.join(", ")}`}return I||E("error.unknown")},[T,I,E,y]),o=C(e=>e.errorCode&&Y[e.errorCode]?Y[e.errorCode]:"error",[]),m=C(async(e,i,r)=>{let t=await b.createItem(e,i,r);if(!t.success&&g&&d(t)){let s=u(t),n=o(t);c(s,n,{autoHideDuration:a})}else if(t.success){let s=r?.actionConfig,n=s?.key||"create",f=s?.moduleKey||e;if(A(n,f)){let _=p(n,f,s);c(_,"success",{autoHideDuration:a})}}return t},[g,A,c,u,o,p,a,d]),l=C(async(e,i,r)=>{let t=await b.updateItem(e,i,r);if(!t.success&&g&&d(t)){let s=u(t),n=o(t);c(s,n,{autoHideDuration:a})}else if(t.success){let s=r?.actionConfig,n=s?.key||"update",f=s?.moduleKey||e;if(A(n,f)){let _=p(n,f,s);c(_,"success",{autoHideDuration:a})}}return t},[g,A,c,u,o,p,a,d]),L=C(async(e,i,r)=>{let t=await b.deleteItem(e,i,r);if(!t.success&&g&&d(t)){let s=u(t),n=o(t);c(s,n,{autoHideDuration:a})}else if(t.success){let s=r?.actionConfig,n=s?.key||"delete",f=s?.moduleKey||e;if(A(n,f)){let _=p(n,f,s);c(_,"success",{autoHideDuration:a})}}return t},[g,A,c,u,o,p,a,d]),P=C(async(e,i,r)=>{let t=await b.readItem(e,i,r);if(!t.success&&g&&d(t)){let s=u(t),n=o(t);c(s,n,{autoHideDuration:a})}return t},[g,c,u,o,a,d]),w=C(async(e,i,r)=>{let t=await b.readItems(e,i,r);if(!t.success&&g&&d(t)){let s=u(t),n=o(t);c(s,n,{autoHideDuration:a})}return t},[g,c,u,o,a,d]),V=C(async(e,i)=>{let r=await b.transaction(e,i),t=i?.skipNotifications===!0;if(!t&&!r.success&&g&&d(r)){let s=u(r),n=o(r);c(s,n,{autoHideDuration:a})}else if(!t&&r.success){let s="transaction",n,f=null;if(i?.actionConfig?(f=i.actionConfig,s=f.key,n=f.moduleKey):Array.isArray(e)&&e.length>0&&e[0].operation&&(s=e[0].operation,f=R.find(_=>_.key===s),f&&(n=f.moduleKey)),A(s,n)){let _=p(s,n,f);c(_,"success",{autoHideDuration:a})}}return r},[g,A,c,u,o,p,a,d,R]),x=C((e,i)=>{if(!e.success&&g&&d(e)){let r=u(e),t=o(e);c(r,t,{autoHideDuration:a})}else e.success&&N&&i&&c(i,"success",{autoHideDuration:a});return e},[g,N,c,u,o,a,d,E]);return{createItem:m,updateItem:l,deleteItem:L,readItem:P,readItems:w,transaction:V,handleResponse:x,getErrorMessage:u,getErrorSeverity:o,shouldShowNotification:d}};export{G as a,ee as b,oe as c,le as d};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{e as Qe,g as Q,j as Ze}from"./chunk-TKYA4Q4U.mjs";import{g as z}from"./chunk-BJ6PIVZR.mjs";import{a as Je,e as Xe}from"./chunk-YS3C7YG5.mjs";import{Box as kr,Typography as Lr}from"@mui/material";import{createContext as $o,useContext as Ho,useMemo as oo}from"react";import{useState as Fe,useEffect as Mo}from"react";var eo=(e,t)=>{let[s,a]=Fe({}),[m,n]=Fe(!1),[i,p]=Fe(null);return Mo(()=>{if(console.log("\u{1F527} [I18nProvider] Hybrid translation loading:",{hasProvidedTranslations:!!t&&Object.keys(t).length>0,hasUrl:!!e,providedKeys:t?Object.keys(t).length:0}),t&&Object.keys(t).length>0){console.log("\u2705 [I18nProvider] Using provided translations (highest priority)"),a(t),n(!1),p(null);return}if(!e){console.log("\u26A0\uFE0F [I18nProvider] No translations provided, using empty object (keys will show as-is)"),a({}),n(!1),p(null);return}console.log("\u{1F310} [I18nProvider] Loading translations from URL:",e);let l=!1;return n(!0),p(null),fetch(e).then(y=>{if(!y.ok)throw new Error(`Failed to load translations: ${y.status}`);return y.json()}).then(y=>{l||(console.log("\u2705 [I18nProvider] Translations loaded successfully from URL:",{url:e,keysLoaded:Object.keys(y).length}),a(y),n(!1))}).catch(y=>{l||(console.error("\u274C [I18nProvider] Failed to load translations from URL:",e,y),p(y.message),console.log("\u{1F504} [I18nProvider] Falling back to empty translations (keys will show as-is)"),a({}),n(!1))}),()=>{l=!0}},[e,t]),{translations:s,loading:m,error:i}};import{jsx as ro}from"react/jsx-runtime";var to=$o(null),Ko=(e,t)=>e&&e[t]?e[t]:t.split(".").reduce((s,a)=>s&&typeof s=="object"?s[a]:void 0,e),no=({children:e,translations:t,translationsUrl:s,language:a="en"})=>{let{translations:m,loading:n}=eo(s,t),i=oo(()=>(l,y)=>{let c=Ko(m,l);return c==null&&(console.log(`\u{1F50D} [I18nProvider] Translation not found for key: "${l}" - showing key as-is`),c=l),y&&typeof c=="string"&&Object.entries(y).forEach(([x,d])=>{c=c.replace(new RegExp(`{{${x}}}`,"g"),d)}),typeof c=="string"?c:l},[m]),p=oo(()=>({t:i,language:a}),[i,a]);return n?ro("div",{children:"Loading translations..."}):ro(to.Provider,{value:p,children:e})},U=()=>{let e=Ho(to);if(!e)throw new Error("useTranslation must be used within I18nProvider");return e};import{createContext as jo,useContext as qo,useEffect as Go,useState as ve}from"react";import fe from"@nocios/crudify-browser";import{jsx as Yo}from"react/jsx-runtime";var io=jo(void 0),so=({config:e,children:t})=>{let[s,a]=ve(!0),[m,n]=ve(null),[i,p]=ve(!1),[l,y]=ve("");console.log("\u{1F50D} CrudifyProvider - Received config:",e),Go(()=>{if(console.log("\u{1F50D} CrudifyProvider - useEffect - config.publicApiKey:",e.publicApiKey),console.log("\u{1F50D} CrudifyProvider - useEffect - full config:",e),!e.publicApiKey){console.log("\u274C CrudifyProvider - No publicApiKey provided, setting error"),n("No publicApiKey provided"),a(!1),p(!1);return}console.log("\u2705 CrudifyProvider - publicApiKey found, proceeding with initialization");let x=`${e.publicApiKey}-${e.env}`;if(x===l&&i){a(!1);return}(async()=>{a(!0),n(null),p(!1);try{if(fe.config(e.env||"prod"),await fe.init(e.publicApiKey,"none"),typeof fe.transaction=="function"&&typeof fe.login=="function")p(!0),y(x);else throw new Error("Crudify methods not properly initialized")}catch(o){let r=o instanceof Error?o.message:"Failed to initialize Crudify";n(r),p(!1)}finally{a(!1)}})()},[e.publicApiKey,e.env,l,i]);let c={crudify:i?fe:null,isLoading:s,error:m,isInitialized:i};return Yo(io.Provider,{value:c,children:t})},q=()=>{let e=qo(io);if(e===void 0)throw new Error("useCrudify must be used within a CrudifyProvider");return e};import{createContext as Jo,useContext as Xo,useReducer as Qo,useEffect as ao}from"react";import{jsx as er}from"react/jsx-runtime";var lo={currentScreen:"login",searchParams:{},formData:{username:"",password:"",email:"",code:"",newPassword:"",confirmPassword:""},loading:!1,errors:{global:[]},emailSent:!1,codeAlreadyExists:!1,codeValidated:!1,fromCodeVerification:!1,config:{}};function Zo(e,t){switch(t.type){case"SET_SCREEN":let s={...e,currentScreen:t.payload.screen,searchParams:t.payload.params||e.searchParams,errors:{global:[]}},a=new URLSearchParams(s.searchParams),m=a.toString()?`?${a.toString()}`:window.location.pathname;try{window.history.replaceState({},"",m)}catch{}return s;case"SET_SEARCH_PARAMS":return{...e,searchParams:t.payload};case"UPDATE_FORM_DATA":return{...e,formData:{...e.formData,...t.payload},errors:{...e.errors,...Object.keys(t.payload).reduce((n,i)=>({...n,[i]:void 0}),{})}};case"SET_LOADING":return{...e,loading:t.payload};case"SET_ERRORS":return{...e,errors:{...e.errors,...t.payload}};case"CLEAR_ERRORS":return{...e,errors:{global:[]}};case"SET_EMAIL_SENT":return{...e,emailSent:t.payload};case"SET_CODE_ALREADY_EXISTS":return{...e,codeAlreadyExists:t.payload};case"SET_CODE_VALIDATED":return{...e,codeValidated:t.payload};case"SET_FROM_CODE_VERIFICATION":return{...e,fromCodeVerification:t.payload};case"RESET_FORM":return{...e,formData:lo.formData,errors:{global:[]},loading:!1,emailSent:!1,codeAlreadyExists:!1,codeValidated:!1,fromCodeVerification:!1};case"INIT_CONFIG":return{...e,config:t.payload};default:return e}}var co=Jo(void 0),uo=({children:e,initialScreen:t="login",config:s,autoReadFromCookies:a=!0})=>{let[m,n]=Qo(Zo,{...lo,currentScreen:t});ao(()=>{n({type:"INIT_CONFIG",payload:(()=>{let o={};if(a)try{let r=Je("logo");if(r){let u=decodeURIComponent(r);u.startsWith("http")&&(o.logo=u)}}catch(r){console.error("Error reading configuration from cookies:",r)}return{publicApiKey:s?.publicApiKey,env:s?.env,appName:s?.appName,logo:s?.logo||o.logo,loginActions:s?.loginActions}})()})},[s,a]),ao(()=>{let d=new URLSearchParams(window.location.search),o={};d.forEach((r,u)=>{o[u]=r}),Object.keys(o).length>0&&n({type:"SET_SEARCH_PARAMS",payload:o}),t==="checkCode"&&o.email&&n({type:"UPDATE_FORM_DATA",payload:{email:o.email,code:o.code||""}}),t==="resetPassword"&&o.link&&n({type:"SET_SEARCH_PARAMS",payload:o})},[t]);let x={state:m,dispatch:n,setScreen:(d,o)=>{n({type:"SET_SCREEN",payload:{screen:d,params:o}})},updateFormData:d=>{n({type:"UPDATE_FORM_DATA",payload:d})},setFieldError:(d,o)=>{n({type:"SET_ERRORS",payload:{[d]:o}})},clearErrors:()=>{n({type:"CLEAR_ERRORS"})},setLoading:d=>{n({type:"SET_LOADING",payload:d})}};return er(co.Provider,{value:x,children:e})},Te=()=>{let e=Xo(co);if(e===void 0)throw new Error("useLoginState must be used within a LoginStateProvider");return e};import{useEffect as or,useRef as rr}from"react";import{Typography as De,TextField as fo,Button as tr,Box as me,CircularProgress as nr,Alert as ir,Link as mo}from"@mui/material";import{Fragment as ar,jsx as M,jsxs as pe}from"react/jsx-runtime";var sr=({onScreenChange:e,onExternalNavigate:t,onLoginSuccess:s,onError:a,redirectUrl:m="/"})=>{let{crudify:n}=q(),{state:i,updateFormData:p,setFieldError:l,clearErrors:y,setLoading:c}=Te(),{login:x}=Q(),d=U(),{t:o}=d,r=d.i18n,u=rr(null),C=Xe(o,{currentLanguage:r?.language,enableDebug:!1}),P=()=>{if(i.searchParams.redirect)try{let g=decodeURIComponent(i.searchParams.redirect);if(g.startsWith("/")&&!g.startsWith("//"))return g}catch{}return m||"/"};or(()=>{let g=setTimeout(()=>{u.current&&u.current.focus()},100);return()=>clearTimeout(g)},[]);let f=g=>{console.log("\u{1F50D} [LoginForm] Translating parsed error:",g);let S=C.translateError({code:g.code,message:g.message,field:g.field});return console.log("\u{1F50D} [LoginForm] Translation result:",S),S},h=async()=>{if(!i.loading){if(!i.formData.username.trim()){l("username",o("login.usernameRequired"));return}if(!i.formData.password.trim()){l("password",o("login.passwordRequired"));return}y(),c(!0);try{let g=await x(i.formData.username,i.formData.password);if(c(!1),g.success){console.log("\u{1F510} LoginForm - Login successful via SessionProvider, calling onLoginSuccess");let S=P();s&&s(g.data,S)}else{let S=g.rawResponse||g;w(S)}}catch(g){c(!1);let J=z(g).map(f);l("global",J),a&&a(J.join(", "))}}},w=g=>{z(g).forEach(J=>{if(J.field)l(J.field,f(J));else{let de=i.errors.global||[];l("global",[...de,f(J)])}})};return pe(ar,{children:[pe(me,{component:"form",noValidate:!0,onSubmit:g=>{g.preventDefault(),h()},onKeyDown:g=>{g.key==="Enter"&&!i.loading&&(g.preventDefault(),h())},sx:{width:"100%",display:"flex",flexDirection:"column",gap:2},children:[pe(me,{sx:{mb:1},children:[M(De,{variant:"body2",component:"label",htmlFor:"email",sx:{display:"block",fontWeight:500,color:"grey.700",mb:.5},children:o("login.usernameOrEmailLabel")}),M(fo,{fullWidth:!0,id:"email",name:"email",type:"email",value:i.formData.username,disabled:i.loading,onChange:g=>p({username:g.target.value}),error:!!i.errors.username,helperText:i.errors.username,autoComplete:"email",placeholder:o("login.usernameOrEmailPlaceholder"),inputRef:u,required:!0})]}),pe(me,{sx:{mb:1},children:[M(De,{variant:"body2",component:"label",htmlFor:"password",sx:{display:"block",fontWeight:500,color:"grey.700",mb:.5},children:o("login.passwordLabel")}),M(fo,{fullWidth:!0,id:"password",name:"password",type:"password",value:i.formData.password,disabled:i.loading,onChange:g=>p({password:g.target.value}),error:!!i.errors.password,helperText:i.errors.password,autoComplete:"current-password",placeholder:o("login.passwordPlaceholder"),required:!0})]}),i.config.loginActions?.includes("forgotPassword")&&M(me,{sx:{display:"flex",justifyContent:"flex-end",alignItems:"center"},children:M(mo,{sx:{cursor:"pointer"},onClick:()=>{e?.("forgotPassword",i.searchParams)},variant:"body2",color:"secondary",children:o("login.forgotPasswordLink")})}),M(tr,{disabled:i.loading,type:"submit",fullWidth:!0,variant:"contained",color:"primary",sx:{mt:1,mb:2},children:i.loading?M(nr,{size:20}):o("login.loginButton")})]}),M(me,{children:i.errors.global&&i.errors.global.length>0&&i.errors.global.map((g,S)=>M(ir,{variant:"filled",sx:{mt:2},severity:"error",children:M("div",{children:g})},S))}),i.config.loginActions?.includes("createUser")&&pe(De,{variant:"body2",align:"center",sx:{color:"text.secondary",mt:3},children:[o("login.noAccountPrompt")," ",M(mo,{sx:{cursor:"pointer"},onClick:()=>{let S=`/public/users/create${Object.keys(i.searchParams).length>0?`?${new URLSearchParams(i.searchParams).toString()}`:""}`;t?.(S)},fontWeight:"medium",color:"secondary",children:o("login.signUpLink")})]})]})},po=sr;import{useState as ie}from"react";import{Typography as se,TextField as lr,Button as go,Box as Z,CircularProgress as cr,Alert as dr,Link as _e}from"@mui/material";import{Fragment as yo,jsx as B,jsxs as te}from"react/jsx-runtime";var ur=({onScreenChange:e,onError:t})=>{let{crudify:s}=q(),[a,m]=ie(""),[n,i]=ie(!1),[p,l]=ie([]),[y,c]=ie(null),[x,d]=ie(!1),[o,r]=ie(!1),{t:u}=U(),C=v=>{let E=[`errors.auth.${v.code}`,`errors.data.${v.code}`,`errors.system.${v.code}`,`errors.${v.code}`,`forgotPassword.${v.code.toLowerCase()}`];for(let g of E){let S=u(g);if(S!==g)return S}return v.message||u("error.unknown")},P=v=>/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(v),f=async()=>{if(!(n||!s)){if(l([]),c(null),!a){c(u("forgotPassword.emailRequired"));return}if(!P(a)){c(u("forgotPassword.invalidEmail"));return}i(!0);try{let v=[{operation:"requestPasswordReset",data:{email:a}}],E=await s.transaction(v);if(E.success)E.data&&E.data.existingCodeValid?r(!0):d(!0);else{let S=z(E).map(C);l(S)}}catch(v){let g=z(v).map(C);l(g),t&&t(g.join(", "))}finally{i(!1)}}},h=()=>{e?.("login")},w=()=>{if(x||o){e?.("checkCode",{email:a});return}if(!a){c(u("forgotPassword.emailRequired"));return}if(!P(a)){c(u("forgotPassword.invalidEmail"));return}e?.("checkCode",{email:a})};return x||o?B(yo,{children:te(Z,{sx:{width:"100%",display:"flex",flexDirection:"column",gap:2,textAlign:"center"},children:[te(Z,{sx:{mb:2},children:[B(se,{variant:"h5",component:"h1",sx:{mb:1,fontWeight:600},children:u(o?"forgotPassword.codeAlreadyExistsMessage":"forgotPassword.emailSentMessage")}),B(se,{variant:"body2",sx:{color:o?"success.main":"grey.600"},children:u("forgotPassword.checkEmailInstructions")})]}),B(go,{type:"button",onClick:w,fullWidth:!0,variant:"contained",color:"primary",sx:{mt:2,mb:2},children:u("forgotPassword.enterCodeLink")}),B(Z,{sx:{display:"flex",justifyContent:"center",alignItems:"center"},children:B(_e,{sx:{cursor:"pointer"},onClick:h,variant:"body2",color:"secondary",children:u("common.back")})})]})}):te(yo,{children:[te(Z,{component:"form",noValidate:!0,sx:{width:"100%",display:"flex",flexDirection:"column",gap:2},children:[te(Z,{sx:{mb:2},children:[B(se,{variant:"h5",component:"h1",sx:{mb:1,fontWeight:600},children:u("forgotPassword.title")}),B(se,{variant:"body2",sx:{color:"grey.600"},children:u("forgotPassword.instructions")})]}),te(Z,{sx:{mb:1},children:[B(se,{variant:"body2",component:"label",htmlFor:"email",sx:{display:"block",fontWeight:500,color:"grey.700",mb:.5},children:u("forgotPassword.emailLabel")}),B(lr,{fullWidth:!0,id:"email",name:"email",type:"email",value:a,disabled:n,onChange:v=>m(v.target.value),error:!!y,helperText:y,autoComplete:"email",placeholder:u("forgotPassword.emailPlaceholder"),required:!0})]}),B(go,{disabled:n,type:"button",onClick:f,fullWidth:!0,variant:"contained",color:"primary",sx:{mt:2,mb:2},children:n?B(cr,{size:20}):u("forgotPassword.sendCodeButton")}),te(Z,{sx:{display:"flex",justifyContent:"center",alignItems:"center",gap:2},children:[B(_e,{sx:{cursor:"pointer"},onClick:h,variant:"body2",color:"secondary",children:u("common.back")}),B(se,{variant:"body2",sx:{color:"grey.400"},children:"\u2022"}),B(_e,{sx:{cursor:"pointer"},onClick:w,variant:"body2",color:"secondary",children:u("login.alreadyHaveCodeLink")})]})]}),B(Z,{children:p.length>0&&p.map((v,E)=>B(dr,{variant:"filled",sx:{mt:2},severity:"error",children:v},E))})]})},xo=ur;import{useState as V,useEffect as ho}from"react";import{Typography as Ee,TextField as bo,Button as fr,Box as ee,CircularProgress as wo,Alert as Co,Link as mr}from"@mui/material";import{Fragment as gr,jsx as F,jsxs as ge}from"react/jsx-runtime";var pr=({onScreenChange:e,onError:t,searchParams:s,onResetSuccess:a})=>{let{crudify:m}=q(),[n,i]=V(""),[p,l]=V(""),[y,c]=V(!1),[x,d]=V([]),[o,r]=V(null),[u,C]=V(null),[P,f]=V(""),[h,w]=V(""),[v,E]=V(!1),[g,S]=V(!0),[J,de]=V(!1),[we,Be]=V(null),[No,Ye]=V(!1),{t:I}=U(),Ce=T=>{let k=[`errors.auth.${T.code}`,`errors.data.${T.code}`,`errors.system.${T.code}`,`errors.${T.code}`,`resetPassword.${T.code.toLowerCase()}`];for(let O of k){let N=I(O);if(N!==O)return N}return T.message||I("error.unknown")},Pe=T=>s?s instanceof URLSearchParams?s.get(T):s[T]||null:null;ho(()=>{if(s){if(s){let T=Pe("fromCodeVerification"),k=Pe("email"),O=Pe("code");if(T==="true"&&k&&O){f(k),w(O),E(!0),de(!0),S(!1);return}let N=Pe("link");if(N)try{let $=decodeURIComponent(N),[H,ue]=$.split("/");if(H&&ue&&H.length===6){w(H),f(ue),E(!1),Be({email:ue,code:H});return}}catch{}if(k&&O){f(k),w(O),E(!1),Be({email:k,code:O});return}}d([I("resetPassword.invalidCode")]),S(!1),setTimeout(()=>e?.("forgotPassword"),3e3)}},[s,m,I,e]),ho(()=>{m&&we&&!No&&(Ye(!0),(async(k,O)=>{try{let N=[{operation:"validatePasswordResetCode",data:{email:k,codePassword:O}}],$=await m.transaction(N);if($.data&&Array.isArray($.data)){let H=$.data[0];if(H&&H.response&&H.response.status==="OK"){de(!0);return}}if($.success)de(!0);else{let ue=z($).map(Ce);d(ue),setTimeout(()=>e?.("forgotPassword"),3e3)}}catch(N){let H=z(N).map(Ce);d(H),setTimeout(()=>e?.("forgotPassword"),3e3)}finally{S(!1),Be(null),Ye(!1)}})(we.email,we.code))},[m,we,I,e]);let Vo=T=>T.length<8?I("resetPassword.passwordTooShort"):null,Wo=async()=>{if(y||!m)return;d([]),r(null),C(null);let T=!1;if(!n)r(I("resetPassword.newPasswordRequired")),T=!0;else{let k=Vo(n);k&&(r(k),T=!0)}if(p?n!==p&&(C(I("resetPassword.passwordsDoNotMatch")),T=!0):(C(I("resetPassword.confirmPasswordRequired")),T=!0),!T){c(!0);try{let k=[{operation:"validateAndResetPassword",data:{email:P,codePassword:h,newPassword:n}}],O=await m.transaction(k);if(O.success)d([]),setTimeout(()=>{a?.()},1e3);else{let $=z(O).map(Ce);d($)}}catch(k){let N=z(k).map(Ce);d(N),t&&t(N.join(", "))}c(!1)}},Uo=()=>{v?e?.("checkCode",{email:P}):e?.("forgotPassword")};return g?F(ee,{sx:{display:"flex",justifyContent:"center",alignItems:"center",minHeight:"300px"},children:F(wo,{})}):J?ge(gr,{children:[ge(ee,{component:"form",noValidate:!0,sx:{width:"100%",display:"flex",flexDirection:"column",gap:2},children:[ge(ee,{sx:{mb:2},children:[F(Ee,{variant:"h5",component:"h1",sx:{mb:1,fontWeight:600},children:I("resetPassword.title")}),F(Ee,{variant:"body2",sx:{color:"grey.600"},children:I("resetPassword.instructions")})]}),ge(ee,{sx:{mb:1},children:[F(Ee,{variant:"body2",component:"label",htmlFor:"newPassword",sx:{display:"block",fontWeight:500,color:"grey.700",mb:.5},children:I("resetPassword.newPasswordLabel")}),F(bo,{fullWidth:!0,id:"newPassword",name:"newPassword",type:"password",value:n,disabled:y,onChange:T=>i(T.target.value),error:!!o,helperText:o,autoComplete:"new-password",placeholder:I("resetPassword.newPasswordPlaceholder"),required:!0})]}),ge(ee,{sx:{mb:1},children:[F(Ee,{variant:"body2",component:"label",htmlFor:"confirmPassword",sx:{display:"block",fontWeight:500,color:"grey.700",mb:.5},children:I("resetPassword.confirmPasswordLabel")}),F(bo,{fullWidth:!0,id:"confirmPassword",name:"confirmPassword",type:"password",value:p,disabled:y,onChange:T=>l(T.target.value),error:!!u,helperText:u,autoComplete:"new-password",placeholder:I("resetPassword.confirmPasswordPlaceholder"),required:!0})]}),F(fr,{disabled:y,type:"button",onClick:Wo,fullWidth:!0,variant:"contained",color:"primary",sx:{mt:2,mb:2},children:y?F(wo,{size:20}):I("resetPassword.resetPasswordButton")}),F(ee,{sx:{display:"flex",justifyContent:"center",alignItems:"center"},children:F(mr,{sx:{cursor:"pointer"},onClick:Uo,variant:"body2",color:"secondary",children:I("common.back")})})]}),F(ee,{children:x.length>0&&x.map((T,k)=>F(Co,{variant:"filled",sx:{mt:2},severity:"error",children:T},k))})]}):F(ee,{children:x.length>0&&x.map((T,k)=>F(Co,{variant:"filled",sx:{mt:2},severity:"error",children:T},k))})},Po=pr;import{useState as ye,useEffect as yr}from"react";import{Typography as Oe,TextField as xr,Button as hr,Box as xe,CircularProgress as br,Alert as wr,Link as Cr}from"@mui/material";import{Fragment as vr,jsx as G,jsxs as Se}from"react/jsx-runtime";var Pr=({onScreenChange:e,onError:t,searchParams:s})=>{let{crudify:a}=q(),[m,n]=ye(""),[i,p]=ye(!1),[l,y]=ye([]),[c,x]=ye(null),[d,o]=ye(""),{t:r}=U(),u=w=>s?s instanceof URLSearchParams?s.get(w):s[w]||null:null,C=w=>{let v=[`errors.auth.${w.code}`,`errors.data.${w.code}`,`errors.system.${w.code}`,`errors.${w.code}`,`checkCode.${w.code.toLowerCase()}`];for(let E of v){let g=r(E);if(g!==E)return g}return w.message||r("error.unknown")};yr(()=>{let w=u("email");w?o(w):e?.("forgotPassword")},[s,e]);let P=async()=>{if(!(i||!a)){if(y([]),x(null),!m){x(r("checkCode.codeRequired"));return}if(m.length!==6){x(r("checkCode.codeRequired"));return}p(!0);try{let w=[{operation:"validatePasswordResetCode",data:{email:d,codePassword:m}}],v=await a.transaction(w);if(v.success)e?.("resetPassword",{email:d,code:m,fromCodeVerification:"true"});else{let g=z(v).map(C);y(g),p(!1)}}catch(w){let E=z(w).map(C);y(E),p(!1),t&&t(E.join(", "))}}},f=()=>{e?.("forgotPassword")},h=w=>{let v=w.target.value.replace(/\D/g,"").slice(0,6);n(v)};return Se(vr,{children:[Se(xe,{component:"form",noValidate:!0,sx:{width:"100%",display:"flex",flexDirection:"column",gap:2},children:[Se(xe,{sx:{mb:2},children:[G(Oe,{variant:"h5",component:"h1",sx:{mb:1,fontWeight:600},children:r("checkCode.title")}),G(Oe,{variant:"body2",sx:{color:"grey.600"},children:r("checkCode.instructions")})]}),Se(xe,{sx:{mb:1},children:[G(Oe,{variant:"body2",component:"label",htmlFor:"code",sx:{display:"block",fontWeight:500,color:"grey.700",mb:.5},children:r("checkCode.codeLabel")}),G(xr,{fullWidth:!0,id:"code",name:"code",type:"text",value:m,disabled:i,onChange:h,error:!!c,helperText:c,placeholder:r("checkCode.codePlaceholder"),inputProps:{maxLength:6,style:{textAlign:"center",fontSize:"1.5rem",letterSpacing:"0.4rem"}},required:!0})]}),G(hr,{disabled:i||m.length!==6,type:"button",onClick:P,fullWidth:!0,variant:"contained",color:"primary",sx:{mt:2,mb:2},children:i?G(br,{size:20}):r("checkCode.verifyButton")}),G(xe,{sx:{display:"flex",justifyContent:"center",alignItems:"center"},children:G(Cr,{sx:{cursor:"pointer"},onClick:f,variant:"body2",color:"secondary",children:r("common.back")})})]}),G(xe,{children:l.length>0&&l.map((w,v)=>G(wr,{sx:{mt:2},severity:"error",children:w},v))})]})},vo=Pr;import{Box as Tr,CircularProgress as Er,Alert as To,Typography as ze}from"@mui/material";import{Fragment as Sr,jsx as ae,jsxs as Eo}from"react/jsx-runtime";var So=({children:e,fallback:t})=>{let{isLoading:s,error:a,isInitialized:m}=q(),{t:n}=U();return s?t||Eo(Tr,{sx:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",minHeight:"200px",gap:2},children:[ae(Er,{}),ae(ze,{variant:"body2",color:"text.secondary",children:n("login.initializing")!=="login.initializing"?n("login.initializing"):"Initializing..."})]}):a?ae(To,{severity:"error",sx:{mt:2},children:Eo(ze,{variant:"body2",children:[n("login.initializationError")!=="login.initializationError"?n("login.initializationError"):"Initialization error",":"," ",a]})}):m?ae(Sr,{children:e}):ae(To,{severity:"warning",sx:{mt:2},children:ae(ze,{variant:"body2",children:n("login.notInitialized")!=="login.notInitialized"?n("login.notInitialized"):"System not initialized"})})};import{jsx as K,jsxs as Ir}from"react/jsx-runtime";var Rr=({onScreenChange:e,onExternalNavigate:t,onLoginSuccess:s,onError:a,redirectUrl:m="/"})=>{let{t:n}=U(),{state:i,setScreen:p}=Te(),{config:l}=Q(),{showNotification:y}=Qe(),c=(d,o)=>{let r=o;d==="login"?r={}:d==="forgotPassword"&&!o&&(r={}),p(d,r),e?.(d,r)},x=()=>{let d={onScreenChange:c,onExternalNavigate:t,onError:a,redirectUrl:m};switch(i.currentScreen){case"forgotPassword":return K(xo,{...d});case"checkCode":return K(vo,{...d,searchParams:i.searchParams});case"resetPassword":return K(Po,{...d,searchParams:i.searchParams,onResetSuccess:()=>{let o=n("resetPassword.successMessage");y(o,"success"),c("login")}});default:return K(po,{...d,onLoginSuccess:s})}};return Ir(So,{children:[K(kr,{sx:{display:"flex",justifyContent:"center",mb:3},children:K("img",{src:l.logo||"/nocios-default.png",alt:n("login.logoAlt"),style:{width:"100%",maxWidth:"150px",height:"auto"},onError:d=>{let o=d.target;o.src="/nocios-default.png"}})}),!l.logo&&l.appName&&K(Lr,{variant:"h6",component:"h1",sx:{textAlign:"center",mb:2},children:l.appName}),x()]})},Ar=({translations:e,translationsUrl:t,language:s="en",initialScreen:a="login",autoReadFromCookies:m=!0,...n})=>{let{config:i}=Q();return K(no,{translations:e,translationsUrl:t,language:s,children:K(so,{config:i,children:K(uo,{config:i,initialScreen:a,autoReadFromCookies:m,children:K(Rr,{...n})})})})},Wn=Ar;import{Box as W,Card as ko,CardContent as Lo,Typography as j,Chip as ke,Avatar as Br,Divider as Fr,CircularProgress as Dr,Alert as Ro,List as _r,ListItem as Ne,ListItemText as Ve,ListItemIcon as Or,Collapse as zr,IconButton as We}from"@mui/material";import{Person as Nr,Email as Vr,Badge as Wr,Security as Ur,Schedule as Mr,AccountCircle as $r,ExpandMore as Hr,ExpandLess as Kr,Info as jr}from"@mui/icons-material";import{useState as qr}from"react";import{Fragment as Jr,jsx as b,jsxs as L}from"react/jsx-runtime";var Gr=({showExtendedData:e=!0,showProfileCard:t=!0,autoRefresh:s=!0})=>{let{userProfile:a,loading:m,error:n,extendedData:i,refreshProfile:p}=Ze({autoFetch:s,retryOnError:!0,maxRetries:3}),[l,y]=qr(!1);if(m)return L(W,{display:"flex",justifyContent:"center",alignItems:"center",p:3,children:[b(Dr,{}),b(j,{variant:"body2",sx:{ml:2},children:"Cargando perfil de usuario..."})]});if(n)return L(Ro,{severity:"error",action:b(We,{color:"inherit",size:"small",onClick:p,children:b(j,{variant:"caption",children:"Reintentar"})}),children:["Error al cargar el perfil: ",n]});if(!a)return b(Ro,{severity:"warning",children:"No se encontr\xF3 informaci\xF3n del usuario"});let c=i?.displayData||{},x=i?.totalFields||0,d=f=>{if(!f)return"No disponible";try{return new Date(f).toLocaleString("es-ES",{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}catch{return f}},o=(f,h)=>h==null?"No disponible":typeof h=="boolean"?h?"S\xED":"No":Array.isArray(h)?h.length>0?h.join(", "):"Ninguno":typeof h=="object"?JSON.stringify(h,null,2):String(h),r=[{key:"id",label:"ID",icon:b(Wr,{})},{key:"email",label:"Email",icon:b(Vr,{})},{key:"username",label:"Usuario",icon:b(Nr,{})},{key:"fullName",label:"Nombre completo",icon:b($r,{})},{key:"role",label:"Rol",icon:b(Ur,{})}],u=[{key:"firstName",label:"Nombre"},{key:"lastName",label:"Apellido"},{key:"isActive",label:"Activo"},{key:"lastLogin",label:"\xDAltimo login"},{key:"createdAt",label:"Creado"},{key:"updatedAt",label:"Actualizado"}],C=[...r.map(f=>f.key),...u.map(f=>f.key),"permissions"],P=Object.keys(c).filter(f=>!C.includes(f)).map(f=>({key:f,label:f}));return L(W,{children:[t&&b(ko,{sx:{mb:2},children:L(Lo,{children:[L(W,{display:"flex",alignItems:"center",mb:2,children:[b(Br,{src:c.avatar,sx:{width:56,height:56,mr:2},children:c.fullName?.[0]||c.username?.[0]||c.email?.[0]}),L(W,{children:[b(j,{variant:"h6",children:c.fullName||c.username||c.email}),b(j,{variant:"body2",color:"text.secondary",children:c.role||"Usuario"}),c.isActive!==void 0&&b(ke,{label:c.isActive?"Activo":"Inactivo",color:c.isActive?"success":"error",size:"small",sx:{mt:.5}})]})]}),b(W,{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(250px, 1fr))",gap:2,children:r.map(({key:f,label:h,icon:w})=>c[f]?L(W,{display:"flex",alignItems:"center",children:[b(W,{sx:{mr:1,color:"text.secondary"},children:w}),L(W,{children:[b(j,{variant:"caption",color:"text.secondary",children:h}),b(j,{variant:"body2",children:o(f,c[f])})]})]},f):null)}),c.permissions&&Array.isArray(c.permissions)&&c.permissions.length>0&&L(W,{mt:2,children:[b(j,{variant:"caption",color:"text.secondary",display:"block",children:"Permisos"}),L(W,{display:"flex",flexWrap:"wrap",gap:.5,mt:.5,children:[c.permissions.slice(0,5).map((f,h)=>b(ke,{label:f,size:"small",variant:"outlined"},h)),c.permissions.length>5&&b(ke,{label:`+${c.permissions.length-5} m\xE1s`,size:"small"})]})]})]})}),e&&b(ko,{children:L(Lo,{children:[L(W,{display:"flex",justifyContent:"space-between",alignItems:"center",mb:2,children:[L(j,{variant:"h6",display:"flex",alignItems:"center",children:[b(jr,{sx:{mr:1}}),"Informaci\xF3n Detallada"]}),b(ke,{label:`${x} campos totales`,size:"small"})]}),L(_r,{dense:!0,children:[u.map(({key:f,label:h})=>c[f]!==void 0&&L(Ne,{divider:!0,children:[b(Or,{children:b(Mr,{fontSize:"small"})}),b(Ve,{primary:h,secondary:f.includes("At")||f.includes("Login")?d(c[f]):o(f,c[f])})]},f)),P.length>0&&L(Jr,{children:[b(Fr,{sx:{my:1}}),b(Ne,{children:b(Ve,{primary:L(W,{display:"flex",justifyContent:"space-between",alignItems:"center",children:[L(j,{variant:"subtitle2",children:["Campos Personalizados (",P.length,")"]}),b(We,{size:"small",onClick:()=>y(!l),children:l?b(Kr,{}):b(Hr,{})})]})})}),b(zr,{in:l,children:P.map(({key:f,label:h})=>b(Ne,{sx:{pl:4},children:b(Ve,{primary:h,secondary:o(f,c[f])})},f))})]})]}),L(W,{mt:2,display:"flex",justifyContent:"space-between",alignItems:"center",children:[L(j,{variant:"caption",color:"text.secondary",children:["\xDAltima actualizaci\xF3n: ",d(c.updatedAt)]}),b(We,{size:"small",onClick:p,disabled:m,children:b(j,{variant:"caption",children:"Actualizar"})})]})]})})]})},Yr=Gr;var Ao=["create","read","update","delete"],Io=["create","read","update","delete"];import{useRef as wt}from"react";import{useTranslation as Ct}from"react-i18next";import{Box as Re,Typography as _o,Button as Pt,Stack as vt,Alert as Oo,Divider as Tt}from"@mui/material";import{Add as Et}from"@mui/icons-material";import{forwardRef as at}from"react";import{useTranslation as lt}from"react-i18next";import{Box as ne,FormControl as ct,InputLabel as dt,Select as ut,MenuItem as ft,IconButton as mt,Typography as le,FormHelperText as pt,Stack as Le,Paper as Do,Divider as gt,Button as Ke}from"@mui/material";import{Delete as yt,SelectAll as xt,ClearAll as ht}from"@mui/icons-material";import{useState as Xr,useEffect as Qr,useRef as Zr}from"react";import{useTranslation as et}from"react-i18next";import{Box as Ue,Typography as he,Button as Bo,Stack as Me,FormHelperText as Fo,ToggleButton as $e,ToggleButtonGroup as ot}from"@mui/material";import{CheckCircle as rt,Cancel as tt,SelectAll as nt,ClearAll as it}from"@mui/icons-material";import{jsx as D,jsxs as oe}from"react/jsx-runtime";var st=({value:e,onChange:t,availableFields:s,error:a,disabled:m=!1})=>{let{t:n}=et(),[i,p]=Xr("custom"),l=Zr(!1);Qr(()=>{let o=e||{allow:[],owner_allow:[],deny:[]},r=new Set(s),u=(o.allow||[]).filter(h=>r.has(h)),C=(o.owner_allow||[]).filter(h=>r.has(h)),P=(o.deny||[]).filter(h=>r.has(h));s.forEach(h=>{!u.includes(h)&&!C.includes(h)&&!P.includes(h)&&P.push(h)});let f={allow:u,owner_allow:C,deny:P};JSON.stringify(f)!==JSON.stringify(o)&&t(f),u.length===s.length?p("all"):P.length===s.length?p("none"):p("custom")},[s,e]);let y=()=>{l.current=!0,t({allow:[...s],owner_allow:[],deny:[]}),p("all"),setTimeout(()=>{l.current=!1},0)},c=()=>{l.current=!0,t({allow:[],owner_allow:[],deny:[...s]}),p("none"),setTimeout(()=>{l.current=!1},0)},x=o=>e?.allow?.includes(o)?"allow":e?.owner_allow?.includes(o)?"owner_allow":"deny",d=(o,r)=>{l.current=!0;let u=new Set(e?.allow||[]),C=new Set(e?.owner_allow||[]),P=new Set(e?.deny||[]);u.delete(o),C.delete(o),P.delete(o),r==="allow"&&u.add(o),r==="owner_allow"&&C.add(o),r==="deny"&&P.add(o),t({allow:Array.from(u),owner_allow:Array.from(C),deny:Array.from(P)}),p("custom"),setTimeout(()=>{l.current=!1},0)};return s.length===0?oe(Ue,{children:[D(he,{variant:"body2",color:"text.secondary",sx:{mb:1},children:n("modules.form.publicPolicies.fields.conditions.label")}),D(he,{variant:"body2",color:"text.secondary",sx:{fontStyle:"italic"},children:n("modules.form.publicPolicies.fields.conditions.noFieldsAvailable")}),a&&D(Fo,{error:!0,sx:{mt:1},children:a})]}):oe(Ue,{children:[D(he,{variant:"body2",color:"text.secondary",sx:{mb:2},children:n("modules.form.publicPolicies.fields.conditions.label")}),oe(Me,{direction:"row",spacing:1,sx:{mb:3},children:[D(Bo,{variant:i==="all"?"contained":"outlined",startIcon:D(nt,{}),onClick:y,disabled:m,size:"small",sx:{minWidth:120,...i==="all"&&{backgroundColor:"#16a34a","&:hover":{backgroundColor:"#15803d"}}},children:n("modules.form.publicPolicies.fields.conditions.allFields")}),D(Bo,{variant:i==="none"?"contained":"outlined",startIcon:D(it,{}),onClick:c,disabled:m,size:"small",sx:{minWidth:120,...i==="none"&&{backgroundColor:"#cf222e","&:hover":{backgroundColor:"#bc1f2c"}}},children:n("modules.form.publicPolicies.fields.conditions.noFields")})]}),oe(Ue,{sx:{p:2,border:"1px solid #d1d9e0",borderRadius:1,backgroundColor:"#f6f8fa"},children:[D(he,{variant:"body2",color:"text.secondary",sx:{mb:2},children:n("modules.form.publicPolicies.fields.conditions.help")}),D(Me,{spacing:1,children:s.map(o=>{let r=x(o);return oe(Me,{direction:"row",spacing:1,alignItems:"center",children:[D(he,{variant:"body2",sx:{minWidth:100,fontFamily:"monospace"},children:o}),oe(ot,{value:r,exclusive:!0,size:"small",children:[oe($e,{value:"allow",onClick:()=>d(o,"allow"),disabled:m,sx:{px:2,color:r==="allow"?"#ffffff":"#6b7280",backgroundColor:r==="allow"?"#16a34a":"#f3f4f6",borderColor:r==="allow"?"#16a34a":"#d1d5db","&:hover":{backgroundColor:r==="allow"?"#15803d":"#e5e7eb",borderColor:r==="allow"?"#15803d":"#9ca3af"},"&.Mui-selected":{backgroundColor:"#16a34a",color:"#ffffff","&:hover":{backgroundColor:"#15803d"}}},children:[D(rt,{sx:{fontSize:16,mr:.5}}),n("modules.form.publicPolicies.fields.conditions.states.allow")]}),D($e,{value:"owner_allow",onClick:()=>d(o,"owner_allow"),disabled:m,sx:{px:2,color:r==="owner_allow"?"#ffffff":"#6b7280",backgroundColor:r==="owner_allow"?"#0ea5e9":"#f3f4f6",borderColor:r==="owner_allow"?"#0ea5e9":"#d1d5db","&:hover":{backgroundColor:r==="owner_allow"?"#0284c7":"#e5e7eb",borderColor:r==="owner_allow"?"#0284c7":"#9ca3af"},"&.Mui-selected":{backgroundColor:"#0ea5e9",color:"#ffffff","&:hover":{backgroundColor:"#0284c7"}}},children:n("modules.form.publicPolicies.fields.conditions.states.ownerAllow")}),oe($e,{value:"deny",onClick:()=>d(o,"deny"),disabled:m,sx:{px:2,color:r==="deny"?"#ffffff":"#6b7280",backgroundColor:r==="deny"?"#dc2626":"#f3f4f6",borderColor:r==="deny"?"#dc2626":"#d1d5db","&:hover":{backgroundColor:r==="deny"?"#b91c1c":"#e5e7eb",borderColor:r==="deny"?"#b91c1c":"#9ca3af"},"&.Mui-selected":{backgroundColor:"#dc2626",color:"#ffffff","&:hover":{backgroundColor:"#b91c1c"}}},children:[D(tt,{sx:{fontSize:16,mr:.5}}),n("modules.form.publicPolicies.fields.conditions.states.deny")]})]})]},o)})})]}),a&&D(Fo,{error:!0,sx:{mt:1},children:a})]})},He=st;import{jsx as A,jsxs as _}from"react/jsx-runtime";var bt=at(({policy:e,onChange:t,onRemove:s,availableFields:a,isSubmitting:m=!1,usedActions:n,error:i},p)=>{let{t:l}=lt(),y=new Set(Array.from(n||[]));y.delete(e.action);let c=Ao.map(x=>({value:x,label:l(`modules.form.publicPolicies.fields.action.options.${x}`)}));return _(Do,{ref:p,sx:{p:3,border:"1px solid #d1d9e0",borderRadius:2,position:"relative",backgroundColor:"#ffffff"},children:[_(ne,{sx:{display:"flex",justifyContent:"space-between",alignItems:"flex-start",mb:3},children:[A(le,{variant:"subtitle1",sx:{fontWeight:600,color:"#111418",fontSize:"1rem"},children:l("modules.form.publicPolicies.policyTitle")}),A(mt,{onClick:s,size:"small",disabled:m,"aria-label":l("modules.form.publicPolicies.removePolicy"),sx:{color:"#656d76","&:hover":{color:"#cf222e",backgroundColor:"rgba(207, 34, 46, 0.1)"}},children:A(yt,{})})]}),_(Le,{spacing:3,children:[A(Le,{direction:{xs:"column",md:"row"},spacing:2,children:A(ne,{sx:{flex:1,minWidth:200},children:_(ct,{fullWidth:!0,children:[A(dt,{children:l("modules.form.publicPolicies.fields.action.label")}),A(ut,{value:e.action,label:l("modules.form.publicPolicies.fields.action.label"),disabled:m,onChange:x=>{let d=x.target.value,o={...e,action:d};d==="delete"?(o.permission="deny",delete o.fields):(o.fields={allow:[],owner_allow:[],deny:a},delete o.permission),t(o)},sx:{backgroundColor:"#ffffff","&:hover .MuiOutlinedInput-notchedOutline":{borderColor:"#8c959f"},"&.Mui-focused .MuiOutlinedInput-notchedOutline":{borderColor:"#0969da",borderWidth:2}},children:c.map(x=>{let d=y.has(x.value);return A(ft,{value:x.value,disabled:d,children:x.label},x.value)})}),i&&A(pt,{error:!0,children:i})]})})}),e.action==="delete"?_(ne,{children:[A(le,{variant:"body2",color:"text.secondary",sx:{mb:2},children:l("modules.form.publicPolicies.fields.conditions.label")}),_(Le,{direction:"row",spacing:1,sx:{mb:3},children:[A(Ke,{variant:e.permission==="*"?"contained":"outlined",startIcon:A(xt,{}),onClick:()=>t({...e,permission:"*"}),disabled:m,size:"small",sx:{minWidth:140,whiteSpace:"nowrap",...e.permission==="*"&&{backgroundColor:"#16a34a","&:hover":{backgroundColor:"#15803d"}}},children:l("modules.form.publicPolicies.fields.conditions.allFields")}),A(Ke,{variant:e.permission==="owner"?"contained":"outlined",onClick:()=>t({...e,permission:"owner"}),disabled:m,size:"small",sx:{minWidth:140,whiteSpace:"nowrap",...e.permission==="owner"&&{backgroundColor:"#0ea5e9","&:hover":{backgroundColor:"#0284c7"}}},children:l("modules.form.publicPolicies.fields.conditions.states.ownerAllow")}),A(Ke,{variant:e.permission==="deny"?"contained":"outlined",startIcon:A(ht,{}),onClick:()=>t({...e,permission:"deny"}),disabled:m,size:"small",sx:{minWidth:140,whiteSpace:"nowrap",...e.permission==="deny"&&{backgroundColor:"#cf222e","&:hover":{backgroundColor:"#bc1f2c"}}},children:l("modules.form.publicPolicies.fields.conditions.noFields")})]})]}):A(He,{value:e.fields||{allow:[],owner_allow:[],deny:[]},onChange:x=>t({...e,fields:x}),availableFields:a,disabled:m}),A(Do,{variant:"outlined",sx:{p:2,backgroundColor:"#f9fafb"},children:e.action==="delete"?_(le,{variant:"body2",sx:{fontFamily:"monospace",color:"text.secondary"},children:[_(ne,{component:"span",sx:{color:e.permission==="*"?"#16a34a":e.permission==="owner"?"#0ea5e9":"#dc2626"},children:[l("modules.form.publicPolicies.fields.conditions.states.allow"),":"]})," ",e.permission||"-"]}):_(Le,{spacing:.5,divider:A(gt,{sx:{borderColor:"#e5e7eb"}}),children:[_(le,{variant:"body2",sx:{fontFamily:"monospace",color:"text.secondary"},children:[_(ne,{component:"span",sx:{color:"#16a34a"},children:[l("modules.form.publicPolicies.fields.conditions.states.allow"),":"]})," ",(e?.fields?.allow||[]).join(", ")||"-"]}),_(le,{variant:"body2",sx:{fontFamily:"monospace",color:"text.secondary"},children:[_(ne,{component:"span",sx:{color:"#0ea5e9"},children:[l("modules.form.publicPolicies.fields.conditions.states.ownerAllow"),":"]})," ",(e?.fields?.owner_allow||[]).join(", ")||"-"]}),_(le,{variant:"body2",sx:{fontFamily:"monospace",color:"text.secondary"},children:[_(ne,{component:"span",sx:{color:"#dc2626"},children:[l("modules.form.publicPolicies.fields.conditions.states.deny"),":"]})," ",(e?.fields?.deny||[]).join(", ")||"-"]})]})})]})]})}),je=bt;import{Fragment as Lt,jsx as Y,jsxs as Ae}from"react/jsx-runtime";var St=()=>{let e=globalThis?.crypto;return e&&typeof e.randomUUID=="function"?e.randomUUID():`${Date.now()}-${Math.random().toString(16).slice(2)}`},kt=({policies:e,onChange:t,availableFields:s,errors:a,isSubmitting:m=!1})=>{let{t:n}=Ct(),i=wt({}),p=new Set((e||[]).map(r=>r.action).filter(Boolean)),l=Io.filter(r=>!p.has(r)),y=l.length>0,c=()=>{let r=l[0]||"create",u={id:St(),action:r};r==="delete"?u.permission="deny":u.fields={allow:[],owner_allow:[],deny:s};let C=[...e||[],u];t(C),setTimeout(()=>{let P=C.length-1,f=i.current[P];f&&f.scrollIntoView({behavior:"smooth",block:"center"})},100)},x=r=>{let u=[...e];u.splice(r,1),t(u)},d=(()=>{if(!a)return null;if(typeof a=="string")return a;let r=a._error;return typeof r=="string"?r:null})(),o=new Set((e||[]).map(r=>r.action));return Ae(Lt,{children:[Y(Tt,{sx:{borderColor:"#e0e4e7"}}),Ae(Re,{children:[Y(Re,{display:"flex",justifyContent:"space-between",alignItems:"center",mb:3,children:Ae(Re,{children:[Y(_o,{variant:"h6",sx:{fontWeight:600,color:"#111418",mb:1},children:n("modules.form.publicPolicies.title")}),Y(_o,{variant:"body2",color:"text.secondary",sx:{fontSize:"0.875rem"},children:n("modules.form.publicPolicies.description")})]})}),d&&Y(Oo,{severity:"error",sx:{mb:3},children:d}),Ae(vt,{spacing:3,children:[(e||[]).length===0?Y(Oo,{severity:"info",children:n("modules.form.publicPolicies.noPolicies")}):e.map((r,u)=>Y(je,{ref:C=>{i.current[u]=C},policy:r,onChange:C=>{let P=[...e];P[u]=C,t(P)},onRemove:()=>x(u),availableFields:s,isSubmitting:m,usedActions:o,error:typeof a=="object"&&a&&r.id in a?a[r.id]:void 0},r.id)),y&&Y(Re,{children:Y(Pt,{type:"button",variant:"outlined",startIcon:Y(Et,{}),onClick:c,disabled:m,sx:{borderColor:"#d0d7de",color:"#656d76","&:hover":{borderColor:"#8c959f",backgroundColor:"transparent"}},children:n("modules.form.publicPolicies.addPolicy")})})]})]})]})},Ti=kt;import{useState as qe}from"react";import{Button as Ie,TextField as zo,Box as ce,Alert as be,Typography as re,CircularProgress as Ge}from"@mui/material";import{jsx as R,jsxs as X}from"react/jsx-runtime";function Ii(){let[e,t]=qe(""),[s,a]=qe(""),[m,n]=qe(!1),{isAuthenticated:i,isLoading:p,error:l,login:y,logout:c,refreshTokens:x,clearError:d,isExpiringSoon:o,expiresIn:r}=Q(),u=async f=>{if(f.preventDefault(),!e||!s)return;(await y(e,s)).success&&(t(""),a(""),n(!1))},C=async()=>{await c()},P=async()=>{await x()};return i?X(ce,{sx:{maxWidth:600,mx:"auto",p:3},children:[R(re,{variant:"h4",gutterBottom:!0,children:"Welcome! \u{1F389}"}),R(be,{severity:"success",sx:{mb:3},children:"You are successfully logged in with Refresh Token Pattern enabled"}),X(ce,{sx:{mb:3,p:2,bgcolor:"background.paper",border:1,borderColor:"divider",borderRadius:1},children:[R(re,{variant:"h6",gutterBottom:!0,children:"Token Status"}),X(re,{variant:"body2",color:"text.secondary",children:["Access Token expires in: ",Math.round(r/1e3/60)," minutes"]}),o&&R(be,{severity:"warning",sx:{mt:1},children:"Token expires soon - automatic refresh will happen"})]}),X(ce,{sx:{display:"flex",gap:2,flexWrap:"wrap"},children:[R(Ie,{variant:"contained",onClick:P,disabled:p,startIcon:p?R(Ge,{size:16}):null,children:"Refresh Tokens"}),R(Ie,{variant:"outlined",color:"error",onClick:C,disabled:p,children:"Logout"})]}),l&&R(be,{severity:"error",sx:{mt:2},onClose:d,children:l})]}):X(ce,{sx:{maxWidth:400,mx:"auto",p:3},children:[R(re,{variant:"h4",gutterBottom:!0,align:"center",children:"Login with Refresh Tokens"}),R(be,{severity:"info",sx:{mb:3},children:"This demo shows the new Refresh Token Pattern with automatic session management"}),m?X("form",{onSubmit:u,children:[R(zo,{fullWidth:!0,label:"Email",type:"email",value:e,onChange:f=>t(f.target.value),margin:"normal",required:!0,autoComplete:"email"}),R(zo,{fullWidth:!0,label:"Password",type:"password",value:s,onChange:f=>a(f.target.value),margin:"normal",required:!0,autoComplete:"current-password"}),R(Ie,{type:"submit",fullWidth:!0,variant:"contained",size:"large",disabled:p,startIcon:p?R(Ge,{size:16}):null,sx:{mt:3,mb:2},children:p?"Logging in...":"Login"})]}):R(Ie,{fullWidth:!0,variant:"contained",size:"large",onClick:()=>n(!0),sx:{mt:2},children:"Show Login Form"}),l&&R(be,{severity:"error",sx:{mt:2},onClose:d,children:l})]})}function Bi(){let{isAuthenticated:e,isLoading:t,isExpiringSoon:s,expiresIn:a}=Q();return t?X(ce,{sx:{display:"flex",alignItems:"center",gap:1},children:[R(Ge,{size:16}),R(re,{variant:"caption",children:"Loading session..."})]}):e?X(ce,{children:[R(re,{variant:"caption",color:"success.main",children:"\u2713 Authenticated"}),s&&X(re,{variant:"caption",color:"warning.main",display:"block",children:["\u26A0 Token expires in ",Math.round(a/1e3/60)," min"]})]}):R(re,{variant:"caption",color:"text.secondary",children:"Not logged in"})}export{Wn as a,Yr as b,Ao as c,Io as d,Ti as e,Ii as f,Bi as g};
|
|
1
|
+
import{e as Qe,g as Q,j as Ze}from"./chunk-VVXZWBHL.mjs";import{g as z}from"./chunk-BJ6PIVZR.mjs";import{a as Je,e as Xe}from"./chunk-YS3C7YG5.mjs";import{Box as kr,Typography as Lr}from"@mui/material";import{createContext as $o,useContext as Ho,useMemo as oo}from"react";import{useState as Fe,useEffect as Mo}from"react";var eo=(e,t)=>{let[s,a]=Fe({}),[m,n]=Fe(!1),[i,p]=Fe(null);return Mo(()=>{if(console.log("\u{1F527} [I18nProvider] Hybrid translation loading:",{hasProvidedTranslations:!!t&&Object.keys(t).length>0,hasUrl:!!e,providedKeys:t?Object.keys(t).length:0}),t&&Object.keys(t).length>0){console.log("\u2705 [I18nProvider] Using provided translations (highest priority)"),a(t),n(!1),p(null);return}if(!e){console.log("\u26A0\uFE0F [I18nProvider] No translations provided, using empty object (keys will show as-is)"),a({}),n(!1),p(null);return}console.log("\u{1F310} [I18nProvider] Loading translations from URL:",e);let l=!1;return n(!0),p(null),fetch(e).then(y=>{if(!y.ok)throw new Error(`Failed to load translations: ${y.status}`);return y.json()}).then(y=>{l||(console.log("\u2705 [I18nProvider] Translations loaded successfully from URL:",{url:e,keysLoaded:Object.keys(y).length}),a(y),n(!1))}).catch(y=>{l||(console.error("\u274C [I18nProvider] Failed to load translations from URL:",e,y),p(y.message),console.log("\u{1F504} [I18nProvider] Falling back to empty translations (keys will show as-is)"),a({}),n(!1))}),()=>{l=!0}},[e,t]),{translations:s,loading:m,error:i}};import{jsx as ro}from"react/jsx-runtime";var to=$o(null),Ko=(e,t)=>e&&e[t]?e[t]:t.split(".").reduce((s,a)=>s&&typeof s=="object"?s[a]:void 0,e),no=({children:e,translations:t,translationsUrl:s,language:a="en"})=>{let{translations:m,loading:n}=eo(s,t),i=oo(()=>(l,y)=>{let c=Ko(m,l);return c==null&&(console.log(`\u{1F50D} [I18nProvider] Translation not found for key: "${l}" - showing key as-is`),c=l),y&&typeof c=="string"&&Object.entries(y).forEach(([x,d])=>{c=c.replace(new RegExp(`{{${x}}}`,"g"),d)}),typeof c=="string"?c:l},[m]),p=oo(()=>({t:i,language:a}),[i,a]);return n?ro("div",{children:"Loading translations..."}):ro(to.Provider,{value:p,children:e})},U=()=>{let e=Ho(to);if(!e)throw new Error("useTranslation must be used within I18nProvider");return e};import{createContext as jo,useContext as qo,useEffect as Go,useState as ve}from"react";import fe from"@nocios/crudify-browser";import{jsx as Yo}from"react/jsx-runtime";var io=jo(void 0),so=({config:e,children:t})=>{let[s,a]=ve(!0),[m,n]=ve(null),[i,p]=ve(!1),[l,y]=ve("");console.log("\u{1F50D} CrudifyProvider - Received config:",e),Go(()=>{if(console.log("\u{1F50D} CrudifyProvider - useEffect - config.publicApiKey:",e.publicApiKey),console.log("\u{1F50D} CrudifyProvider - useEffect - full config:",e),!e.publicApiKey){console.log("\u274C CrudifyProvider - No publicApiKey provided, setting error"),n("No publicApiKey provided"),a(!1),p(!1);return}console.log("\u2705 CrudifyProvider - publicApiKey found, proceeding with initialization");let x=`${e.publicApiKey}-${e.env}`;if(x===l&&i){a(!1);return}(async()=>{a(!0),n(null),p(!1);try{if(fe.config(e.env||"prod"),await fe.init(e.publicApiKey,"none"),typeof fe.transaction=="function"&&typeof fe.login=="function")p(!0),y(x);else throw new Error("Crudify methods not properly initialized")}catch(o){let r=o instanceof Error?o.message:"Failed to initialize Crudify";n(r),p(!1)}finally{a(!1)}})()},[e.publicApiKey,e.env,l,i]);let c={crudify:i?fe:null,isLoading:s,error:m,isInitialized:i};return Yo(io.Provider,{value:c,children:t})},q=()=>{let e=qo(io);if(e===void 0)throw new Error("useCrudify must be used within a CrudifyProvider");return e};import{createContext as Jo,useContext as Xo,useReducer as Qo,useEffect as ao}from"react";import{jsx as er}from"react/jsx-runtime";var lo={currentScreen:"login",searchParams:{},formData:{username:"",password:"",email:"",code:"",newPassword:"",confirmPassword:""},loading:!1,errors:{global:[]},emailSent:!1,codeAlreadyExists:!1,codeValidated:!1,fromCodeVerification:!1,config:{}};function Zo(e,t){switch(t.type){case"SET_SCREEN":let s={...e,currentScreen:t.payload.screen,searchParams:t.payload.params||e.searchParams,errors:{global:[]}},a=new URLSearchParams(s.searchParams),m=a.toString()?`?${a.toString()}`:window.location.pathname;try{window.history.replaceState({},"",m)}catch{}return s;case"SET_SEARCH_PARAMS":return{...e,searchParams:t.payload};case"UPDATE_FORM_DATA":return{...e,formData:{...e.formData,...t.payload},errors:{...e.errors,...Object.keys(t.payload).reduce((n,i)=>({...n,[i]:void 0}),{})}};case"SET_LOADING":return{...e,loading:t.payload};case"SET_ERRORS":return{...e,errors:{...e.errors,...t.payload}};case"CLEAR_ERRORS":return{...e,errors:{global:[]}};case"SET_EMAIL_SENT":return{...e,emailSent:t.payload};case"SET_CODE_ALREADY_EXISTS":return{...e,codeAlreadyExists:t.payload};case"SET_CODE_VALIDATED":return{...e,codeValidated:t.payload};case"SET_FROM_CODE_VERIFICATION":return{...e,fromCodeVerification:t.payload};case"RESET_FORM":return{...e,formData:lo.formData,errors:{global:[]},loading:!1,emailSent:!1,codeAlreadyExists:!1,codeValidated:!1,fromCodeVerification:!1};case"INIT_CONFIG":return{...e,config:t.payload};default:return e}}var co=Jo(void 0),uo=({children:e,initialScreen:t="login",config:s,autoReadFromCookies:a=!0})=>{let[m,n]=Qo(Zo,{...lo,currentScreen:t});ao(()=>{n({type:"INIT_CONFIG",payload:(()=>{let o={};if(a)try{let r=Je("logo");if(r){let u=decodeURIComponent(r);u.startsWith("http")&&(o.logo=u)}}catch(r){console.error("Error reading configuration from cookies:",r)}return{publicApiKey:s?.publicApiKey,env:s?.env,appName:s?.appName,logo:s?.logo||o.logo,loginActions:s?.loginActions}})()})},[s,a]),ao(()=>{let d=new URLSearchParams(window.location.search),o={};d.forEach((r,u)=>{o[u]=r}),Object.keys(o).length>0&&n({type:"SET_SEARCH_PARAMS",payload:o}),t==="checkCode"&&o.email&&n({type:"UPDATE_FORM_DATA",payload:{email:o.email,code:o.code||""}}),t==="resetPassword"&&o.link&&n({type:"SET_SEARCH_PARAMS",payload:o})},[t]);let x={state:m,dispatch:n,setScreen:(d,o)=>{n({type:"SET_SCREEN",payload:{screen:d,params:o}})},updateFormData:d=>{n({type:"UPDATE_FORM_DATA",payload:d})},setFieldError:(d,o)=>{n({type:"SET_ERRORS",payload:{[d]:o}})},clearErrors:()=>{n({type:"CLEAR_ERRORS"})},setLoading:d=>{n({type:"SET_LOADING",payload:d})}};return er(co.Provider,{value:x,children:e})},Te=()=>{let e=Xo(co);if(e===void 0)throw new Error("useLoginState must be used within a LoginStateProvider");return e};import{useEffect as or,useRef as rr}from"react";import{Typography as De,TextField as fo,Button as tr,Box as me,CircularProgress as nr,Alert as ir,Link as mo}from"@mui/material";import{Fragment as ar,jsx as M,jsxs as pe}from"react/jsx-runtime";var sr=({onScreenChange:e,onExternalNavigate:t,onLoginSuccess:s,onError:a,redirectUrl:m="/"})=>{let{crudify:n}=q(),{state:i,updateFormData:p,setFieldError:l,clearErrors:y,setLoading:c}=Te(),{login:x}=Q(),d=U(),{t:o}=d,r=d.i18n,u=rr(null),C=Xe(o,{currentLanguage:r?.language,enableDebug:!1}),P=()=>{if(i.searchParams.redirect)try{let g=decodeURIComponent(i.searchParams.redirect);if(g.startsWith("/")&&!g.startsWith("//"))return g}catch{}return m||"/"};or(()=>{let g=setTimeout(()=>{u.current&&u.current.focus()},100);return()=>clearTimeout(g)},[]);let f=g=>{console.log("\u{1F50D} [LoginForm] Translating parsed error:",g);let S=C.translateError({code:g.code,message:g.message,field:g.field});return console.log("\u{1F50D} [LoginForm] Translation result:",S),S},h=async()=>{if(!i.loading){if(!i.formData.username.trim()){l("username",o("login.usernameRequired"));return}if(!i.formData.password.trim()){l("password",o("login.passwordRequired"));return}y(),c(!0);try{let g=await x(i.formData.username,i.formData.password);if(c(!1),g.success){console.log("\u{1F510} LoginForm - Login successful via SessionProvider, calling onLoginSuccess");let S=P();s&&s(g.data,S)}else{let S=g.rawResponse||g;w(S)}}catch(g){c(!1);let J=z(g).map(f);l("global",J),a&&a(J.join(", "))}}},w=g=>{z(g).forEach(J=>{if(J.field)l(J.field,f(J));else{let de=i.errors.global||[];l("global",[...de,f(J)])}})};return pe(ar,{children:[pe(me,{component:"form",noValidate:!0,onSubmit:g=>{g.preventDefault(),h()},onKeyDown:g=>{g.key==="Enter"&&!i.loading&&(g.preventDefault(),h())},sx:{width:"100%",display:"flex",flexDirection:"column",gap:2},children:[pe(me,{sx:{mb:1},children:[M(De,{variant:"body2",component:"label",htmlFor:"email",sx:{display:"block",fontWeight:500,color:"grey.700",mb:.5},children:o("login.usernameOrEmailLabel")}),M(fo,{fullWidth:!0,id:"email",name:"email",type:"email",value:i.formData.username,disabled:i.loading,onChange:g=>p({username:g.target.value}),error:!!i.errors.username,helperText:i.errors.username,autoComplete:"email",placeholder:o("login.usernameOrEmailPlaceholder"),inputRef:u,required:!0})]}),pe(me,{sx:{mb:1},children:[M(De,{variant:"body2",component:"label",htmlFor:"password",sx:{display:"block",fontWeight:500,color:"grey.700",mb:.5},children:o("login.passwordLabel")}),M(fo,{fullWidth:!0,id:"password",name:"password",type:"password",value:i.formData.password,disabled:i.loading,onChange:g=>p({password:g.target.value}),error:!!i.errors.password,helperText:i.errors.password,autoComplete:"current-password",placeholder:o("login.passwordPlaceholder"),required:!0})]}),i.config.loginActions?.includes("forgotPassword")&&M(me,{sx:{display:"flex",justifyContent:"flex-end",alignItems:"center"},children:M(mo,{sx:{cursor:"pointer"},onClick:()=>{e?.("forgotPassword",i.searchParams)},variant:"body2",color:"secondary",children:o("login.forgotPasswordLink")})}),M(tr,{disabled:i.loading,type:"submit",fullWidth:!0,variant:"contained",color:"primary",sx:{mt:1,mb:2},children:i.loading?M(nr,{size:20}):o("login.loginButton")})]}),M(me,{children:i.errors.global&&i.errors.global.length>0&&i.errors.global.map((g,S)=>M(ir,{variant:"filled",sx:{mt:2},severity:"error",children:M("div",{children:g})},S))}),i.config.loginActions?.includes("createUser")&&pe(De,{variant:"body2",align:"center",sx:{color:"text.secondary",mt:3},children:[o("login.noAccountPrompt")," ",M(mo,{sx:{cursor:"pointer"},onClick:()=>{let S=`/public/users/create${Object.keys(i.searchParams).length>0?`?${new URLSearchParams(i.searchParams).toString()}`:""}`;t?.(S)},fontWeight:"medium",color:"secondary",children:o("login.signUpLink")})]})]})},po=sr;import{useState as ie}from"react";import{Typography as se,TextField as lr,Button as go,Box as Z,CircularProgress as cr,Alert as dr,Link as _e}from"@mui/material";import{Fragment as yo,jsx as B,jsxs as te}from"react/jsx-runtime";var ur=({onScreenChange:e,onError:t})=>{let{crudify:s}=q(),[a,m]=ie(""),[n,i]=ie(!1),[p,l]=ie([]),[y,c]=ie(null),[x,d]=ie(!1),[o,r]=ie(!1),{t:u}=U(),C=v=>{let E=[`errors.auth.${v.code}`,`errors.data.${v.code}`,`errors.system.${v.code}`,`errors.${v.code}`,`forgotPassword.${v.code.toLowerCase()}`];for(let g of E){let S=u(g);if(S!==g)return S}return v.message||u("error.unknown")},P=v=>/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(v),f=async()=>{if(!(n||!s)){if(l([]),c(null),!a){c(u("forgotPassword.emailRequired"));return}if(!P(a)){c(u("forgotPassword.invalidEmail"));return}i(!0);try{let v=[{operation:"requestPasswordReset",data:{email:a}}],E=await s.transaction(v);if(E.success)E.data&&E.data.existingCodeValid?r(!0):d(!0);else{let S=z(E).map(C);l(S)}}catch(v){let g=z(v).map(C);l(g),t&&t(g.join(", "))}finally{i(!1)}}},h=()=>{e?.("login")},w=()=>{if(x||o){e?.("checkCode",{email:a});return}if(!a){c(u("forgotPassword.emailRequired"));return}if(!P(a)){c(u("forgotPassword.invalidEmail"));return}e?.("checkCode",{email:a})};return x||o?B(yo,{children:te(Z,{sx:{width:"100%",display:"flex",flexDirection:"column",gap:2,textAlign:"center"},children:[te(Z,{sx:{mb:2},children:[B(se,{variant:"h5",component:"h1",sx:{mb:1,fontWeight:600},children:u(o?"forgotPassword.codeAlreadyExistsMessage":"forgotPassword.emailSentMessage")}),B(se,{variant:"body2",sx:{color:o?"success.main":"grey.600"},children:u("forgotPassword.checkEmailInstructions")})]}),B(go,{type:"button",onClick:w,fullWidth:!0,variant:"contained",color:"primary",sx:{mt:2,mb:2},children:u("forgotPassword.enterCodeLink")}),B(Z,{sx:{display:"flex",justifyContent:"center",alignItems:"center"},children:B(_e,{sx:{cursor:"pointer"},onClick:h,variant:"body2",color:"secondary",children:u("common.back")})})]})}):te(yo,{children:[te(Z,{component:"form",noValidate:!0,sx:{width:"100%",display:"flex",flexDirection:"column",gap:2},children:[te(Z,{sx:{mb:2},children:[B(se,{variant:"h5",component:"h1",sx:{mb:1,fontWeight:600},children:u("forgotPassword.title")}),B(se,{variant:"body2",sx:{color:"grey.600"},children:u("forgotPassword.instructions")})]}),te(Z,{sx:{mb:1},children:[B(se,{variant:"body2",component:"label",htmlFor:"email",sx:{display:"block",fontWeight:500,color:"grey.700",mb:.5},children:u("forgotPassword.emailLabel")}),B(lr,{fullWidth:!0,id:"email",name:"email",type:"email",value:a,disabled:n,onChange:v=>m(v.target.value),error:!!y,helperText:y,autoComplete:"email",placeholder:u("forgotPassword.emailPlaceholder"),required:!0})]}),B(go,{disabled:n,type:"button",onClick:f,fullWidth:!0,variant:"contained",color:"primary",sx:{mt:2,mb:2},children:n?B(cr,{size:20}):u("forgotPassword.sendCodeButton")}),te(Z,{sx:{display:"flex",justifyContent:"center",alignItems:"center",gap:2},children:[B(_e,{sx:{cursor:"pointer"},onClick:h,variant:"body2",color:"secondary",children:u("common.back")}),B(se,{variant:"body2",sx:{color:"grey.400"},children:"\u2022"}),B(_e,{sx:{cursor:"pointer"},onClick:w,variant:"body2",color:"secondary",children:u("login.alreadyHaveCodeLink")})]})]}),B(Z,{children:p.length>0&&p.map((v,E)=>B(dr,{variant:"filled",sx:{mt:2},severity:"error",children:v},E))})]})},xo=ur;import{useState as V,useEffect as ho}from"react";import{Typography as Ee,TextField as bo,Button as fr,Box as ee,CircularProgress as wo,Alert as Co,Link as mr}from"@mui/material";import{Fragment as gr,jsx as F,jsxs as ge}from"react/jsx-runtime";var pr=({onScreenChange:e,onError:t,searchParams:s,onResetSuccess:a})=>{let{crudify:m}=q(),[n,i]=V(""),[p,l]=V(""),[y,c]=V(!1),[x,d]=V([]),[o,r]=V(null),[u,C]=V(null),[P,f]=V(""),[h,w]=V(""),[v,E]=V(!1),[g,S]=V(!0),[J,de]=V(!1),[we,Be]=V(null),[No,Ye]=V(!1),{t:I}=U(),Ce=T=>{let k=[`errors.auth.${T.code}`,`errors.data.${T.code}`,`errors.system.${T.code}`,`errors.${T.code}`,`resetPassword.${T.code.toLowerCase()}`];for(let O of k){let N=I(O);if(N!==O)return N}return T.message||I("error.unknown")},Pe=T=>s?s instanceof URLSearchParams?s.get(T):s[T]||null:null;ho(()=>{if(s){if(s){let T=Pe("fromCodeVerification"),k=Pe("email"),O=Pe("code");if(T==="true"&&k&&O){f(k),w(O),E(!0),de(!0),S(!1);return}let N=Pe("link");if(N)try{let $=decodeURIComponent(N),[H,ue]=$.split("/");if(H&&ue&&H.length===6){w(H),f(ue),E(!1),Be({email:ue,code:H});return}}catch{}if(k&&O){f(k),w(O),E(!1),Be({email:k,code:O});return}}d([I("resetPassword.invalidCode")]),S(!1),setTimeout(()=>e?.("forgotPassword"),3e3)}},[s,m,I,e]),ho(()=>{m&&we&&!No&&(Ye(!0),(async(k,O)=>{try{let N=[{operation:"validatePasswordResetCode",data:{email:k,codePassword:O}}],$=await m.transaction(N);if($.data&&Array.isArray($.data)){let H=$.data[0];if(H&&H.response&&H.response.status==="OK"){de(!0);return}}if($.success)de(!0);else{let ue=z($).map(Ce);d(ue),setTimeout(()=>e?.("forgotPassword"),3e3)}}catch(N){let H=z(N).map(Ce);d(H),setTimeout(()=>e?.("forgotPassword"),3e3)}finally{S(!1),Be(null),Ye(!1)}})(we.email,we.code))},[m,we,I,e]);let Vo=T=>T.length<8?I("resetPassword.passwordTooShort"):null,Wo=async()=>{if(y||!m)return;d([]),r(null),C(null);let T=!1;if(!n)r(I("resetPassword.newPasswordRequired")),T=!0;else{let k=Vo(n);k&&(r(k),T=!0)}if(p?n!==p&&(C(I("resetPassword.passwordsDoNotMatch")),T=!0):(C(I("resetPassword.confirmPasswordRequired")),T=!0),!T){c(!0);try{let k=[{operation:"validateAndResetPassword",data:{email:P,codePassword:h,newPassword:n}}],O=await m.transaction(k);if(O.success)d([]),setTimeout(()=>{a?.()},1e3);else{let $=z(O).map(Ce);d($)}}catch(k){let N=z(k).map(Ce);d(N),t&&t(N.join(", "))}c(!1)}},Uo=()=>{v?e?.("checkCode",{email:P}):e?.("forgotPassword")};return g?F(ee,{sx:{display:"flex",justifyContent:"center",alignItems:"center",minHeight:"300px"},children:F(wo,{})}):J?ge(gr,{children:[ge(ee,{component:"form",noValidate:!0,sx:{width:"100%",display:"flex",flexDirection:"column",gap:2},children:[ge(ee,{sx:{mb:2},children:[F(Ee,{variant:"h5",component:"h1",sx:{mb:1,fontWeight:600},children:I("resetPassword.title")}),F(Ee,{variant:"body2",sx:{color:"grey.600"},children:I("resetPassword.instructions")})]}),ge(ee,{sx:{mb:1},children:[F(Ee,{variant:"body2",component:"label",htmlFor:"newPassword",sx:{display:"block",fontWeight:500,color:"grey.700",mb:.5},children:I("resetPassword.newPasswordLabel")}),F(bo,{fullWidth:!0,id:"newPassword",name:"newPassword",type:"password",value:n,disabled:y,onChange:T=>i(T.target.value),error:!!o,helperText:o,autoComplete:"new-password",placeholder:I("resetPassword.newPasswordPlaceholder"),required:!0})]}),ge(ee,{sx:{mb:1},children:[F(Ee,{variant:"body2",component:"label",htmlFor:"confirmPassword",sx:{display:"block",fontWeight:500,color:"grey.700",mb:.5},children:I("resetPassword.confirmPasswordLabel")}),F(bo,{fullWidth:!0,id:"confirmPassword",name:"confirmPassword",type:"password",value:p,disabled:y,onChange:T=>l(T.target.value),error:!!u,helperText:u,autoComplete:"new-password",placeholder:I("resetPassword.confirmPasswordPlaceholder"),required:!0})]}),F(fr,{disabled:y,type:"button",onClick:Wo,fullWidth:!0,variant:"contained",color:"primary",sx:{mt:2,mb:2},children:y?F(wo,{size:20}):I("resetPassword.resetPasswordButton")}),F(ee,{sx:{display:"flex",justifyContent:"center",alignItems:"center"},children:F(mr,{sx:{cursor:"pointer"},onClick:Uo,variant:"body2",color:"secondary",children:I("common.back")})})]}),F(ee,{children:x.length>0&&x.map((T,k)=>F(Co,{variant:"filled",sx:{mt:2},severity:"error",children:T},k))})]}):F(ee,{children:x.length>0&&x.map((T,k)=>F(Co,{variant:"filled",sx:{mt:2},severity:"error",children:T},k))})},Po=pr;import{useState as ye,useEffect as yr}from"react";import{Typography as Oe,TextField as xr,Button as hr,Box as xe,CircularProgress as br,Alert as wr,Link as Cr}from"@mui/material";import{Fragment as vr,jsx as G,jsxs as Se}from"react/jsx-runtime";var Pr=({onScreenChange:e,onError:t,searchParams:s})=>{let{crudify:a}=q(),[m,n]=ye(""),[i,p]=ye(!1),[l,y]=ye([]),[c,x]=ye(null),[d,o]=ye(""),{t:r}=U(),u=w=>s?s instanceof URLSearchParams?s.get(w):s[w]||null:null,C=w=>{let v=[`errors.auth.${w.code}`,`errors.data.${w.code}`,`errors.system.${w.code}`,`errors.${w.code}`,`checkCode.${w.code.toLowerCase()}`];for(let E of v){let g=r(E);if(g!==E)return g}return w.message||r("error.unknown")};yr(()=>{let w=u("email");w?o(w):e?.("forgotPassword")},[s,e]);let P=async()=>{if(!(i||!a)){if(y([]),x(null),!m){x(r("checkCode.codeRequired"));return}if(m.length!==6){x(r("checkCode.codeRequired"));return}p(!0);try{let w=[{operation:"validatePasswordResetCode",data:{email:d,codePassword:m}}],v=await a.transaction(w);if(v.success)e?.("resetPassword",{email:d,code:m,fromCodeVerification:"true"});else{let g=z(v).map(C);y(g),p(!1)}}catch(w){let E=z(w).map(C);y(E),p(!1),t&&t(E.join(", "))}}},f=()=>{e?.("forgotPassword")},h=w=>{let v=w.target.value.replace(/\D/g,"").slice(0,6);n(v)};return Se(vr,{children:[Se(xe,{component:"form",noValidate:!0,sx:{width:"100%",display:"flex",flexDirection:"column",gap:2},children:[Se(xe,{sx:{mb:2},children:[G(Oe,{variant:"h5",component:"h1",sx:{mb:1,fontWeight:600},children:r("checkCode.title")}),G(Oe,{variant:"body2",sx:{color:"grey.600"},children:r("checkCode.instructions")})]}),Se(xe,{sx:{mb:1},children:[G(Oe,{variant:"body2",component:"label",htmlFor:"code",sx:{display:"block",fontWeight:500,color:"grey.700",mb:.5},children:r("checkCode.codeLabel")}),G(xr,{fullWidth:!0,id:"code",name:"code",type:"text",value:m,disabled:i,onChange:h,error:!!c,helperText:c,placeholder:r("checkCode.codePlaceholder"),inputProps:{maxLength:6,style:{textAlign:"center",fontSize:"1.5rem",letterSpacing:"0.4rem"}},required:!0})]}),G(hr,{disabled:i||m.length!==6,type:"button",onClick:P,fullWidth:!0,variant:"contained",color:"primary",sx:{mt:2,mb:2},children:i?G(br,{size:20}):r("checkCode.verifyButton")}),G(xe,{sx:{display:"flex",justifyContent:"center",alignItems:"center"},children:G(Cr,{sx:{cursor:"pointer"},onClick:f,variant:"body2",color:"secondary",children:r("common.back")})})]}),G(xe,{children:l.length>0&&l.map((w,v)=>G(wr,{sx:{mt:2},severity:"error",children:w},v))})]})},vo=Pr;import{Box as Tr,CircularProgress as Er,Alert as To,Typography as ze}from"@mui/material";import{Fragment as Sr,jsx as ae,jsxs as Eo}from"react/jsx-runtime";var So=({children:e,fallback:t})=>{let{isLoading:s,error:a,isInitialized:m}=q(),{t:n}=U();return s?t||Eo(Tr,{sx:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",minHeight:"200px",gap:2},children:[ae(Er,{}),ae(ze,{variant:"body2",color:"text.secondary",children:n("login.initializing")!=="login.initializing"?n("login.initializing"):"Initializing..."})]}):a?ae(To,{severity:"error",sx:{mt:2},children:Eo(ze,{variant:"body2",children:[n("login.initializationError")!=="login.initializationError"?n("login.initializationError"):"Initialization error",":"," ",a]})}):m?ae(Sr,{children:e}):ae(To,{severity:"warning",sx:{mt:2},children:ae(ze,{variant:"body2",children:n("login.notInitialized")!=="login.notInitialized"?n("login.notInitialized"):"System not initialized"})})};import{jsx as K,jsxs as Ir}from"react/jsx-runtime";var Rr=({onScreenChange:e,onExternalNavigate:t,onLoginSuccess:s,onError:a,redirectUrl:m="/"})=>{let{t:n}=U(),{state:i,setScreen:p}=Te(),{config:l}=Q(),{showNotification:y}=Qe(),c=(d,o)=>{let r=o;d==="login"?r={}:d==="forgotPassword"&&!o&&(r={}),p(d,r),e?.(d,r)},x=()=>{let d={onScreenChange:c,onExternalNavigate:t,onError:a,redirectUrl:m};switch(i.currentScreen){case"forgotPassword":return K(xo,{...d});case"checkCode":return K(vo,{...d,searchParams:i.searchParams});case"resetPassword":return K(Po,{...d,searchParams:i.searchParams,onResetSuccess:()=>{let o=n("resetPassword.successMessage");y(o,"success"),c("login")}});default:return K(po,{...d,onLoginSuccess:s})}};return Ir(So,{children:[K(kr,{sx:{display:"flex",justifyContent:"center",mb:3},children:K("img",{src:l.logo||"/nocios-default.png",alt:n("login.logoAlt"),style:{width:"100%",maxWidth:"150px",height:"auto"},onError:d=>{let o=d.target;o.src="/nocios-default.png"}})}),!l.logo&&l.appName&&K(Lr,{variant:"h6",component:"h1",sx:{textAlign:"center",mb:2},children:l.appName}),x()]})},Ar=({translations:e,translationsUrl:t,language:s="en",initialScreen:a="login",autoReadFromCookies:m=!0,...n})=>{let{config:i}=Q();return K(no,{translations:e,translationsUrl:t,language:s,children:K(so,{config:i,children:K(uo,{config:i,initialScreen:a,autoReadFromCookies:m,children:K(Rr,{...n})})})})},Wn=Ar;import{Box as W,Card as ko,CardContent as Lo,Typography as j,Chip as ke,Avatar as Br,Divider as Fr,CircularProgress as Dr,Alert as Ro,List as _r,ListItem as Ne,ListItemText as Ve,ListItemIcon as Or,Collapse as zr,IconButton as We}from"@mui/material";import{Person as Nr,Email as Vr,Badge as Wr,Security as Ur,Schedule as Mr,AccountCircle as $r,ExpandMore as Hr,ExpandLess as Kr,Info as jr}from"@mui/icons-material";import{useState as qr}from"react";import{Fragment as Jr,jsx as b,jsxs as L}from"react/jsx-runtime";var Gr=({showExtendedData:e=!0,showProfileCard:t=!0,autoRefresh:s=!0})=>{let{userProfile:a,loading:m,error:n,extendedData:i,refreshProfile:p}=Ze({autoFetch:s,retryOnError:!0,maxRetries:3}),[l,y]=qr(!1);if(m)return L(W,{display:"flex",justifyContent:"center",alignItems:"center",p:3,children:[b(Dr,{}),b(j,{variant:"body2",sx:{ml:2},children:"Cargando perfil de usuario..."})]});if(n)return L(Ro,{severity:"error",action:b(We,{color:"inherit",size:"small",onClick:p,children:b(j,{variant:"caption",children:"Reintentar"})}),children:["Error al cargar el perfil: ",n]});if(!a)return b(Ro,{severity:"warning",children:"No se encontr\xF3 informaci\xF3n del usuario"});let c=i?.displayData||{},x=i?.totalFields||0,d=f=>{if(!f)return"No disponible";try{return new Date(f).toLocaleString("es-ES",{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}catch{return f}},o=(f,h)=>h==null?"No disponible":typeof h=="boolean"?h?"S\xED":"No":Array.isArray(h)?h.length>0?h.join(", "):"Ninguno":typeof h=="object"?JSON.stringify(h,null,2):String(h),r=[{key:"id",label:"ID",icon:b(Wr,{})},{key:"email",label:"Email",icon:b(Vr,{})},{key:"username",label:"Usuario",icon:b(Nr,{})},{key:"fullName",label:"Nombre completo",icon:b($r,{})},{key:"role",label:"Rol",icon:b(Ur,{})}],u=[{key:"firstName",label:"Nombre"},{key:"lastName",label:"Apellido"},{key:"isActive",label:"Activo"},{key:"lastLogin",label:"\xDAltimo login"},{key:"createdAt",label:"Creado"},{key:"updatedAt",label:"Actualizado"}],C=[...r.map(f=>f.key),...u.map(f=>f.key),"permissions"],P=Object.keys(c).filter(f=>!C.includes(f)).map(f=>({key:f,label:f}));return L(W,{children:[t&&b(ko,{sx:{mb:2},children:L(Lo,{children:[L(W,{display:"flex",alignItems:"center",mb:2,children:[b(Br,{src:c.avatar,sx:{width:56,height:56,mr:2},children:c.fullName?.[0]||c.username?.[0]||c.email?.[0]}),L(W,{children:[b(j,{variant:"h6",children:c.fullName||c.username||c.email}),b(j,{variant:"body2",color:"text.secondary",children:c.role||"Usuario"}),c.isActive!==void 0&&b(ke,{label:c.isActive?"Activo":"Inactivo",color:c.isActive?"success":"error",size:"small",sx:{mt:.5}})]})]}),b(W,{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(250px, 1fr))",gap:2,children:r.map(({key:f,label:h,icon:w})=>c[f]?L(W,{display:"flex",alignItems:"center",children:[b(W,{sx:{mr:1,color:"text.secondary"},children:w}),L(W,{children:[b(j,{variant:"caption",color:"text.secondary",children:h}),b(j,{variant:"body2",children:o(f,c[f])})]})]},f):null)}),c.permissions&&Array.isArray(c.permissions)&&c.permissions.length>0&&L(W,{mt:2,children:[b(j,{variant:"caption",color:"text.secondary",display:"block",children:"Permisos"}),L(W,{display:"flex",flexWrap:"wrap",gap:.5,mt:.5,children:[c.permissions.slice(0,5).map((f,h)=>b(ke,{label:f,size:"small",variant:"outlined"},h)),c.permissions.length>5&&b(ke,{label:`+${c.permissions.length-5} m\xE1s`,size:"small"})]})]})]})}),e&&b(ko,{children:L(Lo,{children:[L(W,{display:"flex",justifyContent:"space-between",alignItems:"center",mb:2,children:[L(j,{variant:"h6",display:"flex",alignItems:"center",children:[b(jr,{sx:{mr:1}}),"Informaci\xF3n Detallada"]}),b(ke,{label:`${x} campos totales`,size:"small"})]}),L(_r,{dense:!0,children:[u.map(({key:f,label:h})=>c[f]!==void 0&&L(Ne,{divider:!0,children:[b(Or,{children:b(Mr,{fontSize:"small"})}),b(Ve,{primary:h,secondary:f.includes("At")||f.includes("Login")?d(c[f]):o(f,c[f])})]},f)),P.length>0&&L(Jr,{children:[b(Fr,{sx:{my:1}}),b(Ne,{children:b(Ve,{primary:L(W,{display:"flex",justifyContent:"space-between",alignItems:"center",children:[L(j,{variant:"subtitle2",children:["Campos Personalizados (",P.length,")"]}),b(We,{size:"small",onClick:()=>y(!l),children:l?b(Kr,{}):b(Hr,{})})]})})}),b(zr,{in:l,children:P.map(({key:f,label:h})=>b(Ne,{sx:{pl:4},children:b(Ve,{primary:h,secondary:o(f,c[f])})},f))})]})]}),L(W,{mt:2,display:"flex",justifyContent:"space-between",alignItems:"center",children:[L(j,{variant:"caption",color:"text.secondary",children:["\xDAltima actualizaci\xF3n: ",d(c.updatedAt)]}),b(We,{size:"small",onClick:p,disabled:m,children:b(j,{variant:"caption",children:"Actualizar"})})]})]})})]})},Yr=Gr;var Ao=["create","read","update","delete"],Io=["create","read","update","delete"];import{useRef as wt}from"react";import{useTranslation as Ct}from"react-i18next";import{Box as Re,Typography as _o,Button as Pt,Stack as vt,Alert as Oo,Divider as Tt}from"@mui/material";import{Add as Et}from"@mui/icons-material";import{forwardRef as at}from"react";import{useTranslation as lt}from"react-i18next";import{Box as ne,FormControl as ct,InputLabel as dt,Select as ut,MenuItem as ft,IconButton as mt,Typography as le,FormHelperText as pt,Stack as Le,Paper as Do,Divider as gt,Button as Ke}from"@mui/material";import{Delete as yt,SelectAll as xt,ClearAll as ht}from"@mui/icons-material";import{useState as Xr,useEffect as Qr,useRef as Zr}from"react";import{useTranslation as et}from"react-i18next";import{Box as Ue,Typography as he,Button as Bo,Stack as Me,FormHelperText as Fo,ToggleButton as $e,ToggleButtonGroup as ot}from"@mui/material";import{CheckCircle as rt,Cancel as tt,SelectAll as nt,ClearAll as it}from"@mui/icons-material";import{jsx as D,jsxs as oe}from"react/jsx-runtime";var st=({value:e,onChange:t,availableFields:s,error:a,disabled:m=!1})=>{let{t:n}=et(),[i,p]=Xr("custom"),l=Zr(!1);Qr(()=>{let o=e||{allow:[],owner_allow:[],deny:[]},r=new Set(s),u=(o.allow||[]).filter(h=>r.has(h)),C=(o.owner_allow||[]).filter(h=>r.has(h)),P=(o.deny||[]).filter(h=>r.has(h));s.forEach(h=>{!u.includes(h)&&!C.includes(h)&&!P.includes(h)&&P.push(h)});let f={allow:u,owner_allow:C,deny:P};JSON.stringify(f)!==JSON.stringify(o)&&t(f),u.length===s.length?p("all"):P.length===s.length?p("none"):p("custom")},[s,e]);let y=()=>{l.current=!0,t({allow:[...s],owner_allow:[],deny:[]}),p("all"),setTimeout(()=>{l.current=!1},0)},c=()=>{l.current=!0,t({allow:[],owner_allow:[],deny:[...s]}),p("none"),setTimeout(()=>{l.current=!1},0)},x=o=>e?.allow?.includes(o)?"allow":e?.owner_allow?.includes(o)?"owner_allow":"deny",d=(o,r)=>{l.current=!0;let u=new Set(e?.allow||[]),C=new Set(e?.owner_allow||[]),P=new Set(e?.deny||[]);u.delete(o),C.delete(o),P.delete(o),r==="allow"&&u.add(o),r==="owner_allow"&&C.add(o),r==="deny"&&P.add(o),t({allow:Array.from(u),owner_allow:Array.from(C),deny:Array.from(P)}),p("custom"),setTimeout(()=>{l.current=!1},0)};return s.length===0?oe(Ue,{children:[D(he,{variant:"body2",color:"text.secondary",sx:{mb:1},children:n("modules.form.publicPolicies.fields.conditions.label")}),D(he,{variant:"body2",color:"text.secondary",sx:{fontStyle:"italic"},children:n("modules.form.publicPolicies.fields.conditions.noFieldsAvailable")}),a&&D(Fo,{error:!0,sx:{mt:1},children:a})]}):oe(Ue,{children:[D(he,{variant:"body2",color:"text.secondary",sx:{mb:2},children:n("modules.form.publicPolicies.fields.conditions.label")}),oe(Me,{direction:"row",spacing:1,sx:{mb:3},children:[D(Bo,{variant:i==="all"?"contained":"outlined",startIcon:D(nt,{}),onClick:y,disabled:m,size:"small",sx:{minWidth:120,...i==="all"&&{backgroundColor:"#16a34a","&:hover":{backgroundColor:"#15803d"}}},children:n("modules.form.publicPolicies.fields.conditions.allFields")}),D(Bo,{variant:i==="none"?"contained":"outlined",startIcon:D(it,{}),onClick:c,disabled:m,size:"small",sx:{minWidth:120,...i==="none"&&{backgroundColor:"#cf222e","&:hover":{backgroundColor:"#bc1f2c"}}},children:n("modules.form.publicPolicies.fields.conditions.noFields")})]}),oe(Ue,{sx:{p:2,border:"1px solid #d1d9e0",borderRadius:1,backgroundColor:"#f6f8fa"},children:[D(he,{variant:"body2",color:"text.secondary",sx:{mb:2},children:n("modules.form.publicPolicies.fields.conditions.help")}),D(Me,{spacing:1,children:s.map(o=>{let r=x(o);return oe(Me,{direction:"row",spacing:1,alignItems:"center",children:[D(he,{variant:"body2",sx:{minWidth:100,fontFamily:"monospace"},children:o}),oe(ot,{value:r,exclusive:!0,size:"small",children:[oe($e,{value:"allow",onClick:()=>d(o,"allow"),disabled:m,sx:{px:2,color:r==="allow"?"#ffffff":"#6b7280",backgroundColor:r==="allow"?"#16a34a":"#f3f4f6",borderColor:r==="allow"?"#16a34a":"#d1d5db","&:hover":{backgroundColor:r==="allow"?"#15803d":"#e5e7eb",borderColor:r==="allow"?"#15803d":"#9ca3af"},"&.Mui-selected":{backgroundColor:"#16a34a",color:"#ffffff","&:hover":{backgroundColor:"#15803d"}}},children:[D(rt,{sx:{fontSize:16,mr:.5}}),n("modules.form.publicPolicies.fields.conditions.states.allow")]}),D($e,{value:"owner_allow",onClick:()=>d(o,"owner_allow"),disabled:m,sx:{px:2,color:r==="owner_allow"?"#ffffff":"#6b7280",backgroundColor:r==="owner_allow"?"#0ea5e9":"#f3f4f6",borderColor:r==="owner_allow"?"#0ea5e9":"#d1d5db","&:hover":{backgroundColor:r==="owner_allow"?"#0284c7":"#e5e7eb",borderColor:r==="owner_allow"?"#0284c7":"#9ca3af"},"&.Mui-selected":{backgroundColor:"#0ea5e9",color:"#ffffff","&:hover":{backgroundColor:"#0284c7"}}},children:n("modules.form.publicPolicies.fields.conditions.states.ownerAllow")}),oe($e,{value:"deny",onClick:()=>d(o,"deny"),disabled:m,sx:{px:2,color:r==="deny"?"#ffffff":"#6b7280",backgroundColor:r==="deny"?"#dc2626":"#f3f4f6",borderColor:r==="deny"?"#dc2626":"#d1d5db","&:hover":{backgroundColor:r==="deny"?"#b91c1c":"#e5e7eb",borderColor:r==="deny"?"#b91c1c":"#9ca3af"},"&.Mui-selected":{backgroundColor:"#dc2626",color:"#ffffff","&:hover":{backgroundColor:"#b91c1c"}}},children:[D(tt,{sx:{fontSize:16,mr:.5}}),n("modules.form.publicPolicies.fields.conditions.states.deny")]})]})]},o)})})]}),a&&D(Fo,{error:!0,sx:{mt:1},children:a})]})},He=st;import{jsx as A,jsxs as _}from"react/jsx-runtime";var bt=at(({policy:e,onChange:t,onRemove:s,availableFields:a,isSubmitting:m=!1,usedActions:n,error:i},p)=>{let{t:l}=lt(),y=new Set(Array.from(n||[]));y.delete(e.action);let c=Ao.map(x=>({value:x,label:l(`modules.form.publicPolicies.fields.action.options.${x}`)}));return _(Do,{ref:p,sx:{p:3,border:"1px solid #d1d9e0",borderRadius:2,position:"relative",backgroundColor:"#ffffff"},children:[_(ne,{sx:{display:"flex",justifyContent:"space-between",alignItems:"flex-start",mb:3},children:[A(le,{variant:"subtitle1",sx:{fontWeight:600,color:"#111418",fontSize:"1rem"},children:l("modules.form.publicPolicies.policyTitle")}),A(mt,{onClick:s,size:"small",disabled:m,"aria-label":l("modules.form.publicPolicies.removePolicy"),sx:{color:"#656d76","&:hover":{color:"#cf222e",backgroundColor:"rgba(207, 34, 46, 0.1)"}},children:A(yt,{})})]}),_(Le,{spacing:3,children:[A(Le,{direction:{xs:"column",md:"row"},spacing:2,children:A(ne,{sx:{flex:1,minWidth:200},children:_(ct,{fullWidth:!0,children:[A(dt,{children:l("modules.form.publicPolicies.fields.action.label")}),A(ut,{value:e.action,label:l("modules.form.publicPolicies.fields.action.label"),disabled:m,onChange:x=>{let d=x.target.value,o={...e,action:d};d==="delete"?(o.permission="deny",delete o.fields):(o.fields={allow:[],owner_allow:[],deny:a},delete o.permission),t(o)},sx:{backgroundColor:"#ffffff","&:hover .MuiOutlinedInput-notchedOutline":{borderColor:"#8c959f"},"&.Mui-focused .MuiOutlinedInput-notchedOutline":{borderColor:"#0969da",borderWidth:2}},children:c.map(x=>{let d=y.has(x.value);return A(ft,{value:x.value,disabled:d,children:x.label},x.value)})}),i&&A(pt,{error:!0,children:i})]})})}),e.action==="delete"?_(ne,{children:[A(le,{variant:"body2",color:"text.secondary",sx:{mb:2},children:l("modules.form.publicPolicies.fields.conditions.label")}),_(Le,{direction:"row",spacing:1,sx:{mb:3},children:[A(Ke,{variant:e.permission==="*"?"contained":"outlined",startIcon:A(xt,{}),onClick:()=>t({...e,permission:"*"}),disabled:m,size:"small",sx:{minWidth:140,whiteSpace:"nowrap",...e.permission==="*"&&{backgroundColor:"#16a34a","&:hover":{backgroundColor:"#15803d"}}},children:l("modules.form.publicPolicies.fields.conditions.allFields")}),A(Ke,{variant:e.permission==="owner"?"contained":"outlined",onClick:()=>t({...e,permission:"owner"}),disabled:m,size:"small",sx:{minWidth:140,whiteSpace:"nowrap",...e.permission==="owner"&&{backgroundColor:"#0ea5e9","&:hover":{backgroundColor:"#0284c7"}}},children:l("modules.form.publicPolicies.fields.conditions.states.ownerAllow")}),A(Ke,{variant:e.permission==="deny"?"contained":"outlined",startIcon:A(ht,{}),onClick:()=>t({...e,permission:"deny"}),disabled:m,size:"small",sx:{minWidth:140,whiteSpace:"nowrap",...e.permission==="deny"&&{backgroundColor:"#cf222e","&:hover":{backgroundColor:"#bc1f2c"}}},children:l("modules.form.publicPolicies.fields.conditions.noFields")})]})]}):A(He,{value:e.fields||{allow:[],owner_allow:[],deny:[]},onChange:x=>t({...e,fields:x}),availableFields:a,disabled:m}),A(Do,{variant:"outlined",sx:{p:2,backgroundColor:"#f9fafb"},children:e.action==="delete"?_(le,{variant:"body2",sx:{fontFamily:"monospace",color:"text.secondary"},children:[_(ne,{component:"span",sx:{color:e.permission==="*"?"#16a34a":e.permission==="owner"?"#0ea5e9":"#dc2626"},children:[l("modules.form.publicPolicies.fields.conditions.states.allow"),":"]})," ",e.permission||"-"]}):_(Le,{spacing:.5,divider:A(gt,{sx:{borderColor:"#e5e7eb"}}),children:[_(le,{variant:"body2",sx:{fontFamily:"monospace",color:"text.secondary"},children:[_(ne,{component:"span",sx:{color:"#16a34a"},children:[l("modules.form.publicPolicies.fields.conditions.states.allow"),":"]})," ",(e?.fields?.allow||[]).join(", ")||"-"]}),_(le,{variant:"body2",sx:{fontFamily:"monospace",color:"text.secondary"},children:[_(ne,{component:"span",sx:{color:"#0ea5e9"},children:[l("modules.form.publicPolicies.fields.conditions.states.ownerAllow"),":"]})," ",(e?.fields?.owner_allow||[]).join(", ")||"-"]}),_(le,{variant:"body2",sx:{fontFamily:"monospace",color:"text.secondary"},children:[_(ne,{component:"span",sx:{color:"#dc2626"},children:[l("modules.form.publicPolicies.fields.conditions.states.deny"),":"]})," ",(e?.fields?.deny||[]).join(", ")||"-"]})]})})]})]})}),je=bt;import{Fragment as Lt,jsx as Y,jsxs as Ae}from"react/jsx-runtime";var St=()=>{let e=globalThis?.crypto;return e&&typeof e.randomUUID=="function"?e.randomUUID():`${Date.now()}-${Math.random().toString(16).slice(2)}`},kt=({policies:e,onChange:t,availableFields:s,errors:a,isSubmitting:m=!1})=>{let{t:n}=Ct(),i=wt({}),p=new Set((e||[]).map(r=>r.action).filter(Boolean)),l=Io.filter(r=>!p.has(r)),y=l.length>0,c=()=>{let r=l[0]||"create",u={id:St(),action:r};r==="delete"?u.permission="deny":u.fields={allow:[],owner_allow:[],deny:s};let C=[...e||[],u];t(C),setTimeout(()=>{let P=C.length-1,f=i.current[P];f&&f.scrollIntoView({behavior:"smooth",block:"center"})},100)},x=r=>{let u=[...e];u.splice(r,1),t(u)},d=(()=>{if(!a)return null;if(typeof a=="string")return a;let r=a._error;return typeof r=="string"?r:null})(),o=new Set((e||[]).map(r=>r.action));return Ae(Lt,{children:[Y(Tt,{sx:{borderColor:"#e0e4e7"}}),Ae(Re,{children:[Y(Re,{display:"flex",justifyContent:"space-between",alignItems:"center",mb:3,children:Ae(Re,{children:[Y(_o,{variant:"h6",sx:{fontWeight:600,color:"#111418",mb:1},children:n("modules.form.publicPolicies.title")}),Y(_o,{variant:"body2",color:"text.secondary",sx:{fontSize:"0.875rem"},children:n("modules.form.publicPolicies.description")})]})}),d&&Y(Oo,{severity:"error",sx:{mb:3},children:d}),Ae(vt,{spacing:3,children:[(e||[]).length===0?Y(Oo,{severity:"info",children:n("modules.form.publicPolicies.noPolicies")}):e.map((r,u)=>Y(je,{ref:C=>{i.current[u]=C},policy:r,onChange:C=>{let P=[...e];P[u]=C,t(P)},onRemove:()=>x(u),availableFields:s,isSubmitting:m,usedActions:o,error:typeof a=="object"&&a&&r.id in a?a[r.id]:void 0},r.id)),y&&Y(Re,{children:Y(Pt,{type:"button",variant:"outlined",startIcon:Y(Et,{}),onClick:c,disabled:m,sx:{borderColor:"#d0d7de",color:"#656d76","&:hover":{borderColor:"#8c959f",backgroundColor:"transparent"}},children:n("modules.form.publicPolicies.addPolicy")})})]})]})]})},Ti=kt;import{useState as qe}from"react";import{Button as Ie,TextField as zo,Box as ce,Alert as be,Typography as re,CircularProgress as Ge}from"@mui/material";import{jsx as R,jsxs as X}from"react/jsx-runtime";function Ii(){let[e,t]=qe(""),[s,a]=qe(""),[m,n]=qe(!1),{isAuthenticated:i,isLoading:p,error:l,login:y,logout:c,refreshTokens:x,clearError:d,isExpiringSoon:o,expiresIn:r}=Q(),u=async f=>{if(f.preventDefault(),!e||!s)return;(await y(e,s)).success&&(t(""),a(""),n(!1))},C=async()=>{await c()},P=async()=>{await x()};return i?X(ce,{sx:{maxWidth:600,mx:"auto",p:3},children:[R(re,{variant:"h4",gutterBottom:!0,children:"Welcome! \u{1F389}"}),R(be,{severity:"success",sx:{mb:3},children:"You are successfully logged in with Refresh Token Pattern enabled"}),X(ce,{sx:{mb:3,p:2,bgcolor:"background.paper",border:1,borderColor:"divider",borderRadius:1},children:[R(re,{variant:"h6",gutterBottom:!0,children:"Token Status"}),X(re,{variant:"body2",color:"text.secondary",children:["Access Token expires in: ",Math.round(r/1e3/60)," minutes"]}),o&&R(be,{severity:"warning",sx:{mt:1},children:"Token expires soon - automatic refresh will happen"})]}),X(ce,{sx:{display:"flex",gap:2,flexWrap:"wrap"},children:[R(Ie,{variant:"contained",onClick:P,disabled:p,startIcon:p?R(Ge,{size:16}):null,children:"Refresh Tokens"}),R(Ie,{variant:"outlined",color:"error",onClick:C,disabled:p,children:"Logout"})]}),l&&R(be,{severity:"error",sx:{mt:2},onClose:d,children:l})]}):X(ce,{sx:{maxWidth:400,mx:"auto",p:3},children:[R(re,{variant:"h4",gutterBottom:!0,align:"center",children:"Login with Refresh Tokens"}),R(be,{severity:"info",sx:{mb:3},children:"This demo shows the new Refresh Token Pattern with automatic session management"}),m?X("form",{onSubmit:u,children:[R(zo,{fullWidth:!0,label:"Email",type:"email",value:e,onChange:f=>t(f.target.value),margin:"normal",required:!0,autoComplete:"email"}),R(zo,{fullWidth:!0,label:"Password",type:"password",value:s,onChange:f=>a(f.target.value),margin:"normal",required:!0,autoComplete:"current-password"}),R(Ie,{type:"submit",fullWidth:!0,variant:"contained",size:"large",disabled:p,startIcon:p?R(Ge,{size:16}):null,sx:{mt:3,mb:2},children:p?"Logging in...":"Login"})]}):R(Ie,{fullWidth:!0,variant:"contained",size:"large",onClick:()=>n(!0),sx:{mt:2},children:"Show Login Form"}),l&&R(be,{severity:"error",sx:{mt:2},onClose:d,children:l})]})}function Bi(){let{isAuthenticated:e,isLoading:t,isExpiringSoon:s,expiresIn:a}=Q();return t?X(ce,{sx:{display:"flex",alignItems:"center",gap:1},children:[R(Ge,{size:16}),R(re,{variant:"caption",children:"Loading session..."})]}):e?X(ce,{children:[R(re,{variant:"caption",color:"success.main",children:"\u2713 Authenticated"}),s&&X(re,{variant:"caption",color:"warning.main",display:"block",children:["\u26A0 Token expires in ",Math.round(a/1e3/60)," min"]})]}):R(re,{variant:"caption",color:"text.secondary",children:"Not logged in"})}export{Wn as a,Yr as b,Ao as c,Io as d,Ti as e,Ii as f,Bi as g};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } 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 _chunkEP4KANK7js = require('./chunk-EP4KANK7.js');var _chunkYIIUEOXCjs = require('./chunk-YIIUEOXC.js');var _chunk6EBMA4HZjs = require('./chunk-6EBMA4HZ.js');var _material = require('@mui/material');var _react = require('react');var eo=(e,t)=>{let[s,a]=_react.useState.call(void 0, {}),[m,n]=_react.useState.call(void 0, !1),[i,p]=_react.useState.call(void 0, null);return _react.useEffect.call(void 0, ()=>{if(console.log("\u{1F527} [I18nProvider] Hybrid translation loading:",{hasProvidedTranslations:!!t&&Object.keys(t).length>0,hasUrl:!!e,providedKeys:t?Object.keys(t).length:0}),t&&Object.keys(t).length>0){console.log("\u2705 [I18nProvider] Using provided translations (highest priority)"),a(t),n(!1),p(null);return}if(!e){console.log("\u26A0\uFE0F [I18nProvider] No translations provided, using empty object (keys will show as-is)"),a({}),n(!1),p(null);return}console.log("\u{1F310} [I18nProvider] Loading translations from URL:",e);let l=!1;return n(!0),p(null),fetch(e).then(y=>{if(!y.ok)throw new Error(`Failed to load translations: ${y.status}`);return y.json()}).then(y=>{l||(console.log("\u2705 [I18nProvider] Translations loaded successfully from URL:",{url:e,keysLoaded:Object.keys(y).length}),a(y),n(!1))}).catch(y=>{l||(console.error("\u274C [I18nProvider] Failed to load translations from URL:",e,y),p(y.message),console.log("\u{1F504} [I18nProvider] Falling back to empty translations (keys will show as-is)"),a({}),n(!1))}),()=>{l=!0}},[e,t]),{translations:s,loading:m,error:i}};var _jsxruntime = require('react/jsx-runtime');var to=_react.createContext.call(void 0, null),Ko=(e,t)=>e&&e[t]?e[t]:t.split(".").reduce((s,a)=>s&&typeof s=="object"?s[a]:void 0,e),no=({children:e,translations:t,translationsUrl:s,language:a="en"})=>{let{translations:m,loading:n}=eo(s,t),i=_react.useMemo.call(void 0, ()=>(l,y)=>{let c=Ko(m,l);return c==null&&(console.log(`\u{1F50D} [I18nProvider] Translation not found for key: "${l}" - showing key as-is`),c=l),y&&typeof c=="string"&&Object.entries(y).forEach(([x,d])=>{c=c.replace(new RegExp(`{{${x}}}`,"g"),d)}),typeof c=="string"?c:l},[m]),p=_react.useMemo.call(void 0, ()=>({t:i,language:a}),[i,a]);return n?_jsxruntime.jsx.call(void 0, "div",{children:"Loading translations..."}):_jsxruntime.jsx.call(void 0, to.Provider,{value:p,children:e})},U=()=>{let e=_react.useContext.call(void 0, to);if(!e)throw new Error("useTranslation must be used within I18nProvider");return e};var _crudifybrowser = require('@nocios/crudify-browser'); var _crudifybrowser2 = _interopRequireDefault(_crudifybrowser);var io=_react.createContext.call(void 0, void 0),so=({config:e,children:t})=>{let[s,a]=_react.useState.call(void 0, !0),[m,n]=_react.useState.call(void 0, null),[i,p]=_react.useState.call(void 0, !1),[l,y]=_react.useState.call(void 0, "");console.log("\u{1F50D} CrudifyProvider - Received config:",e),_react.useEffect.call(void 0, ()=>{if(console.log("\u{1F50D} CrudifyProvider - useEffect - config.publicApiKey:",e.publicApiKey),console.log("\u{1F50D} CrudifyProvider - useEffect - full config:",e),!e.publicApiKey){console.log("\u274C CrudifyProvider - No publicApiKey provided, setting error"),n("No publicApiKey provided"),a(!1),p(!1);return}console.log("\u2705 CrudifyProvider - publicApiKey found, proceeding with initialization");let x=`${e.publicApiKey}-${e.env}`;if(x===l&&i){a(!1);return}(async()=>{a(!0),n(null),p(!1);try{if(_crudifybrowser2.default.config(e.env||"prod"),await _crudifybrowser2.default.init(e.publicApiKey,"none"),typeof _crudifybrowser2.default.transaction=="function"&&typeof _crudifybrowser2.default.login=="function")p(!0),y(x);else throw new Error("Crudify methods not properly initialized")}catch(o){let r=o instanceof Error?o.message:"Failed to initialize Crudify";n(r),p(!1)}finally{a(!1)}})()},[e.publicApiKey,e.env,l,i]);let c={crudify:i?_crudifybrowser2.default:null,isLoading:s,error:m,isInitialized:i};return _jsxruntime.jsx.call(void 0, io.Provider,{value:c,children:t})},q=()=>{let e=_react.useContext.call(void 0, io);if(e===void 0)throw new Error("useCrudify must be used within a CrudifyProvider");return e};var lo={currentScreen:"login",searchParams:{},formData:{username:"",password:"",email:"",code:"",newPassword:"",confirmPassword:""},loading:!1,errors:{global:[]},emailSent:!1,codeAlreadyExists:!1,codeValidated:!1,fromCodeVerification:!1,config:{}};function Zo(e,t){switch(t.type){case"SET_SCREEN":let s={...e,currentScreen:t.payload.screen,searchParams:t.payload.params||e.searchParams,errors:{global:[]}},a=new URLSearchParams(s.searchParams),m=a.toString()?`?${a.toString()}`:window.location.pathname;try{window.history.replaceState({},"",m)}catch (e2){}return s;case"SET_SEARCH_PARAMS":return{...e,searchParams:t.payload};case"UPDATE_FORM_DATA":return{...e,formData:{...e.formData,...t.payload},errors:{...e.errors,...Object.keys(t.payload).reduce((n,i)=>({...n,[i]:void 0}),{})}};case"SET_LOADING":return{...e,loading:t.payload};case"SET_ERRORS":return{...e,errors:{...e.errors,...t.payload}};case"CLEAR_ERRORS":return{...e,errors:{global:[]}};case"SET_EMAIL_SENT":return{...e,emailSent:t.payload};case"SET_CODE_ALREADY_EXISTS":return{...e,codeAlreadyExists:t.payload};case"SET_CODE_VALIDATED":return{...e,codeValidated:t.payload};case"SET_FROM_CODE_VERIFICATION":return{...e,fromCodeVerification:t.payload};case"RESET_FORM":return{...e,formData:lo.formData,errors:{global:[]},loading:!1,emailSent:!1,codeAlreadyExists:!1,codeValidated:!1,fromCodeVerification:!1};case"INIT_CONFIG":return{...e,config:t.payload};default:return e}}var co=_react.createContext.call(void 0, void 0),uo=({children:e,initialScreen:t="login",config:s,autoReadFromCookies:a=!0})=>{let[m,n]=_react.useReducer.call(void 0, Zo,{...lo,currentScreen:t});_react.useEffect.call(void 0, ()=>{n({type:"INIT_CONFIG",payload:(()=>{let o={};if(a)try{let r=_chunk6EBMA4HZjs.a.call(void 0, "logo");if(r){let u=decodeURIComponent(r);u.startsWith("http")&&(o.logo=u)}}catch(r){console.error("Error reading configuration from cookies:",r)}return{publicApiKey:_optionalChain([s, 'optionalAccess', _2 => _2.publicApiKey]),env:_optionalChain([s, 'optionalAccess', _3 => _3.env]),appName:_optionalChain([s, 'optionalAccess', _4 => _4.appName]),logo:_optionalChain([s, 'optionalAccess', _5 => _5.logo])||o.logo,loginActions:_optionalChain([s, 'optionalAccess', _6 => _6.loginActions])}})()})},[s,a]),_react.useEffect.call(void 0, ()=>{let d=new URLSearchParams(window.location.search),o={};d.forEach((r,u)=>{o[u]=r}),Object.keys(o).length>0&&n({type:"SET_SEARCH_PARAMS",payload:o}),t==="checkCode"&&o.email&&n({type:"UPDATE_FORM_DATA",payload:{email:o.email,code:o.code||""}}),t==="resetPassword"&&o.link&&n({type:"SET_SEARCH_PARAMS",payload:o})},[t]);let x={state:m,dispatch:n,setScreen:(d,o)=>{n({type:"SET_SCREEN",payload:{screen:d,params:o}})},updateFormData:d=>{n({type:"UPDATE_FORM_DATA",payload:d})},setFieldError:(d,o)=>{n({type:"SET_ERRORS",payload:{[d]:o}})},clearErrors:()=>{n({type:"CLEAR_ERRORS"})},setLoading:d=>{n({type:"SET_LOADING",payload:d})}};return _jsxruntime.jsx.call(void 0, co.Provider,{value:x,children:e})},Te=()=>{let e=_react.useContext.call(void 0, co);if(e===void 0)throw new Error("useLoginState must be used within a LoginStateProvider");return e};var sr=({onScreenChange:e,onExternalNavigate:t,onLoginSuccess:s,onError:a,redirectUrl:m="/"})=>{let{crudify:n}=q(),{state:i,updateFormData:p,setFieldError:l,clearErrors:y,setLoading:c}=Te(),{login:x}=_chunkEP4KANK7js.g.call(void 0, ),d=U(),{t:o}=d,r=d.i18n,u=_react.useRef.call(void 0, null),C=_chunk6EBMA4HZjs.e.call(void 0, o,{currentLanguage:_optionalChain([r, 'optionalAccess', _7 => _7.language]),enableDebug:!1}),P=()=>{if(i.searchParams.redirect)try{let g=decodeURIComponent(i.searchParams.redirect);if(g.startsWith("/")&&!g.startsWith("//"))return g}catch (e3){}return m||"/"};_react.useEffect.call(void 0, ()=>{let g=setTimeout(()=>{u.current&&u.current.focus()},100);return()=>clearTimeout(g)},[]);let f=g=>{console.log("\u{1F50D} [LoginForm] Translating parsed error:",g);let S=C.translateError({code:g.code,message:g.message,field:g.field});return console.log("\u{1F50D} [LoginForm] Translation result:",S),S},h=async()=>{if(!i.loading){if(!i.formData.username.trim()){l("username",o("login.usernameRequired"));return}if(!i.formData.password.trim()){l("password",o("login.passwordRequired"));return}y(),c(!0);try{let g=await x(i.formData.username,i.formData.password);if(c(!1),g.success){console.log("\u{1F510} LoginForm - Login successful via SessionProvider, calling onLoginSuccess");let S=P();s&&s(g.data,S)}else{let S=g.rawResponse||g;w(S)}}catch(g){c(!1);let J=_chunkYIIUEOXCjs.g.call(void 0, g).map(f);l("global",J),a&&a(J.join(", "))}}},w=g=>{_chunkYIIUEOXCjs.g.call(void 0, g).forEach(J=>{if(J.field)l(J.field,f(J));else{let de=i.errors.global||[];l("global",[...de,f(J)])}})};return _jsxruntime.jsxs.call(void 0, _jsxruntime.Fragment,{children:[_jsxruntime.jsxs.call(void 0, _material.Box,{component:"form",noValidate:!0,onSubmit:g=>{g.preventDefault(),h()},onKeyDown:g=>{g.key==="Enter"&&!i.loading&&(g.preventDefault(),h())},sx:{width:"100%",display:"flex",flexDirection:"column",gap:2},children:[_jsxruntime.jsxs.call(void 0, _material.Box,{sx:{mb:1},children:[_jsxruntime.jsx.call(void 0, _material.Typography,{variant:"body2",component:"label",htmlFor:"email",sx:{display:"block",fontWeight:500,color:"grey.700",mb:.5},children:o("login.usernameOrEmailLabel")}),_jsxruntime.jsx.call(void 0, _material.TextField,{fullWidth:!0,id:"email",name:"email",type:"email",value:i.formData.username,disabled:i.loading,onChange:g=>p({username:g.target.value}),error:!!i.errors.username,helperText:i.errors.username,autoComplete:"email",placeholder:o("login.usernameOrEmailPlaceholder"),inputRef:u,required:!0})]}),_jsxruntime.jsxs.call(void 0, _material.Box,{sx:{mb:1},children:[_jsxruntime.jsx.call(void 0, _material.Typography,{variant:"body2",component:"label",htmlFor:"password",sx:{display:"block",fontWeight:500,color:"grey.700",mb:.5},children:o("login.passwordLabel")}),_jsxruntime.jsx.call(void 0, _material.TextField,{fullWidth:!0,id:"password",name:"password",type:"password",value:i.formData.password,disabled:i.loading,onChange:g=>p({password:g.target.value}),error:!!i.errors.password,helperText:i.errors.password,autoComplete:"current-password",placeholder:o("login.passwordPlaceholder"),required:!0})]}),_optionalChain([i, 'access', _8 => _8.config, 'access', _9 => _9.loginActions, 'optionalAccess', _10 => _10.includes, 'call', _11 => _11("forgotPassword")])&&_jsxruntime.jsx.call(void 0, _material.Box,{sx:{display:"flex",justifyContent:"flex-end",alignItems:"center"},children:_jsxruntime.jsx.call(void 0, _material.Link,{sx:{cursor:"pointer"},onClick:()=>{_optionalChain([e, 'optionalCall', _12 => _12("forgotPassword",i.searchParams)])},variant:"body2",color:"secondary",children:o("login.forgotPasswordLink")})}),_jsxruntime.jsx.call(void 0, _material.Button,{disabled:i.loading,type:"submit",fullWidth:!0,variant:"contained",color:"primary",sx:{mt:1,mb:2},children:i.loading?_jsxruntime.jsx.call(void 0, _material.CircularProgress,{size:20}):o("login.loginButton")})]}),_jsxruntime.jsx.call(void 0, _material.Box,{children:i.errors.global&&i.errors.global.length>0&&i.errors.global.map((g,S)=>_jsxruntime.jsx.call(void 0, _material.Alert,{variant:"filled",sx:{mt:2},severity:"error",children:_jsxruntime.jsx.call(void 0, "div",{children:g})},S))}),_optionalChain([i, 'access', _13 => _13.config, 'access', _14 => _14.loginActions, 'optionalAccess', _15 => _15.includes, 'call', _16 => _16("createUser")])&&_jsxruntime.jsxs.call(void 0, _material.Typography,{variant:"body2",align:"center",sx:{color:"text.secondary",mt:3},children:[o("login.noAccountPrompt")," ",_jsxruntime.jsx.call(void 0, _material.Link,{sx:{cursor:"pointer"},onClick:()=>{let S=`/public/users/create${Object.keys(i.searchParams).length>0?`?${new URLSearchParams(i.searchParams).toString()}`:""}`;_optionalChain([t, 'optionalCall', _17 => _17(S)])},fontWeight:"medium",color:"secondary",children:o("login.signUpLink")})]})]})},po=sr;var ur=({onScreenChange:e,onError:t})=>{let{crudify:s}=q(),[a,m]=_react.useState.call(void 0, ""),[n,i]=_react.useState.call(void 0, !1),[p,l]=_react.useState.call(void 0, []),[y,c]=_react.useState.call(void 0, null),[x,d]=_react.useState.call(void 0, !1),[o,r]=_react.useState.call(void 0, !1),{t:u}=U(),C=v=>{let E=[`errors.auth.${v.code}`,`errors.data.${v.code}`,`errors.system.${v.code}`,`errors.${v.code}`,`forgotPassword.${v.code.toLowerCase()}`];for(let g of E){let S=u(g);if(S!==g)return S}return v.message||u("error.unknown")},P=v=>/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(v),f=async()=>{if(!(n||!s)){if(l([]),c(null),!a){c(u("forgotPassword.emailRequired"));return}if(!P(a)){c(u("forgotPassword.invalidEmail"));return}i(!0);try{let v=[{operation:"requestPasswordReset",data:{email:a}}],E=await s.transaction(v);if(E.success)E.data&&E.data.existingCodeValid?r(!0):d(!0);else{let S=_chunkYIIUEOXCjs.g.call(void 0, E).map(C);l(S)}}catch(v){let g=_chunkYIIUEOXCjs.g.call(void 0, v).map(C);l(g),t&&t(g.join(", "))}finally{i(!1)}}},h=()=>{_optionalChain([e, 'optionalCall', _18 => _18("login")])},w=()=>{if(x||o){_optionalChain([e, 'optionalCall', _19 => _19("checkCode",{email:a})]);return}if(!a){c(u("forgotPassword.emailRequired"));return}if(!P(a)){c(u("forgotPassword.invalidEmail"));return}_optionalChain([e, 'optionalCall', _20 => _20("checkCode",{email:a})])};return x||o?_jsxruntime.jsx.call(void 0, _jsxruntime.Fragment,{children:_jsxruntime.jsxs.call(void 0, _material.Box,{sx:{width:"100%",display:"flex",flexDirection:"column",gap:2,textAlign:"center"},children:[_jsxruntime.jsxs.call(void 0, _material.Box,{sx:{mb:2},children:[_jsxruntime.jsx.call(void 0, _material.Typography,{variant:"h5",component:"h1",sx:{mb:1,fontWeight:600},children:u(o?"forgotPassword.codeAlreadyExistsMessage":"forgotPassword.emailSentMessage")}),_jsxruntime.jsx.call(void 0, _material.Typography,{variant:"body2",sx:{color:o?"success.main":"grey.600"},children:u("forgotPassword.checkEmailInstructions")})]}),_jsxruntime.jsx.call(void 0, _material.Button,{type:"button",onClick:w,fullWidth:!0,variant:"contained",color:"primary",sx:{mt:2,mb:2},children:u("forgotPassword.enterCodeLink")}),_jsxruntime.jsx.call(void 0, _material.Box,{sx:{display:"flex",justifyContent:"center",alignItems:"center"},children:_jsxruntime.jsx.call(void 0, _material.Link,{sx:{cursor:"pointer"},onClick:h,variant:"body2",color:"secondary",children:u("common.back")})})]})}):_jsxruntime.jsxs.call(void 0, _jsxruntime.Fragment,{children:[_jsxruntime.jsxs.call(void 0, _material.Box,{component:"form",noValidate:!0,sx:{width:"100%",display:"flex",flexDirection:"column",gap:2},children:[_jsxruntime.jsxs.call(void 0, _material.Box,{sx:{mb:2},children:[_jsxruntime.jsx.call(void 0, _material.Typography,{variant:"h5",component:"h1",sx:{mb:1,fontWeight:600},children:u("forgotPassword.title")}),_jsxruntime.jsx.call(void 0, _material.Typography,{variant:"body2",sx:{color:"grey.600"},children:u("forgotPassword.instructions")})]}),_jsxruntime.jsxs.call(void 0, _material.Box,{sx:{mb:1},children:[_jsxruntime.jsx.call(void 0, _material.Typography,{variant:"body2",component:"label",htmlFor:"email",sx:{display:"block",fontWeight:500,color:"grey.700",mb:.5},children:u("forgotPassword.emailLabel")}),_jsxruntime.jsx.call(void 0, _material.TextField,{fullWidth:!0,id:"email",name:"email",type:"email",value:a,disabled:n,onChange:v=>m(v.target.value),error:!!y,helperText:y,autoComplete:"email",placeholder:u("forgotPassword.emailPlaceholder"),required:!0})]}),_jsxruntime.jsx.call(void 0, _material.Button,{disabled:n,type:"button",onClick:f,fullWidth:!0,variant:"contained",color:"primary",sx:{mt:2,mb:2},children:n?_jsxruntime.jsx.call(void 0, _material.CircularProgress,{size:20}):u("forgotPassword.sendCodeButton")}),_jsxruntime.jsxs.call(void 0, _material.Box,{sx:{display:"flex",justifyContent:"center",alignItems:"center",gap:2},children:[_jsxruntime.jsx.call(void 0, _material.Link,{sx:{cursor:"pointer"},onClick:h,variant:"body2",color:"secondary",children:u("common.back")}),_jsxruntime.jsx.call(void 0, _material.Typography,{variant:"body2",sx:{color:"grey.400"},children:"\u2022"}),_jsxruntime.jsx.call(void 0, _material.Link,{sx:{cursor:"pointer"},onClick:w,variant:"body2",color:"secondary",children:u("login.alreadyHaveCodeLink")})]})]}),_jsxruntime.jsx.call(void 0, _material.Box,{children:p.length>0&&p.map((v,E)=>_jsxruntime.jsx.call(void 0, _material.Alert,{variant:"filled",sx:{mt:2},severity:"error",children:v},E))})]})},xo=ur;var pr=({onScreenChange:e,onError:t,searchParams:s,onResetSuccess:a})=>{let{crudify:m}=q(),[n,i]=_react.useState.call(void 0, ""),[p,l]=_react.useState.call(void 0, ""),[y,c]=_react.useState.call(void 0, !1),[x,d]=_react.useState.call(void 0, []),[o,r]=_react.useState.call(void 0, null),[u,C]=_react.useState.call(void 0, null),[P,f]=_react.useState.call(void 0, ""),[h,w]=_react.useState.call(void 0, ""),[v,E]=_react.useState.call(void 0, !1),[g,S]=_react.useState.call(void 0, !0),[J,de]=_react.useState.call(void 0, !1),[we,Be]=_react.useState.call(void 0, null),[No,Ye]=_react.useState.call(void 0, !1),{t:I}=U(),Ce=T=>{let k=[`errors.auth.${T.code}`,`errors.data.${T.code}`,`errors.system.${T.code}`,`errors.${T.code}`,`resetPassword.${T.code.toLowerCase()}`];for(let O of k){let N=I(O);if(N!==O)return N}return T.message||I("error.unknown")},Pe=T=>s?s instanceof URLSearchParams?s.get(T):s[T]||null:null;_react.useEffect.call(void 0, ()=>{if(s){if(s){let T=Pe("fromCodeVerification"),k=Pe("email"),O=Pe("code");if(T==="true"&&k&&O){f(k),w(O),E(!0),de(!0),S(!1);return}let N=Pe("link");if(N)try{let $=decodeURIComponent(N),[H,ue]=$.split("/");if(H&&ue&&H.length===6){w(H),f(ue),E(!1),Be({email:ue,code:H});return}}catch (e4){}if(k&&O){f(k),w(O),E(!1),Be({email:k,code:O});return}}d([I("resetPassword.invalidCode")]),S(!1),setTimeout(()=>_optionalChain([e, 'optionalCall', _21 => _21("forgotPassword")]),3e3)}},[s,m,I,e]),_react.useEffect.call(void 0, ()=>{m&&we&&!No&&(Ye(!0),(async(k,O)=>{try{let N=[{operation:"validatePasswordResetCode",data:{email:k,codePassword:O}}],$=await m.transaction(N);if($.data&&Array.isArray($.data)){let H=$.data[0];if(H&&H.response&&H.response.status==="OK"){de(!0);return}}if($.success)de(!0);else{let ue=_chunkYIIUEOXCjs.g.call(void 0, $).map(Ce);d(ue),setTimeout(()=>_optionalChain([e, 'optionalCall', _22 => _22("forgotPassword")]),3e3)}}catch(N){let H=_chunkYIIUEOXCjs.g.call(void 0, N).map(Ce);d(H),setTimeout(()=>_optionalChain([e, 'optionalCall', _23 => _23("forgotPassword")]),3e3)}finally{S(!1),Be(null),Ye(!1)}})(we.email,we.code))},[m,we,I,e]);let Vo=T=>T.length<8?I("resetPassword.passwordTooShort"):null,Wo=async()=>{if(y||!m)return;d([]),r(null),C(null);let T=!1;if(!n)r(I("resetPassword.newPasswordRequired")),T=!0;else{let k=Vo(n);k&&(r(k),T=!0)}if(p?n!==p&&(C(I("resetPassword.passwordsDoNotMatch")),T=!0):(C(I("resetPassword.confirmPasswordRequired")),T=!0),!T){c(!0);try{let k=[{operation:"validateAndResetPassword",data:{email:P,codePassword:h,newPassword:n}}],O=await m.transaction(k);if(O.success)d([]),setTimeout(()=>{_optionalChain([a, 'optionalCall', _24 => _24()])},1e3);else{let $=_chunkYIIUEOXCjs.g.call(void 0, O).map(Ce);d($)}}catch(k){let N=_chunkYIIUEOXCjs.g.call(void 0, k).map(Ce);d(N),t&&t(N.join(", "))}c(!1)}},Uo=()=>{v?_optionalChain([e, 'optionalCall', _25 => _25("checkCode",{email:P})]):_optionalChain([e, 'optionalCall', _26 => _26("forgotPassword")])};return g?_jsxruntime.jsx.call(void 0, _material.Box,{sx:{display:"flex",justifyContent:"center",alignItems:"center",minHeight:"300px"},children:_jsxruntime.jsx.call(void 0, _material.CircularProgress,{})}):J?_jsxruntime.jsxs.call(void 0, _jsxruntime.Fragment,{children:[_jsxruntime.jsxs.call(void 0, _material.Box,{component:"form",noValidate:!0,sx:{width:"100%",display:"flex",flexDirection:"column",gap:2},children:[_jsxruntime.jsxs.call(void 0, _material.Box,{sx:{mb:2},children:[_jsxruntime.jsx.call(void 0, _material.Typography,{variant:"h5",component:"h1",sx:{mb:1,fontWeight:600},children:I("resetPassword.title")}),_jsxruntime.jsx.call(void 0, _material.Typography,{variant:"body2",sx:{color:"grey.600"},children:I("resetPassword.instructions")})]}),_jsxruntime.jsxs.call(void 0, _material.Box,{sx:{mb:1},children:[_jsxruntime.jsx.call(void 0, _material.Typography,{variant:"body2",component:"label",htmlFor:"newPassword",sx:{display:"block",fontWeight:500,color:"grey.700",mb:.5},children:I("resetPassword.newPasswordLabel")}),_jsxruntime.jsx.call(void 0, _material.TextField,{fullWidth:!0,id:"newPassword",name:"newPassword",type:"password",value:n,disabled:y,onChange:T=>i(T.target.value),error:!!o,helperText:o,autoComplete:"new-password",placeholder:I("resetPassword.newPasswordPlaceholder"),required:!0})]}),_jsxruntime.jsxs.call(void 0, _material.Box,{sx:{mb:1},children:[_jsxruntime.jsx.call(void 0, _material.Typography,{variant:"body2",component:"label",htmlFor:"confirmPassword",sx:{display:"block",fontWeight:500,color:"grey.700",mb:.5},children:I("resetPassword.confirmPasswordLabel")}),_jsxruntime.jsx.call(void 0, _material.TextField,{fullWidth:!0,id:"confirmPassword",name:"confirmPassword",type:"password",value:p,disabled:y,onChange:T=>l(T.target.value),error:!!u,helperText:u,autoComplete:"new-password",placeholder:I("resetPassword.confirmPasswordPlaceholder"),required:!0})]}),_jsxruntime.jsx.call(void 0, _material.Button,{disabled:y,type:"button",onClick:Wo,fullWidth:!0,variant:"contained",color:"primary",sx:{mt:2,mb:2},children:y?_jsxruntime.jsx.call(void 0, _material.CircularProgress,{size:20}):I("resetPassword.resetPasswordButton")}),_jsxruntime.jsx.call(void 0, _material.Box,{sx:{display:"flex",justifyContent:"center",alignItems:"center"},children:_jsxruntime.jsx.call(void 0, _material.Link,{sx:{cursor:"pointer"},onClick:Uo,variant:"body2",color:"secondary",children:I("common.back")})})]}),_jsxruntime.jsx.call(void 0, _material.Box,{children:x.length>0&&x.map((T,k)=>_jsxruntime.jsx.call(void 0, _material.Alert,{variant:"filled",sx:{mt:2},severity:"error",children:T},k))})]}):_jsxruntime.jsx.call(void 0, _material.Box,{children:x.length>0&&x.map((T,k)=>_jsxruntime.jsx.call(void 0, _material.Alert,{variant:"filled",sx:{mt:2},severity:"error",children:T},k))})},Po=pr;var Pr=({onScreenChange:e,onError:t,searchParams:s})=>{let{crudify:a}=q(),[m,n]=_react.useState.call(void 0, ""),[i,p]=_react.useState.call(void 0, !1),[l,y]=_react.useState.call(void 0, []),[c,x]=_react.useState.call(void 0, null),[d,o]=_react.useState.call(void 0, ""),{t:r}=U(),u=w=>s?s instanceof URLSearchParams?s.get(w):s[w]||null:null,C=w=>{let v=[`errors.auth.${w.code}`,`errors.data.${w.code}`,`errors.system.${w.code}`,`errors.${w.code}`,`checkCode.${w.code.toLowerCase()}`];for(let E of v){let g=r(E);if(g!==E)return g}return w.message||r("error.unknown")};_react.useEffect.call(void 0, ()=>{let w=u("email");w?o(w):_optionalChain([e, 'optionalCall', _27 => _27("forgotPassword")])},[s,e]);let P=async()=>{if(!(i||!a)){if(y([]),x(null),!m){x(r("checkCode.codeRequired"));return}if(m.length!==6){x(r("checkCode.codeRequired"));return}p(!0);try{let w=[{operation:"validatePasswordResetCode",data:{email:d,codePassword:m}}],v=await a.transaction(w);if(v.success)_optionalChain([e, 'optionalCall', _28 => _28("resetPassword",{email:d,code:m,fromCodeVerification:"true"})]);else{let g=_chunkYIIUEOXCjs.g.call(void 0, v).map(C);y(g),p(!1)}}catch(w){let E=_chunkYIIUEOXCjs.g.call(void 0, w).map(C);y(E),p(!1),t&&t(E.join(", "))}}},f=()=>{_optionalChain([e, 'optionalCall', _29 => _29("forgotPassword")])},h=w=>{let v=w.target.value.replace(/\D/g,"").slice(0,6);n(v)};return _jsxruntime.jsxs.call(void 0, _jsxruntime.Fragment,{children:[_jsxruntime.jsxs.call(void 0, _material.Box,{component:"form",noValidate:!0,sx:{width:"100%",display:"flex",flexDirection:"column",gap:2},children:[_jsxruntime.jsxs.call(void 0, _material.Box,{sx:{mb:2},children:[_jsxruntime.jsx.call(void 0, _material.Typography,{variant:"h5",component:"h1",sx:{mb:1,fontWeight:600},children:r("checkCode.title")}),_jsxruntime.jsx.call(void 0, _material.Typography,{variant:"body2",sx:{color:"grey.600"},children:r("checkCode.instructions")})]}),_jsxruntime.jsxs.call(void 0, _material.Box,{sx:{mb:1},children:[_jsxruntime.jsx.call(void 0, _material.Typography,{variant:"body2",component:"label",htmlFor:"code",sx:{display:"block",fontWeight:500,color:"grey.700",mb:.5},children:r("checkCode.codeLabel")}),_jsxruntime.jsx.call(void 0, _material.TextField,{fullWidth:!0,id:"code",name:"code",type:"text",value:m,disabled:i,onChange:h,error:!!c,helperText:c,placeholder:r("checkCode.codePlaceholder"),inputProps:{maxLength:6,style:{textAlign:"center",fontSize:"1.5rem",letterSpacing:"0.4rem"}},required:!0})]}),_jsxruntime.jsx.call(void 0, _material.Button,{disabled:i||m.length!==6,type:"button",onClick:P,fullWidth:!0,variant:"contained",color:"primary",sx:{mt:2,mb:2},children:i?_jsxruntime.jsx.call(void 0, _material.CircularProgress,{size:20}):r("checkCode.verifyButton")}),_jsxruntime.jsx.call(void 0, _material.Box,{sx:{display:"flex",justifyContent:"center",alignItems:"center"},children:_jsxruntime.jsx.call(void 0, _material.Link,{sx:{cursor:"pointer"},onClick:f,variant:"body2",color:"secondary",children:r("common.back")})})]}),_jsxruntime.jsx.call(void 0, _material.Box,{children:l.length>0&&l.map((w,v)=>_jsxruntime.jsx.call(void 0, _material.Alert,{sx:{mt:2},severity:"error",children:w},v))})]})},vo=Pr;var So=({children:e,fallback:t})=>{let{isLoading:s,error:a,isInitialized:m}=q(),{t:n}=U();return s?t||_jsxruntime.jsxs.call(void 0, _material.Box,{sx:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",minHeight:"200px",gap:2},children:[_jsxruntime.jsx.call(void 0, _material.CircularProgress,{}),_jsxruntime.jsx.call(void 0, _material.Typography,{variant:"body2",color:"text.secondary",children:n("login.initializing")!=="login.initializing"?n("login.initializing"):"Initializing..."})]}):a?_jsxruntime.jsx.call(void 0, _material.Alert,{severity:"error",sx:{mt:2},children:_jsxruntime.jsxs.call(void 0, _material.Typography,{variant:"body2",children:[n("login.initializationError")!=="login.initializationError"?n("login.initializationError"):"Initialization error",":"," ",a]})}):m?_jsxruntime.jsx.call(void 0, _jsxruntime.Fragment,{children:e}):_jsxruntime.jsx.call(void 0, _material.Alert,{severity:"warning",sx:{mt:2},children:_jsxruntime.jsx.call(void 0, _material.Typography,{variant:"body2",children:n("login.notInitialized")!=="login.notInitialized"?n("login.notInitialized"):"System not initialized"})})};var Rr=({onScreenChange:e,onExternalNavigate:t,onLoginSuccess:s,onError:a,redirectUrl:m="/"})=>{let{t:n}=U(),{state:i,setScreen:p}=Te(),{config:l}=_chunkEP4KANK7js.g.call(void 0, ),{showNotification:y}=_chunkEP4KANK7js.e.call(void 0, ),c=(d,o)=>{let r=o;d==="login"?r={}:d==="forgotPassword"&&!o&&(r={}),p(d,r),_optionalChain([e, 'optionalCall', _30 => _30(d,r)])},x=()=>{let d={onScreenChange:c,onExternalNavigate:t,onError:a,redirectUrl:m};switch(i.currentScreen){case"forgotPassword":return _jsxruntime.jsx.call(void 0, xo,{...d});case"checkCode":return _jsxruntime.jsx.call(void 0, vo,{...d,searchParams:i.searchParams});case"resetPassword":return _jsxruntime.jsx.call(void 0, Po,{...d,searchParams:i.searchParams,onResetSuccess:()=>{let o=n("resetPassword.successMessage");y(o,"success"),c("login")}});default:return _jsxruntime.jsx.call(void 0, po,{...d,onLoginSuccess:s})}};return _jsxruntime.jsxs.call(void 0, So,{children:[_jsxruntime.jsx.call(void 0, _material.Box,{sx:{display:"flex",justifyContent:"center",mb:3},children:_jsxruntime.jsx.call(void 0, "img",{src:l.logo||"/nocios-default.png",alt:n("login.logoAlt"),style:{width:"100%",maxWidth:"150px",height:"auto"},onError:d=>{let o=d.target;o.src="/nocios-default.png"}})}),!l.logo&&l.appName&&_jsxruntime.jsx.call(void 0, _material.Typography,{variant:"h6",component:"h1",sx:{textAlign:"center",mb:2},children:l.appName}),x()]})},Ar=({translations:e,translationsUrl:t,language:s="en",initialScreen:a="login",autoReadFromCookies:m=!0,...n})=>{let{config:i}=_chunkEP4KANK7js.g.call(void 0, );return _jsxruntime.jsx.call(void 0, no,{translations:e,translationsUrl:t,language:s,children:_jsxruntime.jsx.call(void 0, so,{config:i,children:_jsxruntime.jsx.call(void 0, uo,{config:i,initialScreen:a,autoReadFromCookies:m,children:_jsxruntime.jsx.call(void 0, Rr,{...n})})})})},Wn= exports.a =Ar;var _iconsmaterial = require('@mui/icons-material');var Gr=({showExtendedData:e=!0,showProfileCard:t=!0,autoRefresh:s=!0})=>{let{userProfile:a,loading:m,error:n,extendedData:i,refreshProfile:p}=_chunkEP4KANK7js.j.call(void 0, {autoFetch:s,retryOnError:!0,maxRetries:3}),[l,y]=_react.useState.call(void 0, !1);if(m)return _jsxruntime.jsxs.call(void 0, _material.Box,{display:"flex",justifyContent:"center",alignItems:"center",p:3,children:[_jsxruntime.jsx.call(void 0, _material.CircularProgress,{}),_jsxruntime.jsx.call(void 0, _material.Typography,{variant:"body2",sx:{ml:2},children:"Cargando perfil de usuario..."})]});if(n)return _jsxruntime.jsxs.call(void 0, _material.Alert,{severity:"error",action:_jsxruntime.jsx.call(void 0, _material.IconButton,{color:"inherit",size:"small",onClick:p,children:_jsxruntime.jsx.call(void 0, _material.Typography,{variant:"caption",children:"Reintentar"})}),children:["Error al cargar el perfil: ",n]});if(!a)return _jsxruntime.jsx.call(void 0, _material.Alert,{severity:"warning",children:"No se encontr\xF3 informaci\xF3n del usuario"});let c=_optionalChain([i, 'optionalAccess', _31 => _31.displayData])||{},x=_optionalChain([i, 'optionalAccess', _32 => _32.totalFields])||0,d=f=>{if(!f)return"No disponible";try{return new Date(f).toLocaleString("es-ES",{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}catch (e5){return f}},o=(f,h)=>h==null?"No disponible":typeof h=="boolean"?h?"S\xED":"No":Array.isArray(h)?h.length>0?h.join(", "):"Ninguno":typeof h=="object"?JSON.stringify(h,null,2):String(h),r=[{key:"id",label:"ID",icon:_jsxruntime.jsx.call(void 0, _iconsmaterial.Badge,{})},{key:"email",label:"Email",icon:_jsxruntime.jsx.call(void 0, _iconsmaterial.Email,{})},{key:"username",label:"Usuario",icon:_jsxruntime.jsx.call(void 0, _iconsmaterial.Person,{})},{key:"fullName",label:"Nombre completo",icon:_jsxruntime.jsx.call(void 0, _iconsmaterial.AccountCircle,{})},{key:"role",label:"Rol",icon:_jsxruntime.jsx.call(void 0, _iconsmaterial.Security,{})}],u=[{key:"firstName",label:"Nombre"},{key:"lastName",label:"Apellido"},{key:"isActive",label:"Activo"},{key:"lastLogin",label:"\xDAltimo login"},{key:"createdAt",label:"Creado"},{key:"updatedAt",label:"Actualizado"}],C=[...r.map(f=>f.key),...u.map(f=>f.key),"permissions"],P=Object.keys(c).filter(f=>!C.includes(f)).map(f=>({key:f,label:f}));return _jsxruntime.jsxs.call(void 0, _material.Box,{children:[t&&_jsxruntime.jsx.call(void 0, _material.Card,{sx:{mb:2},children:_jsxruntime.jsxs.call(void 0, _material.CardContent,{children:[_jsxruntime.jsxs.call(void 0, _material.Box,{display:"flex",alignItems:"center",mb:2,children:[_jsxruntime.jsx.call(void 0, _material.Avatar,{src:c.avatar,sx:{width:56,height:56,mr:2},children:_optionalChain([c, 'access', _33 => _33.fullName, 'optionalAccess', _34 => _34[0]])||_optionalChain([c, 'access', _35 => _35.username, 'optionalAccess', _36 => _36[0]])||_optionalChain([c, 'access', _37 => _37.email, 'optionalAccess', _38 => _38[0]])}),_jsxruntime.jsxs.call(void 0, _material.Box,{children:[_jsxruntime.jsx.call(void 0, _material.Typography,{variant:"h6",children:c.fullName||c.username||c.email}),_jsxruntime.jsx.call(void 0, _material.Typography,{variant:"body2",color:"text.secondary",children:c.role||"Usuario"}),c.isActive!==void 0&&_jsxruntime.jsx.call(void 0, _material.Chip,{label:c.isActive?"Activo":"Inactivo",color:c.isActive?"success":"error",size:"small",sx:{mt:.5}})]})]}),_jsxruntime.jsx.call(void 0, _material.Box,{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(250px, 1fr))",gap:2,children:r.map(({key:f,label:h,icon:w})=>c[f]?_jsxruntime.jsxs.call(void 0, _material.Box,{display:"flex",alignItems:"center",children:[_jsxruntime.jsx.call(void 0, _material.Box,{sx:{mr:1,color:"text.secondary"},children:w}),_jsxruntime.jsxs.call(void 0, _material.Box,{children:[_jsxruntime.jsx.call(void 0, _material.Typography,{variant:"caption",color:"text.secondary",children:h}),_jsxruntime.jsx.call(void 0, _material.Typography,{variant:"body2",children:o(f,c[f])})]})]},f):null)}),c.permissions&&Array.isArray(c.permissions)&&c.permissions.length>0&&_jsxruntime.jsxs.call(void 0, _material.Box,{mt:2,children:[_jsxruntime.jsx.call(void 0, _material.Typography,{variant:"caption",color:"text.secondary",display:"block",children:"Permisos"}),_jsxruntime.jsxs.call(void 0, _material.Box,{display:"flex",flexWrap:"wrap",gap:.5,mt:.5,children:[c.permissions.slice(0,5).map((f,h)=>_jsxruntime.jsx.call(void 0, _material.Chip,{label:f,size:"small",variant:"outlined"},h)),c.permissions.length>5&&_jsxruntime.jsx.call(void 0, _material.Chip,{label:`+${c.permissions.length-5} m\xE1s`,size:"small"})]})]})]})}),e&&_jsxruntime.jsx.call(void 0, _material.Card,{children:_jsxruntime.jsxs.call(void 0, _material.CardContent,{children:[_jsxruntime.jsxs.call(void 0, _material.Box,{display:"flex",justifyContent:"space-between",alignItems:"center",mb:2,children:[_jsxruntime.jsxs.call(void 0, _material.Typography,{variant:"h6",display:"flex",alignItems:"center",children:[_jsxruntime.jsx.call(void 0, _iconsmaterial.Info,{sx:{mr:1}}),"Informaci\xF3n Detallada"]}),_jsxruntime.jsx.call(void 0, _material.Chip,{label:`${x} campos totales`,size:"small"})]}),_jsxruntime.jsxs.call(void 0, _material.List,{dense:!0,children:[u.map(({key:f,label:h})=>c[f]!==void 0&&_jsxruntime.jsxs.call(void 0, _material.ListItem,{divider:!0,children:[_jsxruntime.jsx.call(void 0, _material.ListItemIcon,{children:_jsxruntime.jsx.call(void 0, _iconsmaterial.Schedule,{fontSize:"small"})}),_jsxruntime.jsx.call(void 0, _material.ListItemText,{primary:h,secondary:f.includes("At")||f.includes("Login")?d(c[f]):o(f,c[f])})]},f)),P.length>0&&_jsxruntime.jsxs.call(void 0, _jsxruntime.Fragment,{children:[_jsxruntime.jsx.call(void 0, _material.Divider,{sx:{my:1}}),_jsxruntime.jsx.call(void 0, _material.ListItem,{children:_jsxruntime.jsx.call(void 0, _material.ListItemText,{primary:_jsxruntime.jsxs.call(void 0, _material.Box,{display:"flex",justifyContent:"space-between",alignItems:"center",children:[_jsxruntime.jsxs.call(void 0, _material.Typography,{variant:"subtitle2",children:["Campos Personalizados (",P.length,")"]}),_jsxruntime.jsx.call(void 0, _material.IconButton,{size:"small",onClick:()=>y(!l),children:l?_jsxruntime.jsx.call(void 0, _iconsmaterial.ExpandLess,{}):_jsxruntime.jsx.call(void 0, _iconsmaterial.ExpandMore,{})})]})})}),_jsxruntime.jsx.call(void 0, _material.Collapse,{in:l,children:P.map(({key:f,label:h})=>_jsxruntime.jsx.call(void 0, _material.ListItem,{sx:{pl:4},children:_jsxruntime.jsx.call(void 0, _material.ListItemText,{primary:h,secondary:o(f,c[f])})},f))})]})]}),_jsxruntime.jsxs.call(void 0, _material.Box,{mt:2,display:"flex",justifyContent:"space-between",alignItems:"center",children:[_jsxruntime.jsxs.call(void 0, _material.Typography,{variant:"caption",color:"text.secondary",children:["\xDAltima actualizaci\xF3n: ",d(c.updatedAt)]}),_jsxruntime.jsx.call(void 0, _material.IconButton,{size:"small",onClick:p,disabled:m,children:_jsxruntime.jsx.call(void 0, _material.Typography,{variant:"caption",children:"Actualizar"})})]})]})})]})},Yr= exports.b =Gr;var Ao=["create","read","update","delete"],Io= exports.d =["create","read","update","delete"];var _reacti18next = require('react-i18next');var st=({value:e,onChange:t,availableFields:s,error:a,disabled:m=!1})=>{let{t:n}=_reacti18next.useTranslation.call(void 0, ),[i,p]=_react.useState.call(void 0, "custom"),l=_react.useRef.call(void 0, !1);_react.useEffect.call(void 0, ()=>{let o=e||{allow:[],owner_allow:[],deny:[]},r=new Set(s),u=(o.allow||[]).filter(h=>r.has(h)),C=(o.owner_allow||[]).filter(h=>r.has(h)),P=(o.deny||[]).filter(h=>r.has(h));s.forEach(h=>{!u.includes(h)&&!C.includes(h)&&!P.includes(h)&&P.push(h)});let f={allow:u,owner_allow:C,deny:P};JSON.stringify(f)!==JSON.stringify(o)&&t(f),u.length===s.length?p("all"):P.length===s.length?p("none"):p("custom")},[s,e]);let y=()=>{l.current=!0,t({allow:[...s],owner_allow:[],deny:[]}),p("all"),setTimeout(()=>{l.current=!1},0)},c=()=>{l.current=!0,t({allow:[],owner_allow:[],deny:[...s]}),p("none"),setTimeout(()=>{l.current=!1},0)},x=o=>_optionalChain([e, 'optionalAccess', _39 => _39.allow, 'optionalAccess', _40 => _40.includes, 'call', _41 => _41(o)])?"allow":_optionalChain([e, 'optionalAccess', _42 => _42.owner_allow, 'optionalAccess', _43 => _43.includes, 'call', _44 => _44(o)])?"owner_allow":"deny",d=(o,r)=>{l.current=!0;let u=new Set(_optionalChain([e, 'optionalAccess', _45 => _45.allow])||[]),C=new Set(_optionalChain([e, 'optionalAccess', _46 => _46.owner_allow])||[]),P=new Set(_optionalChain([e, 'optionalAccess', _47 => _47.deny])||[]);u.delete(o),C.delete(o),P.delete(o),r==="allow"&&u.add(o),r==="owner_allow"&&C.add(o),r==="deny"&&P.add(o),t({allow:Array.from(u),owner_allow:Array.from(C),deny:Array.from(P)}),p("custom"),setTimeout(()=>{l.current=!1},0)};return s.length===0?_jsxruntime.jsxs.call(void 0, _material.Box,{children:[_jsxruntime.jsx.call(void 0, _material.Typography,{variant:"body2",color:"text.secondary",sx:{mb:1},children:n("modules.form.publicPolicies.fields.conditions.label")}),_jsxruntime.jsx.call(void 0, _material.Typography,{variant:"body2",color:"text.secondary",sx:{fontStyle:"italic"},children:n("modules.form.publicPolicies.fields.conditions.noFieldsAvailable")}),a&&_jsxruntime.jsx.call(void 0, _material.FormHelperText,{error:!0,sx:{mt:1},children:a})]}):_jsxruntime.jsxs.call(void 0, _material.Box,{children:[_jsxruntime.jsx.call(void 0, _material.Typography,{variant:"body2",color:"text.secondary",sx:{mb:2},children:n("modules.form.publicPolicies.fields.conditions.label")}),_jsxruntime.jsxs.call(void 0, _material.Stack,{direction:"row",spacing:1,sx:{mb:3},children:[_jsxruntime.jsx.call(void 0, _material.Button,{variant:i==="all"?"contained":"outlined",startIcon:_jsxruntime.jsx.call(void 0, _iconsmaterial.SelectAll,{}),onClick:y,disabled:m,size:"small",sx:{minWidth:120,...i==="all"&&{backgroundColor:"#16a34a","&:hover":{backgroundColor:"#15803d"}}},children:n("modules.form.publicPolicies.fields.conditions.allFields")}),_jsxruntime.jsx.call(void 0, _material.Button,{variant:i==="none"?"contained":"outlined",startIcon:_jsxruntime.jsx.call(void 0, _iconsmaterial.ClearAll,{}),onClick:c,disabled:m,size:"small",sx:{minWidth:120,...i==="none"&&{backgroundColor:"#cf222e","&:hover":{backgroundColor:"#bc1f2c"}}},children:n("modules.form.publicPolicies.fields.conditions.noFields")})]}),_jsxruntime.jsxs.call(void 0, _material.Box,{sx:{p:2,border:"1px solid #d1d9e0",borderRadius:1,backgroundColor:"#f6f8fa"},children:[_jsxruntime.jsx.call(void 0, _material.Typography,{variant:"body2",color:"text.secondary",sx:{mb:2},children:n("modules.form.publicPolicies.fields.conditions.help")}),_jsxruntime.jsx.call(void 0, _material.Stack,{spacing:1,children:s.map(o=>{let r=x(o);return _jsxruntime.jsxs.call(void 0, _material.Stack,{direction:"row",spacing:1,alignItems:"center",children:[_jsxruntime.jsx.call(void 0, _material.Typography,{variant:"body2",sx:{minWidth:100,fontFamily:"monospace"},children:o}),_jsxruntime.jsxs.call(void 0, _material.ToggleButtonGroup,{value:r,exclusive:!0,size:"small",children:[_jsxruntime.jsxs.call(void 0, _material.ToggleButton,{value:"allow",onClick:()=>d(o,"allow"),disabled:m,sx:{px:2,color:r==="allow"?"#ffffff":"#6b7280",backgroundColor:r==="allow"?"#16a34a":"#f3f4f6",borderColor:r==="allow"?"#16a34a":"#d1d5db","&:hover":{backgroundColor:r==="allow"?"#15803d":"#e5e7eb",borderColor:r==="allow"?"#15803d":"#9ca3af"},"&.Mui-selected":{backgroundColor:"#16a34a",color:"#ffffff","&:hover":{backgroundColor:"#15803d"}}},children:[_jsxruntime.jsx.call(void 0, _iconsmaterial.CheckCircle,{sx:{fontSize:16,mr:.5}}),n("modules.form.publicPolicies.fields.conditions.states.allow")]}),_jsxruntime.jsx.call(void 0, _material.ToggleButton,{value:"owner_allow",onClick:()=>d(o,"owner_allow"),disabled:m,sx:{px:2,color:r==="owner_allow"?"#ffffff":"#6b7280",backgroundColor:r==="owner_allow"?"#0ea5e9":"#f3f4f6",borderColor:r==="owner_allow"?"#0ea5e9":"#d1d5db","&:hover":{backgroundColor:r==="owner_allow"?"#0284c7":"#e5e7eb",borderColor:r==="owner_allow"?"#0284c7":"#9ca3af"},"&.Mui-selected":{backgroundColor:"#0ea5e9",color:"#ffffff","&:hover":{backgroundColor:"#0284c7"}}},children:n("modules.form.publicPolicies.fields.conditions.states.ownerAllow")}),_jsxruntime.jsxs.call(void 0, _material.ToggleButton,{value:"deny",onClick:()=>d(o,"deny"),disabled:m,sx:{px:2,color:r==="deny"?"#ffffff":"#6b7280",backgroundColor:r==="deny"?"#dc2626":"#f3f4f6",borderColor:r==="deny"?"#dc2626":"#d1d5db","&:hover":{backgroundColor:r==="deny"?"#b91c1c":"#e5e7eb",borderColor:r==="deny"?"#b91c1c":"#9ca3af"},"&.Mui-selected":{backgroundColor:"#dc2626",color:"#ffffff","&:hover":{backgroundColor:"#b91c1c"}}},children:[_jsxruntime.jsx.call(void 0, _iconsmaterial.Cancel,{sx:{fontSize:16,mr:.5}}),n("modules.form.publicPolicies.fields.conditions.states.deny")]})]})]},o)})})]}),a&&_jsxruntime.jsx.call(void 0, _material.FormHelperText,{error:!0,sx:{mt:1},children:a})]})},He=st;var bt=_react.forwardRef.call(void 0, ({policy:e,onChange:t,onRemove:s,availableFields:a,isSubmitting:m=!1,usedActions:n,error:i},p)=>{let{t:l}=_reacti18next.useTranslation.call(void 0, ),y=new Set(Array.from(n||[]));y.delete(e.action);let c=Ao.map(x=>({value:x,label:l(`modules.form.publicPolicies.fields.action.options.${x}`)}));return _jsxruntime.jsxs.call(void 0, _material.Paper,{ref:p,sx:{p:3,border:"1px solid #d1d9e0",borderRadius:2,position:"relative",backgroundColor:"#ffffff"},children:[_jsxruntime.jsxs.call(void 0, _material.Box,{sx:{display:"flex",justifyContent:"space-between",alignItems:"flex-start",mb:3},children:[_jsxruntime.jsx.call(void 0, _material.Typography,{variant:"subtitle1",sx:{fontWeight:600,color:"#111418",fontSize:"1rem"},children:l("modules.form.publicPolicies.policyTitle")}),_jsxruntime.jsx.call(void 0, _material.IconButton,{onClick:s,size:"small",disabled:m,"aria-label":l("modules.form.publicPolicies.removePolicy"),sx:{color:"#656d76","&:hover":{color:"#cf222e",backgroundColor:"rgba(207, 34, 46, 0.1)"}},children:_jsxruntime.jsx.call(void 0, _iconsmaterial.Delete,{})})]}),_jsxruntime.jsxs.call(void 0, _material.Stack,{spacing:3,children:[_jsxruntime.jsx.call(void 0, _material.Stack,{direction:{xs:"column",md:"row"},spacing:2,children:_jsxruntime.jsx.call(void 0, _material.Box,{sx:{flex:1,minWidth:200},children:_jsxruntime.jsxs.call(void 0, _material.FormControl,{fullWidth:!0,children:[_jsxruntime.jsx.call(void 0, _material.InputLabel,{children:l("modules.form.publicPolicies.fields.action.label")}),_jsxruntime.jsx.call(void 0, _material.Select,{value:e.action,label:l("modules.form.publicPolicies.fields.action.label"),disabled:m,onChange:x=>{let d=x.target.value,o={...e,action:d};d==="delete"?(o.permission="deny",delete o.fields):(o.fields={allow:[],owner_allow:[],deny:a},delete o.permission),t(o)},sx:{backgroundColor:"#ffffff","&:hover .MuiOutlinedInput-notchedOutline":{borderColor:"#8c959f"},"&.Mui-focused .MuiOutlinedInput-notchedOutline":{borderColor:"#0969da",borderWidth:2}},children:c.map(x=>{let d=y.has(x.value);return _jsxruntime.jsx.call(void 0, _material.MenuItem,{value:x.value,disabled:d,children:x.label},x.value)})}),i&&_jsxruntime.jsx.call(void 0, _material.FormHelperText,{error:!0,children:i})]})})}),e.action==="delete"?_jsxruntime.jsxs.call(void 0, _material.Box,{children:[_jsxruntime.jsx.call(void 0, _material.Typography,{variant:"body2",color:"text.secondary",sx:{mb:2},children:l("modules.form.publicPolicies.fields.conditions.label")}),_jsxruntime.jsxs.call(void 0, _material.Stack,{direction:"row",spacing:1,sx:{mb:3},children:[_jsxruntime.jsx.call(void 0, _material.Button,{variant:e.permission==="*"?"contained":"outlined",startIcon:_jsxruntime.jsx.call(void 0, _iconsmaterial.SelectAll,{}),onClick:()=>t({...e,permission:"*"}),disabled:m,size:"small",sx:{minWidth:140,whiteSpace:"nowrap",...e.permission==="*"&&{backgroundColor:"#16a34a","&:hover":{backgroundColor:"#15803d"}}},children:l("modules.form.publicPolicies.fields.conditions.allFields")}),_jsxruntime.jsx.call(void 0, _material.Button,{variant:e.permission==="owner"?"contained":"outlined",onClick:()=>t({...e,permission:"owner"}),disabled:m,size:"small",sx:{minWidth:140,whiteSpace:"nowrap",...e.permission==="owner"&&{backgroundColor:"#0ea5e9","&:hover":{backgroundColor:"#0284c7"}}},children:l("modules.form.publicPolicies.fields.conditions.states.ownerAllow")}),_jsxruntime.jsx.call(void 0, _material.Button,{variant:e.permission==="deny"?"contained":"outlined",startIcon:_jsxruntime.jsx.call(void 0, _iconsmaterial.ClearAll,{}),onClick:()=>t({...e,permission:"deny"}),disabled:m,size:"small",sx:{minWidth:140,whiteSpace:"nowrap",...e.permission==="deny"&&{backgroundColor:"#cf222e","&:hover":{backgroundColor:"#bc1f2c"}}},children:l("modules.form.publicPolicies.fields.conditions.noFields")})]})]}):_jsxruntime.jsx.call(void 0, He,{value:e.fields||{allow:[],owner_allow:[],deny:[]},onChange:x=>t({...e,fields:x}),availableFields:a,disabled:m}),_jsxruntime.jsx.call(void 0, _material.Paper,{variant:"outlined",sx:{p:2,backgroundColor:"#f9fafb"},children:e.action==="delete"?_jsxruntime.jsxs.call(void 0, _material.Typography,{variant:"body2",sx:{fontFamily:"monospace",color:"text.secondary"},children:[_jsxruntime.jsxs.call(void 0, _material.Box,{component:"span",sx:{color:e.permission==="*"?"#16a34a":e.permission==="owner"?"#0ea5e9":"#dc2626"},children:[l("modules.form.publicPolicies.fields.conditions.states.allow"),":"]})," ",e.permission||"-"]}):_jsxruntime.jsxs.call(void 0, _material.Stack,{spacing:.5,divider:_jsxruntime.jsx.call(void 0, _material.Divider,{sx:{borderColor:"#e5e7eb"}}),children:[_jsxruntime.jsxs.call(void 0, _material.Typography,{variant:"body2",sx:{fontFamily:"monospace",color:"text.secondary"},children:[_jsxruntime.jsxs.call(void 0, _material.Box,{component:"span",sx:{color:"#16a34a"},children:[l("modules.form.publicPolicies.fields.conditions.states.allow"),":"]})," ",(_optionalChain([e, 'optionalAccess', _48 => _48.fields, 'optionalAccess', _49 => _49.allow])||[]).join(", ")||"-"]}),_jsxruntime.jsxs.call(void 0, _material.Typography,{variant:"body2",sx:{fontFamily:"monospace",color:"text.secondary"},children:[_jsxruntime.jsxs.call(void 0, _material.Box,{component:"span",sx:{color:"#0ea5e9"},children:[l("modules.form.publicPolicies.fields.conditions.states.ownerAllow"),":"]})," ",(_optionalChain([e, 'optionalAccess', _50 => _50.fields, 'optionalAccess', _51 => _51.owner_allow])||[]).join(", ")||"-"]}),_jsxruntime.jsxs.call(void 0, _material.Typography,{variant:"body2",sx:{fontFamily:"monospace",color:"text.secondary"},children:[_jsxruntime.jsxs.call(void 0, _material.Box,{component:"span",sx:{color:"#dc2626"},children:[l("modules.form.publicPolicies.fields.conditions.states.deny"),":"]})," ",(_optionalChain([e, 'optionalAccess', _52 => _52.fields, 'optionalAccess', _53 => _53.deny])||[]).join(", ")||"-"]})]})})]})]})}),je=bt;var St=()=>{let e=_optionalChain([globalThis, 'optionalAccess', _54 => _54.crypto]);return e&&typeof e.randomUUID=="function"?e.randomUUID():`${Date.now()}-${Math.random().toString(16).slice(2)}`},kt=({policies:e,onChange:t,availableFields:s,errors:a,isSubmitting:m=!1})=>{let{t:n}=_reacti18next.useTranslation.call(void 0, ),i=_react.useRef.call(void 0, {}),p=new Set((e||[]).map(r=>r.action).filter(Boolean)),l=Io.filter(r=>!p.has(r)),y=l.length>0,c=()=>{let r=l[0]||"create",u={id:St(),action:r};r==="delete"?u.permission="deny":u.fields={allow:[],owner_allow:[],deny:s};let C=[...e||[],u];t(C),setTimeout(()=>{let P=C.length-1,f=i.current[P];f&&f.scrollIntoView({behavior:"smooth",block:"center"})},100)},x=r=>{let u=[...e];u.splice(r,1),t(u)},d=(()=>{if(!a)return null;if(typeof a=="string")return a;let r=a._error;return typeof r=="string"?r:null})(),o=new Set((e||[]).map(r=>r.action));return _jsxruntime.jsxs.call(void 0, _jsxruntime.Fragment,{children:[_jsxruntime.jsx.call(void 0, _material.Divider,{sx:{borderColor:"#e0e4e7"}}),_jsxruntime.jsxs.call(void 0, _material.Box,{children:[_jsxruntime.jsx.call(void 0, _material.Box,{display:"flex",justifyContent:"space-between",alignItems:"center",mb:3,children:_jsxruntime.jsxs.call(void 0, _material.Box,{children:[_jsxruntime.jsx.call(void 0, _material.Typography,{variant:"h6",sx:{fontWeight:600,color:"#111418",mb:1},children:n("modules.form.publicPolicies.title")}),_jsxruntime.jsx.call(void 0, _material.Typography,{variant:"body2",color:"text.secondary",sx:{fontSize:"0.875rem"},children:n("modules.form.publicPolicies.description")})]})}),d&&_jsxruntime.jsx.call(void 0, _material.Alert,{severity:"error",sx:{mb:3},children:d}),_jsxruntime.jsxs.call(void 0, _material.Stack,{spacing:3,children:[(e||[]).length===0?_jsxruntime.jsx.call(void 0, _material.Alert,{severity:"info",children:n("modules.form.publicPolicies.noPolicies")}):e.map((r,u)=>_jsxruntime.jsx.call(void 0, je,{ref:C=>{i.current[u]=C},policy:r,onChange:C=>{let P=[...e];P[u]=C,t(P)},onRemove:()=>x(u),availableFields:s,isSubmitting:m,usedActions:o,error:typeof a=="object"&&a&&r.id in a?a[r.id]:void 0},r.id)),y&&_jsxruntime.jsx.call(void 0, _material.Box,{children:_jsxruntime.jsx.call(void 0, _material.Button,{type:"button",variant:"outlined",startIcon:_jsxruntime.jsx.call(void 0, _iconsmaterial.Add,{}),onClick:c,disabled:m,sx:{borderColor:"#d0d7de",color:"#656d76","&:hover":{borderColor:"#8c959f",backgroundColor:"transparent"}},children:n("modules.form.publicPolicies.addPolicy")})})]})]})]})},Ti= exports.e =kt;function Ii(){let[e,t]=_react.useState.call(void 0, ""),[s,a]=_react.useState.call(void 0, ""),[m,n]=_react.useState.call(void 0, !1),{isAuthenticated:i,isLoading:p,error:l,login:y,logout:c,refreshTokens:x,clearError:d,isExpiringSoon:o,expiresIn:r}=_chunkEP4KANK7js.g.call(void 0, ),u=async f=>{if(f.preventDefault(),!e||!s)return;(await y(e,s)).success&&(t(""),a(""),n(!1))},C=async()=>{await c()},P=async()=>{await x()};return i?_jsxruntime.jsxs.call(void 0, _material.Box,{sx:{maxWidth:600,mx:"auto",p:3},children:[_jsxruntime.jsx.call(void 0, _material.Typography,{variant:"h4",gutterBottom:!0,children:"Welcome! \u{1F389}"}),_jsxruntime.jsx.call(void 0, _material.Alert,{severity:"success",sx:{mb:3},children:"You are successfully logged in with Refresh Token Pattern enabled"}),_jsxruntime.jsxs.call(void 0, _material.Box,{sx:{mb:3,p:2,bgcolor:"background.paper",border:1,borderColor:"divider",borderRadius:1},children:[_jsxruntime.jsx.call(void 0, _material.Typography,{variant:"h6",gutterBottom:!0,children:"Token Status"}),_jsxruntime.jsxs.call(void 0, _material.Typography,{variant:"body2",color:"text.secondary",children:["Access Token expires in: ",Math.round(r/1e3/60)," minutes"]}),o&&_jsxruntime.jsx.call(void 0, _material.Alert,{severity:"warning",sx:{mt:1},children:"Token expires soon - automatic refresh will happen"})]}),_jsxruntime.jsxs.call(void 0, _material.Box,{sx:{display:"flex",gap:2,flexWrap:"wrap"},children:[_jsxruntime.jsx.call(void 0, _material.Button,{variant:"contained",onClick:P,disabled:p,startIcon:p?_jsxruntime.jsx.call(void 0, _material.CircularProgress,{size:16}):null,children:"Refresh Tokens"}),_jsxruntime.jsx.call(void 0, _material.Button,{variant:"outlined",color:"error",onClick:C,disabled:p,children:"Logout"})]}),l&&_jsxruntime.jsx.call(void 0, _material.Alert,{severity:"error",sx:{mt:2},onClose:d,children:l})]}):_jsxruntime.jsxs.call(void 0, _material.Box,{sx:{maxWidth:400,mx:"auto",p:3},children:[_jsxruntime.jsx.call(void 0, _material.Typography,{variant:"h4",gutterBottom:!0,align:"center",children:"Login with Refresh Tokens"}),_jsxruntime.jsx.call(void 0, _material.Alert,{severity:"info",sx:{mb:3},children:"This demo shows the new Refresh Token Pattern with automatic session management"}),m?_jsxruntime.jsxs.call(void 0, "form",{onSubmit:u,children:[_jsxruntime.jsx.call(void 0, _material.TextField,{fullWidth:!0,label:"Email",type:"email",value:e,onChange:f=>t(f.target.value),margin:"normal",required:!0,autoComplete:"email"}),_jsxruntime.jsx.call(void 0, _material.TextField,{fullWidth:!0,label:"Password",type:"password",value:s,onChange:f=>a(f.target.value),margin:"normal",required:!0,autoComplete:"current-password"}),_jsxruntime.jsx.call(void 0, _material.Button,{type:"submit",fullWidth:!0,variant:"contained",size:"large",disabled:p,startIcon:p?_jsxruntime.jsx.call(void 0, _material.CircularProgress,{size:16}):null,sx:{mt:3,mb:2},children:p?"Logging in...":"Login"})]}):_jsxruntime.jsx.call(void 0, _material.Button,{fullWidth:!0,variant:"contained",size:"large",onClick:()=>n(!0),sx:{mt:2},children:"Show Login Form"}),l&&_jsxruntime.jsx.call(void 0, _material.Alert,{severity:"error",sx:{mt:2},onClose:d,children:l})]})}function Bi(){let{isAuthenticated:e,isLoading:t,isExpiringSoon:s,expiresIn:a}=_chunkEP4KANK7js.g.call(void 0, );return t?_jsxruntime.jsxs.call(void 0, _material.Box,{sx:{display:"flex",alignItems:"center",gap:1},children:[_jsxruntime.jsx.call(void 0, _material.CircularProgress,{size:16}),_jsxruntime.jsx.call(void 0, _material.Typography,{variant:"caption",children:"Loading session..."})]}):e?_jsxruntime.jsxs.call(void 0, _material.Box,{children:[_jsxruntime.jsx.call(void 0, _material.Typography,{variant:"caption",color:"success.main",children:"\u2713 Authenticated"}),s&&_jsxruntime.jsxs.call(void 0, _material.Typography,{variant:"caption",color:"warning.main",display:"block",children:["\u26A0 Token expires in ",Math.round(a/1e3/60)," min"]})]}):_jsxruntime.jsx.call(void 0, _material.Typography,{variant:"caption",color:"text.secondary",children:"Not logged in"})}exports.a = Wn; exports.b = Yr; exports.c = Ao; exports.d = Io; exports.e = Ti; exports.f = Ii; exports.g = Bi;
|
|
1
|
+
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } 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 _chunk2OSNNNIDjs = require('./chunk-2OSNNNID.js');var _chunkYIIUEOXCjs = require('./chunk-YIIUEOXC.js');var _chunk6EBMA4HZjs = require('./chunk-6EBMA4HZ.js');var _material = require('@mui/material');var _react = require('react');var eo=(e,t)=>{let[s,a]=_react.useState.call(void 0, {}),[m,n]=_react.useState.call(void 0, !1),[i,p]=_react.useState.call(void 0, null);return _react.useEffect.call(void 0, ()=>{if(console.log("\u{1F527} [I18nProvider] Hybrid translation loading:",{hasProvidedTranslations:!!t&&Object.keys(t).length>0,hasUrl:!!e,providedKeys:t?Object.keys(t).length:0}),t&&Object.keys(t).length>0){console.log("\u2705 [I18nProvider] Using provided translations (highest priority)"),a(t),n(!1),p(null);return}if(!e){console.log("\u26A0\uFE0F [I18nProvider] No translations provided, using empty object (keys will show as-is)"),a({}),n(!1),p(null);return}console.log("\u{1F310} [I18nProvider] Loading translations from URL:",e);let l=!1;return n(!0),p(null),fetch(e).then(y=>{if(!y.ok)throw new Error(`Failed to load translations: ${y.status}`);return y.json()}).then(y=>{l||(console.log("\u2705 [I18nProvider] Translations loaded successfully from URL:",{url:e,keysLoaded:Object.keys(y).length}),a(y),n(!1))}).catch(y=>{l||(console.error("\u274C [I18nProvider] Failed to load translations from URL:",e,y),p(y.message),console.log("\u{1F504} [I18nProvider] Falling back to empty translations (keys will show as-is)"),a({}),n(!1))}),()=>{l=!0}},[e,t]),{translations:s,loading:m,error:i}};var _jsxruntime = require('react/jsx-runtime');var to=_react.createContext.call(void 0, null),Ko=(e,t)=>e&&e[t]?e[t]:t.split(".").reduce((s,a)=>s&&typeof s=="object"?s[a]:void 0,e),no=({children:e,translations:t,translationsUrl:s,language:a="en"})=>{let{translations:m,loading:n}=eo(s,t),i=_react.useMemo.call(void 0, ()=>(l,y)=>{let c=Ko(m,l);return c==null&&(console.log(`\u{1F50D} [I18nProvider] Translation not found for key: "${l}" - showing key as-is`),c=l),y&&typeof c=="string"&&Object.entries(y).forEach(([x,d])=>{c=c.replace(new RegExp(`{{${x}}}`,"g"),d)}),typeof c=="string"?c:l},[m]),p=_react.useMemo.call(void 0, ()=>({t:i,language:a}),[i,a]);return n?_jsxruntime.jsx.call(void 0, "div",{children:"Loading translations..."}):_jsxruntime.jsx.call(void 0, to.Provider,{value:p,children:e})},U=()=>{let e=_react.useContext.call(void 0, to);if(!e)throw new Error("useTranslation must be used within I18nProvider");return e};var _crudifybrowser = require('@nocios/crudify-browser'); var _crudifybrowser2 = _interopRequireDefault(_crudifybrowser);var io=_react.createContext.call(void 0, void 0),so=({config:e,children:t})=>{let[s,a]=_react.useState.call(void 0, !0),[m,n]=_react.useState.call(void 0, null),[i,p]=_react.useState.call(void 0, !1),[l,y]=_react.useState.call(void 0, "");console.log("\u{1F50D} CrudifyProvider - Received config:",e),_react.useEffect.call(void 0, ()=>{if(console.log("\u{1F50D} CrudifyProvider - useEffect - config.publicApiKey:",e.publicApiKey),console.log("\u{1F50D} CrudifyProvider - useEffect - full config:",e),!e.publicApiKey){console.log("\u274C CrudifyProvider - No publicApiKey provided, setting error"),n("No publicApiKey provided"),a(!1),p(!1);return}console.log("\u2705 CrudifyProvider - publicApiKey found, proceeding with initialization");let x=`${e.publicApiKey}-${e.env}`;if(x===l&&i){a(!1);return}(async()=>{a(!0),n(null),p(!1);try{if(_crudifybrowser2.default.config(e.env||"prod"),await _crudifybrowser2.default.init(e.publicApiKey,"none"),typeof _crudifybrowser2.default.transaction=="function"&&typeof _crudifybrowser2.default.login=="function")p(!0),y(x);else throw new Error("Crudify methods not properly initialized")}catch(o){let r=o instanceof Error?o.message:"Failed to initialize Crudify";n(r),p(!1)}finally{a(!1)}})()},[e.publicApiKey,e.env,l,i]);let c={crudify:i?_crudifybrowser2.default:null,isLoading:s,error:m,isInitialized:i};return _jsxruntime.jsx.call(void 0, io.Provider,{value:c,children:t})},q=()=>{let e=_react.useContext.call(void 0, io);if(e===void 0)throw new Error("useCrudify must be used within a CrudifyProvider");return e};var lo={currentScreen:"login",searchParams:{},formData:{username:"",password:"",email:"",code:"",newPassword:"",confirmPassword:""},loading:!1,errors:{global:[]},emailSent:!1,codeAlreadyExists:!1,codeValidated:!1,fromCodeVerification:!1,config:{}};function Zo(e,t){switch(t.type){case"SET_SCREEN":let s={...e,currentScreen:t.payload.screen,searchParams:t.payload.params||e.searchParams,errors:{global:[]}},a=new URLSearchParams(s.searchParams),m=a.toString()?`?${a.toString()}`:window.location.pathname;try{window.history.replaceState({},"",m)}catch (e2){}return s;case"SET_SEARCH_PARAMS":return{...e,searchParams:t.payload};case"UPDATE_FORM_DATA":return{...e,formData:{...e.formData,...t.payload},errors:{...e.errors,...Object.keys(t.payload).reduce((n,i)=>({...n,[i]:void 0}),{})}};case"SET_LOADING":return{...e,loading:t.payload};case"SET_ERRORS":return{...e,errors:{...e.errors,...t.payload}};case"CLEAR_ERRORS":return{...e,errors:{global:[]}};case"SET_EMAIL_SENT":return{...e,emailSent:t.payload};case"SET_CODE_ALREADY_EXISTS":return{...e,codeAlreadyExists:t.payload};case"SET_CODE_VALIDATED":return{...e,codeValidated:t.payload};case"SET_FROM_CODE_VERIFICATION":return{...e,fromCodeVerification:t.payload};case"RESET_FORM":return{...e,formData:lo.formData,errors:{global:[]},loading:!1,emailSent:!1,codeAlreadyExists:!1,codeValidated:!1,fromCodeVerification:!1};case"INIT_CONFIG":return{...e,config:t.payload};default:return e}}var co=_react.createContext.call(void 0, void 0),uo=({children:e,initialScreen:t="login",config:s,autoReadFromCookies:a=!0})=>{let[m,n]=_react.useReducer.call(void 0, Zo,{...lo,currentScreen:t});_react.useEffect.call(void 0, ()=>{n({type:"INIT_CONFIG",payload:(()=>{let o={};if(a)try{let r=_chunk6EBMA4HZjs.a.call(void 0, "logo");if(r){let u=decodeURIComponent(r);u.startsWith("http")&&(o.logo=u)}}catch(r){console.error("Error reading configuration from cookies:",r)}return{publicApiKey:_optionalChain([s, 'optionalAccess', _2 => _2.publicApiKey]),env:_optionalChain([s, 'optionalAccess', _3 => _3.env]),appName:_optionalChain([s, 'optionalAccess', _4 => _4.appName]),logo:_optionalChain([s, 'optionalAccess', _5 => _5.logo])||o.logo,loginActions:_optionalChain([s, 'optionalAccess', _6 => _6.loginActions])}})()})},[s,a]),_react.useEffect.call(void 0, ()=>{let d=new URLSearchParams(window.location.search),o={};d.forEach((r,u)=>{o[u]=r}),Object.keys(o).length>0&&n({type:"SET_SEARCH_PARAMS",payload:o}),t==="checkCode"&&o.email&&n({type:"UPDATE_FORM_DATA",payload:{email:o.email,code:o.code||""}}),t==="resetPassword"&&o.link&&n({type:"SET_SEARCH_PARAMS",payload:o})},[t]);let x={state:m,dispatch:n,setScreen:(d,o)=>{n({type:"SET_SCREEN",payload:{screen:d,params:o}})},updateFormData:d=>{n({type:"UPDATE_FORM_DATA",payload:d})},setFieldError:(d,o)=>{n({type:"SET_ERRORS",payload:{[d]:o}})},clearErrors:()=>{n({type:"CLEAR_ERRORS"})},setLoading:d=>{n({type:"SET_LOADING",payload:d})}};return _jsxruntime.jsx.call(void 0, co.Provider,{value:x,children:e})},Te=()=>{let e=_react.useContext.call(void 0, co);if(e===void 0)throw new Error("useLoginState must be used within a LoginStateProvider");return e};var sr=({onScreenChange:e,onExternalNavigate:t,onLoginSuccess:s,onError:a,redirectUrl:m="/"})=>{let{crudify:n}=q(),{state:i,updateFormData:p,setFieldError:l,clearErrors:y,setLoading:c}=Te(),{login:x}=_chunk2OSNNNIDjs.g.call(void 0, ),d=U(),{t:o}=d,r=d.i18n,u=_react.useRef.call(void 0, null),C=_chunk6EBMA4HZjs.e.call(void 0, o,{currentLanguage:_optionalChain([r, 'optionalAccess', _7 => _7.language]),enableDebug:!1}),P=()=>{if(i.searchParams.redirect)try{let g=decodeURIComponent(i.searchParams.redirect);if(g.startsWith("/")&&!g.startsWith("//"))return g}catch (e3){}return m||"/"};_react.useEffect.call(void 0, ()=>{let g=setTimeout(()=>{u.current&&u.current.focus()},100);return()=>clearTimeout(g)},[]);let f=g=>{console.log("\u{1F50D} [LoginForm] Translating parsed error:",g);let S=C.translateError({code:g.code,message:g.message,field:g.field});return console.log("\u{1F50D} [LoginForm] Translation result:",S),S},h=async()=>{if(!i.loading){if(!i.formData.username.trim()){l("username",o("login.usernameRequired"));return}if(!i.formData.password.trim()){l("password",o("login.passwordRequired"));return}y(),c(!0);try{let g=await x(i.formData.username,i.formData.password);if(c(!1),g.success){console.log("\u{1F510} LoginForm - Login successful via SessionProvider, calling onLoginSuccess");let S=P();s&&s(g.data,S)}else{let S=g.rawResponse||g;w(S)}}catch(g){c(!1);let J=_chunkYIIUEOXCjs.g.call(void 0, g).map(f);l("global",J),a&&a(J.join(", "))}}},w=g=>{_chunkYIIUEOXCjs.g.call(void 0, g).forEach(J=>{if(J.field)l(J.field,f(J));else{let de=i.errors.global||[];l("global",[...de,f(J)])}})};return _jsxruntime.jsxs.call(void 0, _jsxruntime.Fragment,{children:[_jsxruntime.jsxs.call(void 0, _material.Box,{component:"form",noValidate:!0,onSubmit:g=>{g.preventDefault(),h()},onKeyDown:g=>{g.key==="Enter"&&!i.loading&&(g.preventDefault(),h())},sx:{width:"100%",display:"flex",flexDirection:"column",gap:2},children:[_jsxruntime.jsxs.call(void 0, _material.Box,{sx:{mb:1},children:[_jsxruntime.jsx.call(void 0, _material.Typography,{variant:"body2",component:"label",htmlFor:"email",sx:{display:"block",fontWeight:500,color:"grey.700",mb:.5},children:o("login.usernameOrEmailLabel")}),_jsxruntime.jsx.call(void 0, _material.TextField,{fullWidth:!0,id:"email",name:"email",type:"email",value:i.formData.username,disabled:i.loading,onChange:g=>p({username:g.target.value}),error:!!i.errors.username,helperText:i.errors.username,autoComplete:"email",placeholder:o("login.usernameOrEmailPlaceholder"),inputRef:u,required:!0})]}),_jsxruntime.jsxs.call(void 0, _material.Box,{sx:{mb:1},children:[_jsxruntime.jsx.call(void 0, _material.Typography,{variant:"body2",component:"label",htmlFor:"password",sx:{display:"block",fontWeight:500,color:"grey.700",mb:.5},children:o("login.passwordLabel")}),_jsxruntime.jsx.call(void 0, _material.TextField,{fullWidth:!0,id:"password",name:"password",type:"password",value:i.formData.password,disabled:i.loading,onChange:g=>p({password:g.target.value}),error:!!i.errors.password,helperText:i.errors.password,autoComplete:"current-password",placeholder:o("login.passwordPlaceholder"),required:!0})]}),_optionalChain([i, 'access', _8 => _8.config, 'access', _9 => _9.loginActions, 'optionalAccess', _10 => _10.includes, 'call', _11 => _11("forgotPassword")])&&_jsxruntime.jsx.call(void 0, _material.Box,{sx:{display:"flex",justifyContent:"flex-end",alignItems:"center"},children:_jsxruntime.jsx.call(void 0, _material.Link,{sx:{cursor:"pointer"},onClick:()=>{_optionalChain([e, 'optionalCall', _12 => _12("forgotPassword",i.searchParams)])},variant:"body2",color:"secondary",children:o("login.forgotPasswordLink")})}),_jsxruntime.jsx.call(void 0, _material.Button,{disabled:i.loading,type:"submit",fullWidth:!0,variant:"contained",color:"primary",sx:{mt:1,mb:2},children:i.loading?_jsxruntime.jsx.call(void 0, _material.CircularProgress,{size:20}):o("login.loginButton")})]}),_jsxruntime.jsx.call(void 0, _material.Box,{children:i.errors.global&&i.errors.global.length>0&&i.errors.global.map((g,S)=>_jsxruntime.jsx.call(void 0, _material.Alert,{variant:"filled",sx:{mt:2},severity:"error",children:_jsxruntime.jsx.call(void 0, "div",{children:g})},S))}),_optionalChain([i, 'access', _13 => _13.config, 'access', _14 => _14.loginActions, 'optionalAccess', _15 => _15.includes, 'call', _16 => _16("createUser")])&&_jsxruntime.jsxs.call(void 0, _material.Typography,{variant:"body2",align:"center",sx:{color:"text.secondary",mt:3},children:[o("login.noAccountPrompt")," ",_jsxruntime.jsx.call(void 0, _material.Link,{sx:{cursor:"pointer"},onClick:()=>{let S=`/public/users/create${Object.keys(i.searchParams).length>0?`?${new URLSearchParams(i.searchParams).toString()}`:""}`;_optionalChain([t, 'optionalCall', _17 => _17(S)])},fontWeight:"medium",color:"secondary",children:o("login.signUpLink")})]})]})},po=sr;var ur=({onScreenChange:e,onError:t})=>{let{crudify:s}=q(),[a,m]=_react.useState.call(void 0, ""),[n,i]=_react.useState.call(void 0, !1),[p,l]=_react.useState.call(void 0, []),[y,c]=_react.useState.call(void 0, null),[x,d]=_react.useState.call(void 0, !1),[o,r]=_react.useState.call(void 0, !1),{t:u}=U(),C=v=>{let E=[`errors.auth.${v.code}`,`errors.data.${v.code}`,`errors.system.${v.code}`,`errors.${v.code}`,`forgotPassword.${v.code.toLowerCase()}`];for(let g of E){let S=u(g);if(S!==g)return S}return v.message||u("error.unknown")},P=v=>/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(v),f=async()=>{if(!(n||!s)){if(l([]),c(null),!a){c(u("forgotPassword.emailRequired"));return}if(!P(a)){c(u("forgotPassword.invalidEmail"));return}i(!0);try{let v=[{operation:"requestPasswordReset",data:{email:a}}],E=await s.transaction(v);if(E.success)E.data&&E.data.existingCodeValid?r(!0):d(!0);else{let S=_chunkYIIUEOXCjs.g.call(void 0, E).map(C);l(S)}}catch(v){let g=_chunkYIIUEOXCjs.g.call(void 0, v).map(C);l(g),t&&t(g.join(", "))}finally{i(!1)}}},h=()=>{_optionalChain([e, 'optionalCall', _18 => _18("login")])},w=()=>{if(x||o){_optionalChain([e, 'optionalCall', _19 => _19("checkCode",{email:a})]);return}if(!a){c(u("forgotPassword.emailRequired"));return}if(!P(a)){c(u("forgotPassword.invalidEmail"));return}_optionalChain([e, 'optionalCall', _20 => _20("checkCode",{email:a})])};return x||o?_jsxruntime.jsx.call(void 0, _jsxruntime.Fragment,{children:_jsxruntime.jsxs.call(void 0, _material.Box,{sx:{width:"100%",display:"flex",flexDirection:"column",gap:2,textAlign:"center"},children:[_jsxruntime.jsxs.call(void 0, _material.Box,{sx:{mb:2},children:[_jsxruntime.jsx.call(void 0, _material.Typography,{variant:"h5",component:"h1",sx:{mb:1,fontWeight:600},children:u(o?"forgotPassword.codeAlreadyExistsMessage":"forgotPassword.emailSentMessage")}),_jsxruntime.jsx.call(void 0, _material.Typography,{variant:"body2",sx:{color:o?"success.main":"grey.600"},children:u("forgotPassword.checkEmailInstructions")})]}),_jsxruntime.jsx.call(void 0, _material.Button,{type:"button",onClick:w,fullWidth:!0,variant:"contained",color:"primary",sx:{mt:2,mb:2},children:u("forgotPassword.enterCodeLink")}),_jsxruntime.jsx.call(void 0, _material.Box,{sx:{display:"flex",justifyContent:"center",alignItems:"center"},children:_jsxruntime.jsx.call(void 0, _material.Link,{sx:{cursor:"pointer"},onClick:h,variant:"body2",color:"secondary",children:u("common.back")})})]})}):_jsxruntime.jsxs.call(void 0, _jsxruntime.Fragment,{children:[_jsxruntime.jsxs.call(void 0, _material.Box,{component:"form",noValidate:!0,sx:{width:"100%",display:"flex",flexDirection:"column",gap:2},children:[_jsxruntime.jsxs.call(void 0, _material.Box,{sx:{mb:2},children:[_jsxruntime.jsx.call(void 0, _material.Typography,{variant:"h5",component:"h1",sx:{mb:1,fontWeight:600},children:u("forgotPassword.title")}),_jsxruntime.jsx.call(void 0, _material.Typography,{variant:"body2",sx:{color:"grey.600"},children:u("forgotPassword.instructions")})]}),_jsxruntime.jsxs.call(void 0, _material.Box,{sx:{mb:1},children:[_jsxruntime.jsx.call(void 0, _material.Typography,{variant:"body2",component:"label",htmlFor:"email",sx:{display:"block",fontWeight:500,color:"grey.700",mb:.5},children:u("forgotPassword.emailLabel")}),_jsxruntime.jsx.call(void 0, _material.TextField,{fullWidth:!0,id:"email",name:"email",type:"email",value:a,disabled:n,onChange:v=>m(v.target.value),error:!!y,helperText:y,autoComplete:"email",placeholder:u("forgotPassword.emailPlaceholder"),required:!0})]}),_jsxruntime.jsx.call(void 0, _material.Button,{disabled:n,type:"button",onClick:f,fullWidth:!0,variant:"contained",color:"primary",sx:{mt:2,mb:2},children:n?_jsxruntime.jsx.call(void 0, _material.CircularProgress,{size:20}):u("forgotPassword.sendCodeButton")}),_jsxruntime.jsxs.call(void 0, _material.Box,{sx:{display:"flex",justifyContent:"center",alignItems:"center",gap:2},children:[_jsxruntime.jsx.call(void 0, _material.Link,{sx:{cursor:"pointer"},onClick:h,variant:"body2",color:"secondary",children:u("common.back")}),_jsxruntime.jsx.call(void 0, _material.Typography,{variant:"body2",sx:{color:"grey.400"},children:"\u2022"}),_jsxruntime.jsx.call(void 0, _material.Link,{sx:{cursor:"pointer"},onClick:w,variant:"body2",color:"secondary",children:u("login.alreadyHaveCodeLink")})]})]}),_jsxruntime.jsx.call(void 0, _material.Box,{children:p.length>0&&p.map((v,E)=>_jsxruntime.jsx.call(void 0, _material.Alert,{variant:"filled",sx:{mt:2},severity:"error",children:v},E))})]})},xo=ur;var pr=({onScreenChange:e,onError:t,searchParams:s,onResetSuccess:a})=>{let{crudify:m}=q(),[n,i]=_react.useState.call(void 0, ""),[p,l]=_react.useState.call(void 0, ""),[y,c]=_react.useState.call(void 0, !1),[x,d]=_react.useState.call(void 0, []),[o,r]=_react.useState.call(void 0, null),[u,C]=_react.useState.call(void 0, null),[P,f]=_react.useState.call(void 0, ""),[h,w]=_react.useState.call(void 0, ""),[v,E]=_react.useState.call(void 0, !1),[g,S]=_react.useState.call(void 0, !0),[J,de]=_react.useState.call(void 0, !1),[we,Be]=_react.useState.call(void 0, null),[No,Ye]=_react.useState.call(void 0, !1),{t:I}=U(),Ce=T=>{let k=[`errors.auth.${T.code}`,`errors.data.${T.code}`,`errors.system.${T.code}`,`errors.${T.code}`,`resetPassword.${T.code.toLowerCase()}`];for(let O of k){let N=I(O);if(N!==O)return N}return T.message||I("error.unknown")},Pe=T=>s?s instanceof URLSearchParams?s.get(T):s[T]||null:null;_react.useEffect.call(void 0, ()=>{if(s){if(s){let T=Pe("fromCodeVerification"),k=Pe("email"),O=Pe("code");if(T==="true"&&k&&O){f(k),w(O),E(!0),de(!0),S(!1);return}let N=Pe("link");if(N)try{let $=decodeURIComponent(N),[H,ue]=$.split("/");if(H&&ue&&H.length===6){w(H),f(ue),E(!1),Be({email:ue,code:H});return}}catch (e4){}if(k&&O){f(k),w(O),E(!1),Be({email:k,code:O});return}}d([I("resetPassword.invalidCode")]),S(!1),setTimeout(()=>_optionalChain([e, 'optionalCall', _21 => _21("forgotPassword")]),3e3)}},[s,m,I,e]),_react.useEffect.call(void 0, ()=>{m&&we&&!No&&(Ye(!0),(async(k,O)=>{try{let N=[{operation:"validatePasswordResetCode",data:{email:k,codePassword:O}}],$=await m.transaction(N);if($.data&&Array.isArray($.data)){let H=$.data[0];if(H&&H.response&&H.response.status==="OK"){de(!0);return}}if($.success)de(!0);else{let ue=_chunkYIIUEOXCjs.g.call(void 0, $).map(Ce);d(ue),setTimeout(()=>_optionalChain([e, 'optionalCall', _22 => _22("forgotPassword")]),3e3)}}catch(N){let H=_chunkYIIUEOXCjs.g.call(void 0, N).map(Ce);d(H),setTimeout(()=>_optionalChain([e, 'optionalCall', _23 => _23("forgotPassword")]),3e3)}finally{S(!1),Be(null),Ye(!1)}})(we.email,we.code))},[m,we,I,e]);let Vo=T=>T.length<8?I("resetPassword.passwordTooShort"):null,Wo=async()=>{if(y||!m)return;d([]),r(null),C(null);let T=!1;if(!n)r(I("resetPassword.newPasswordRequired")),T=!0;else{let k=Vo(n);k&&(r(k),T=!0)}if(p?n!==p&&(C(I("resetPassword.passwordsDoNotMatch")),T=!0):(C(I("resetPassword.confirmPasswordRequired")),T=!0),!T){c(!0);try{let k=[{operation:"validateAndResetPassword",data:{email:P,codePassword:h,newPassword:n}}],O=await m.transaction(k);if(O.success)d([]),setTimeout(()=>{_optionalChain([a, 'optionalCall', _24 => _24()])},1e3);else{let $=_chunkYIIUEOXCjs.g.call(void 0, O).map(Ce);d($)}}catch(k){let N=_chunkYIIUEOXCjs.g.call(void 0, k).map(Ce);d(N),t&&t(N.join(", "))}c(!1)}},Uo=()=>{v?_optionalChain([e, 'optionalCall', _25 => _25("checkCode",{email:P})]):_optionalChain([e, 'optionalCall', _26 => _26("forgotPassword")])};return g?_jsxruntime.jsx.call(void 0, _material.Box,{sx:{display:"flex",justifyContent:"center",alignItems:"center",minHeight:"300px"},children:_jsxruntime.jsx.call(void 0, _material.CircularProgress,{})}):J?_jsxruntime.jsxs.call(void 0, _jsxruntime.Fragment,{children:[_jsxruntime.jsxs.call(void 0, _material.Box,{component:"form",noValidate:!0,sx:{width:"100%",display:"flex",flexDirection:"column",gap:2},children:[_jsxruntime.jsxs.call(void 0, _material.Box,{sx:{mb:2},children:[_jsxruntime.jsx.call(void 0, _material.Typography,{variant:"h5",component:"h1",sx:{mb:1,fontWeight:600},children:I("resetPassword.title")}),_jsxruntime.jsx.call(void 0, _material.Typography,{variant:"body2",sx:{color:"grey.600"},children:I("resetPassword.instructions")})]}),_jsxruntime.jsxs.call(void 0, _material.Box,{sx:{mb:1},children:[_jsxruntime.jsx.call(void 0, _material.Typography,{variant:"body2",component:"label",htmlFor:"newPassword",sx:{display:"block",fontWeight:500,color:"grey.700",mb:.5},children:I("resetPassword.newPasswordLabel")}),_jsxruntime.jsx.call(void 0, _material.TextField,{fullWidth:!0,id:"newPassword",name:"newPassword",type:"password",value:n,disabled:y,onChange:T=>i(T.target.value),error:!!o,helperText:o,autoComplete:"new-password",placeholder:I("resetPassword.newPasswordPlaceholder"),required:!0})]}),_jsxruntime.jsxs.call(void 0, _material.Box,{sx:{mb:1},children:[_jsxruntime.jsx.call(void 0, _material.Typography,{variant:"body2",component:"label",htmlFor:"confirmPassword",sx:{display:"block",fontWeight:500,color:"grey.700",mb:.5},children:I("resetPassword.confirmPasswordLabel")}),_jsxruntime.jsx.call(void 0, _material.TextField,{fullWidth:!0,id:"confirmPassword",name:"confirmPassword",type:"password",value:p,disabled:y,onChange:T=>l(T.target.value),error:!!u,helperText:u,autoComplete:"new-password",placeholder:I("resetPassword.confirmPasswordPlaceholder"),required:!0})]}),_jsxruntime.jsx.call(void 0, _material.Button,{disabled:y,type:"button",onClick:Wo,fullWidth:!0,variant:"contained",color:"primary",sx:{mt:2,mb:2},children:y?_jsxruntime.jsx.call(void 0, _material.CircularProgress,{size:20}):I("resetPassword.resetPasswordButton")}),_jsxruntime.jsx.call(void 0, _material.Box,{sx:{display:"flex",justifyContent:"center",alignItems:"center"},children:_jsxruntime.jsx.call(void 0, _material.Link,{sx:{cursor:"pointer"},onClick:Uo,variant:"body2",color:"secondary",children:I("common.back")})})]}),_jsxruntime.jsx.call(void 0, _material.Box,{children:x.length>0&&x.map((T,k)=>_jsxruntime.jsx.call(void 0, _material.Alert,{variant:"filled",sx:{mt:2},severity:"error",children:T},k))})]}):_jsxruntime.jsx.call(void 0, _material.Box,{children:x.length>0&&x.map((T,k)=>_jsxruntime.jsx.call(void 0, _material.Alert,{variant:"filled",sx:{mt:2},severity:"error",children:T},k))})},Po=pr;var Pr=({onScreenChange:e,onError:t,searchParams:s})=>{let{crudify:a}=q(),[m,n]=_react.useState.call(void 0, ""),[i,p]=_react.useState.call(void 0, !1),[l,y]=_react.useState.call(void 0, []),[c,x]=_react.useState.call(void 0, null),[d,o]=_react.useState.call(void 0, ""),{t:r}=U(),u=w=>s?s instanceof URLSearchParams?s.get(w):s[w]||null:null,C=w=>{let v=[`errors.auth.${w.code}`,`errors.data.${w.code}`,`errors.system.${w.code}`,`errors.${w.code}`,`checkCode.${w.code.toLowerCase()}`];for(let E of v){let g=r(E);if(g!==E)return g}return w.message||r("error.unknown")};_react.useEffect.call(void 0, ()=>{let w=u("email");w?o(w):_optionalChain([e, 'optionalCall', _27 => _27("forgotPassword")])},[s,e]);let P=async()=>{if(!(i||!a)){if(y([]),x(null),!m){x(r("checkCode.codeRequired"));return}if(m.length!==6){x(r("checkCode.codeRequired"));return}p(!0);try{let w=[{operation:"validatePasswordResetCode",data:{email:d,codePassword:m}}],v=await a.transaction(w);if(v.success)_optionalChain([e, 'optionalCall', _28 => _28("resetPassword",{email:d,code:m,fromCodeVerification:"true"})]);else{let g=_chunkYIIUEOXCjs.g.call(void 0, v).map(C);y(g),p(!1)}}catch(w){let E=_chunkYIIUEOXCjs.g.call(void 0, w).map(C);y(E),p(!1),t&&t(E.join(", "))}}},f=()=>{_optionalChain([e, 'optionalCall', _29 => _29("forgotPassword")])},h=w=>{let v=w.target.value.replace(/\D/g,"").slice(0,6);n(v)};return _jsxruntime.jsxs.call(void 0, _jsxruntime.Fragment,{children:[_jsxruntime.jsxs.call(void 0, _material.Box,{component:"form",noValidate:!0,sx:{width:"100%",display:"flex",flexDirection:"column",gap:2},children:[_jsxruntime.jsxs.call(void 0, _material.Box,{sx:{mb:2},children:[_jsxruntime.jsx.call(void 0, _material.Typography,{variant:"h5",component:"h1",sx:{mb:1,fontWeight:600},children:r("checkCode.title")}),_jsxruntime.jsx.call(void 0, _material.Typography,{variant:"body2",sx:{color:"grey.600"},children:r("checkCode.instructions")})]}),_jsxruntime.jsxs.call(void 0, _material.Box,{sx:{mb:1},children:[_jsxruntime.jsx.call(void 0, _material.Typography,{variant:"body2",component:"label",htmlFor:"code",sx:{display:"block",fontWeight:500,color:"grey.700",mb:.5},children:r("checkCode.codeLabel")}),_jsxruntime.jsx.call(void 0, _material.TextField,{fullWidth:!0,id:"code",name:"code",type:"text",value:m,disabled:i,onChange:h,error:!!c,helperText:c,placeholder:r("checkCode.codePlaceholder"),inputProps:{maxLength:6,style:{textAlign:"center",fontSize:"1.5rem",letterSpacing:"0.4rem"}},required:!0})]}),_jsxruntime.jsx.call(void 0, _material.Button,{disabled:i||m.length!==6,type:"button",onClick:P,fullWidth:!0,variant:"contained",color:"primary",sx:{mt:2,mb:2},children:i?_jsxruntime.jsx.call(void 0, _material.CircularProgress,{size:20}):r("checkCode.verifyButton")}),_jsxruntime.jsx.call(void 0, _material.Box,{sx:{display:"flex",justifyContent:"center",alignItems:"center"},children:_jsxruntime.jsx.call(void 0, _material.Link,{sx:{cursor:"pointer"},onClick:f,variant:"body2",color:"secondary",children:r("common.back")})})]}),_jsxruntime.jsx.call(void 0, _material.Box,{children:l.length>0&&l.map((w,v)=>_jsxruntime.jsx.call(void 0, _material.Alert,{sx:{mt:2},severity:"error",children:w},v))})]})},vo=Pr;var So=({children:e,fallback:t})=>{let{isLoading:s,error:a,isInitialized:m}=q(),{t:n}=U();return s?t||_jsxruntime.jsxs.call(void 0, _material.Box,{sx:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",minHeight:"200px",gap:2},children:[_jsxruntime.jsx.call(void 0, _material.CircularProgress,{}),_jsxruntime.jsx.call(void 0, _material.Typography,{variant:"body2",color:"text.secondary",children:n("login.initializing")!=="login.initializing"?n("login.initializing"):"Initializing..."})]}):a?_jsxruntime.jsx.call(void 0, _material.Alert,{severity:"error",sx:{mt:2},children:_jsxruntime.jsxs.call(void 0, _material.Typography,{variant:"body2",children:[n("login.initializationError")!=="login.initializationError"?n("login.initializationError"):"Initialization error",":"," ",a]})}):m?_jsxruntime.jsx.call(void 0, _jsxruntime.Fragment,{children:e}):_jsxruntime.jsx.call(void 0, _material.Alert,{severity:"warning",sx:{mt:2},children:_jsxruntime.jsx.call(void 0, _material.Typography,{variant:"body2",children:n("login.notInitialized")!=="login.notInitialized"?n("login.notInitialized"):"System not initialized"})})};var Rr=({onScreenChange:e,onExternalNavigate:t,onLoginSuccess:s,onError:a,redirectUrl:m="/"})=>{let{t:n}=U(),{state:i,setScreen:p}=Te(),{config:l}=_chunk2OSNNNIDjs.g.call(void 0, ),{showNotification:y}=_chunk2OSNNNIDjs.e.call(void 0, ),c=(d,o)=>{let r=o;d==="login"?r={}:d==="forgotPassword"&&!o&&(r={}),p(d,r),_optionalChain([e, 'optionalCall', _30 => _30(d,r)])},x=()=>{let d={onScreenChange:c,onExternalNavigate:t,onError:a,redirectUrl:m};switch(i.currentScreen){case"forgotPassword":return _jsxruntime.jsx.call(void 0, xo,{...d});case"checkCode":return _jsxruntime.jsx.call(void 0, vo,{...d,searchParams:i.searchParams});case"resetPassword":return _jsxruntime.jsx.call(void 0, Po,{...d,searchParams:i.searchParams,onResetSuccess:()=>{let o=n("resetPassword.successMessage");y(o,"success"),c("login")}});default:return _jsxruntime.jsx.call(void 0, po,{...d,onLoginSuccess:s})}};return _jsxruntime.jsxs.call(void 0, So,{children:[_jsxruntime.jsx.call(void 0, _material.Box,{sx:{display:"flex",justifyContent:"center",mb:3},children:_jsxruntime.jsx.call(void 0, "img",{src:l.logo||"/nocios-default.png",alt:n("login.logoAlt"),style:{width:"100%",maxWidth:"150px",height:"auto"},onError:d=>{let o=d.target;o.src="/nocios-default.png"}})}),!l.logo&&l.appName&&_jsxruntime.jsx.call(void 0, _material.Typography,{variant:"h6",component:"h1",sx:{textAlign:"center",mb:2},children:l.appName}),x()]})},Ar=({translations:e,translationsUrl:t,language:s="en",initialScreen:a="login",autoReadFromCookies:m=!0,...n})=>{let{config:i}=_chunk2OSNNNIDjs.g.call(void 0, );return _jsxruntime.jsx.call(void 0, no,{translations:e,translationsUrl:t,language:s,children:_jsxruntime.jsx.call(void 0, so,{config:i,children:_jsxruntime.jsx.call(void 0, uo,{config:i,initialScreen:a,autoReadFromCookies:m,children:_jsxruntime.jsx.call(void 0, Rr,{...n})})})})},Wn= exports.a =Ar;var _iconsmaterial = require('@mui/icons-material');var Gr=({showExtendedData:e=!0,showProfileCard:t=!0,autoRefresh:s=!0})=>{let{userProfile:a,loading:m,error:n,extendedData:i,refreshProfile:p}=_chunk2OSNNNIDjs.j.call(void 0, {autoFetch:s,retryOnError:!0,maxRetries:3}),[l,y]=_react.useState.call(void 0, !1);if(m)return _jsxruntime.jsxs.call(void 0, _material.Box,{display:"flex",justifyContent:"center",alignItems:"center",p:3,children:[_jsxruntime.jsx.call(void 0, _material.CircularProgress,{}),_jsxruntime.jsx.call(void 0, _material.Typography,{variant:"body2",sx:{ml:2},children:"Cargando perfil de usuario..."})]});if(n)return _jsxruntime.jsxs.call(void 0, _material.Alert,{severity:"error",action:_jsxruntime.jsx.call(void 0, _material.IconButton,{color:"inherit",size:"small",onClick:p,children:_jsxruntime.jsx.call(void 0, _material.Typography,{variant:"caption",children:"Reintentar"})}),children:["Error al cargar el perfil: ",n]});if(!a)return _jsxruntime.jsx.call(void 0, _material.Alert,{severity:"warning",children:"No se encontr\xF3 informaci\xF3n del usuario"});let c=_optionalChain([i, 'optionalAccess', _31 => _31.displayData])||{},x=_optionalChain([i, 'optionalAccess', _32 => _32.totalFields])||0,d=f=>{if(!f)return"No disponible";try{return new Date(f).toLocaleString("es-ES",{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}catch (e5){return f}},o=(f,h)=>h==null?"No disponible":typeof h=="boolean"?h?"S\xED":"No":Array.isArray(h)?h.length>0?h.join(", "):"Ninguno":typeof h=="object"?JSON.stringify(h,null,2):String(h),r=[{key:"id",label:"ID",icon:_jsxruntime.jsx.call(void 0, _iconsmaterial.Badge,{})},{key:"email",label:"Email",icon:_jsxruntime.jsx.call(void 0, _iconsmaterial.Email,{})},{key:"username",label:"Usuario",icon:_jsxruntime.jsx.call(void 0, _iconsmaterial.Person,{})},{key:"fullName",label:"Nombre completo",icon:_jsxruntime.jsx.call(void 0, _iconsmaterial.AccountCircle,{})},{key:"role",label:"Rol",icon:_jsxruntime.jsx.call(void 0, _iconsmaterial.Security,{})}],u=[{key:"firstName",label:"Nombre"},{key:"lastName",label:"Apellido"},{key:"isActive",label:"Activo"},{key:"lastLogin",label:"\xDAltimo login"},{key:"createdAt",label:"Creado"},{key:"updatedAt",label:"Actualizado"}],C=[...r.map(f=>f.key),...u.map(f=>f.key),"permissions"],P=Object.keys(c).filter(f=>!C.includes(f)).map(f=>({key:f,label:f}));return _jsxruntime.jsxs.call(void 0, _material.Box,{children:[t&&_jsxruntime.jsx.call(void 0, _material.Card,{sx:{mb:2},children:_jsxruntime.jsxs.call(void 0, _material.CardContent,{children:[_jsxruntime.jsxs.call(void 0, _material.Box,{display:"flex",alignItems:"center",mb:2,children:[_jsxruntime.jsx.call(void 0, _material.Avatar,{src:c.avatar,sx:{width:56,height:56,mr:2},children:_optionalChain([c, 'access', _33 => _33.fullName, 'optionalAccess', _34 => _34[0]])||_optionalChain([c, 'access', _35 => _35.username, 'optionalAccess', _36 => _36[0]])||_optionalChain([c, 'access', _37 => _37.email, 'optionalAccess', _38 => _38[0]])}),_jsxruntime.jsxs.call(void 0, _material.Box,{children:[_jsxruntime.jsx.call(void 0, _material.Typography,{variant:"h6",children:c.fullName||c.username||c.email}),_jsxruntime.jsx.call(void 0, _material.Typography,{variant:"body2",color:"text.secondary",children:c.role||"Usuario"}),c.isActive!==void 0&&_jsxruntime.jsx.call(void 0, _material.Chip,{label:c.isActive?"Activo":"Inactivo",color:c.isActive?"success":"error",size:"small",sx:{mt:.5}})]})]}),_jsxruntime.jsx.call(void 0, _material.Box,{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(250px, 1fr))",gap:2,children:r.map(({key:f,label:h,icon:w})=>c[f]?_jsxruntime.jsxs.call(void 0, _material.Box,{display:"flex",alignItems:"center",children:[_jsxruntime.jsx.call(void 0, _material.Box,{sx:{mr:1,color:"text.secondary"},children:w}),_jsxruntime.jsxs.call(void 0, _material.Box,{children:[_jsxruntime.jsx.call(void 0, _material.Typography,{variant:"caption",color:"text.secondary",children:h}),_jsxruntime.jsx.call(void 0, _material.Typography,{variant:"body2",children:o(f,c[f])})]})]},f):null)}),c.permissions&&Array.isArray(c.permissions)&&c.permissions.length>0&&_jsxruntime.jsxs.call(void 0, _material.Box,{mt:2,children:[_jsxruntime.jsx.call(void 0, _material.Typography,{variant:"caption",color:"text.secondary",display:"block",children:"Permisos"}),_jsxruntime.jsxs.call(void 0, _material.Box,{display:"flex",flexWrap:"wrap",gap:.5,mt:.5,children:[c.permissions.slice(0,5).map((f,h)=>_jsxruntime.jsx.call(void 0, _material.Chip,{label:f,size:"small",variant:"outlined"},h)),c.permissions.length>5&&_jsxruntime.jsx.call(void 0, _material.Chip,{label:`+${c.permissions.length-5} m\xE1s`,size:"small"})]})]})]})}),e&&_jsxruntime.jsx.call(void 0, _material.Card,{children:_jsxruntime.jsxs.call(void 0, _material.CardContent,{children:[_jsxruntime.jsxs.call(void 0, _material.Box,{display:"flex",justifyContent:"space-between",alignItems:"center",mb:2,children:[_jsxruntime.jsxs.call(void 0, _material.Typography,{variant:"h6",display:"flex",alignItems:"center",children:[_jsxruntime.jsx.call(void 0, _iconsmaterial.Info,{sx:{mr:1}}),"Informaci\xF3n Detallada"]}),_jsxruntime.jsx.call(void 0, _material.Chip,{label:`${x} campos totales`,size:"small"})]}),_jsxruntime.jsxs.call(void 0, _material.List,{dense:!0,children:[u.map(({key:f,label:h})=>c[f]!==void 0&&_jsxruntime.jsxs.call(void 0, _material.ListItem,{divider:!0,children:[_jsxruntime.jsx.call(void 0, _material.ListItemIcon,{children:_jsxruntime.jsx.call(void 0, _iconsmaterial.Schedule,{fontSize:"small"})}),_jsxruntime.jsx.call(void 0, _material.ListItemText,{primary:h,secondary:f.includes("At")||f.includes("Login")?d(c[f]):o(f,c[f])})]},f)),P.length>0&&_jsxruntime.jsxs.call(void 0, _jsxruntime.Fragment,{children:[_jsxruntime.jsx.call(void 0, _material.Divider,{sx:{my:1}}),_jsxruntime.jsx.call(void 0, _material.ListItem,{children:_jsxruntime.jsx.call(void 0, _material.ListItemText,{primary:_jsxruntime.jsxs.call(void 0, _material.Box,{display:"flex",justifyContent:"space-between",alignItems:"center",children:[_jsxruntime.jsxs.call(void 0, _material.Typography,{variant:"subtitle2",children:["Campos Personalizados (",P.length,")"]}),_jsxruntime.jsx.call(void 0, _material.IconButton,{size:"small",onClick:()=>y(!l),children:l?_jsxruntime.jsx.call(void 0, _iconsmaterial.ExpandLess,{}):_jsxruntime.jsx.call(void 0, _iconsmaterial.ExpandMore,{})})]})})}),_jsxruntime.jsx.call(void 0, _material.Collapse,{in:l,children:P.map(({key:f,label:h})=>_jsxruntime.jsx.call(void 0, _material.ListItem,{sx:{pl:4},children:_jsxruntime.jsx.call(void 0, _material.ListItemText,{primary:h,secondary:o(f,c[f])})},f))})]})]}),_jsxruntime.jsxs.call(void 0, _material.Box,{mt:2,display:"flex",justifyContent:"space-between",alignItems:"center",children:[_jsxruntime.jsxs.call(void 0, _material.Typography,{variant:"caption",color:"text.secondary",children:["\xDAltima actualizaci\xF3n: ",d(c.updatedAt)]}),_jsxruntime.jsx.call(void 0, _material.IconButton,{size:"small",onClick:p,disabled:m,children:_jsxruntime.jsx.call(void 0, _material.Typography,{variant:"caption",children:"Actualizar"})})]})]})})]})},Yr= exports.b =Gr;var Ao=["create","read","update","delete"],Io= exports.d =["create","read","update","delete"];var _reacti18next = require('react-i18next');var st=({value:e,onChange:t,availableFields:s,error:a,disabled:m=!1})=>{let{t:n}=_reacti18next.useTranslation.call(void 0, ),[i,p]=_react.useState.call(void 0, "custom"),l=_react.useRef.call(void 0, !1);_react.useEffect.call(void 0, ()=>{let o=e||{allow:[],owner_allow:[],deny:[]},r=new Set(s),u=(o.allow||[]).filter(h=>r.has(h)),C=(o.owner_allow||[]).filter(h=>r.has(h)),P=(o.deny||[]).filter(h=>r.has(h));s.forEach(h=>{!u.includes(h)&&!C.includes(h)&&!P.includes(h)&&P.push(h)});let f={allow:u,owner_allow:C,deny:P};JSON.stringify(f)!==JSON.stringify(o)&&t(f),u.length===s.length?p("all"):P.length===s.length?p("none"):p("custom")},[s,e]);let y=()=>{l.current=!0,t({allow:[...s],owner_allow:[],deny:[]}),p("all"),setTimeout(()=>{l.current=!1},0)},c=()=>{l.current=!0,t({allow:[],owner_allow:[],deny:[...s]}),p("none"),setTimeout(()=>{l.current=!1},0)},x=o=>_optionalChain([e, 'optionalAccess', _39 => _39.allow, 'optionalAccess', _40 => _40.includes, 'call', _41 => _41(o)])?"allow":_optionalChain([e, 'optionalAccess', _42 => _42.owner_allow, 'optionalAccess', _43 => _43.includes, 'call', _44 => _44(o)])?"owner_allow":"deny",d=(o,r)=>{l.current=!0;let u=new Set(_optionalChain([e, 'optionalAccess', _45 => _45.allow])||[]),C=new Set(_optionalChain([e, 'optionalAccess', _46 => _46.owner_allow])||[]),P=new Set(_optionalChain([e, 'optionalAccess', _47 => _47.deny])||[]);u.delete(o),C.delete(o),P.delete(o),r==="allow"&&u.add(o),r==="owner_allow"&&C.add(o),r==="deny"&&P.add(o),t({allow:Array.from(u),owner_allow:Array.from(C),deny:Array.from(P)}),p("custom"),setTimeout(()=>{l.current=!1},0)};return s.length===0?_jsxruntime.jsxs.call(void 0, _material.Box,{children:[_jsxruntime.jsx.call(void 0, _material.Typography,{variant:"body2",color:"text.secondary",sx:{mb:1},children:n("modules.form.publicPolicies.fields.conditions.label")}),_jsxruntime.jsx.call(void 0, _material.Typography,{variant:"body2",color:"text.secondary",sx:{fontStyle:"italic"},children:n("modules.form.publicPolicies.fields.conditions.noFieldsAvailable")}),a&&_jsxruntime.jsx.call(void 0, _material.FormHelperText,{error:!0,sx:{mt:1},children:a})]}):_jsxruntime.jsxs.call(void 0, _material.Box,{children:[_jsxruntime.jsx.call(void 0, _material.Typography,{variant:"body2",color:"text.secondary",sx:{mb:2},children:n("modules.form.publicPolicies.fields.conditions.label")}),_jsxruntime.jsxs.call(void 0, _material.Stack,{direction:"row",spacing:1,sx:{mb:3},children:[_jsxruntime.jsx.call(void 0, _material.Button,{variant:i==="all"?"contained":"outlined",startIcon:_jsxruntime.jsx.call(void 0, _iconsmaterial.SelectAll,{}),onClick:y,disabled:m,size:"small",sx:{minWidth:120,...i==="all"&&{backgroundColor:"#16a34a","&:hover":{backgroundColor:"#15803d"}}},children:n("modules.form.publicPolicies.fields.conditions.allFields")}),_jsxruntime.jsx.call(void 0, _material.Button,{variant:i==="none"?"contained":"outlined",startIcon:_jsxruntime.jsx.call(void 0, _iconsmaterial.ClearAll,{}),onClick:c,disabled:m,size:"small",sx:{minWidth:120,...i==="none"&&{backgroundColor:"#cf222e","&:hover":{backgroundColor:"#bc1f2c"}}},children:n("modules.form.publicPolicies.fields.conditions.noFields")})]}),_jsxruntime.jsxs.call(void 0, _material.Box,{sx:{p:2,border:"1px solid #d1d9e0",borderRadius:1,backgroundColor:"#f6f8fa"},children:[_jsxruntime.jsx.call(void 0, _material.Typography,{variant:"body2",color:"text.secondary",sx:{mb:2},children:n("modules.form.publicPolicies.fields.conditions.help")}),_jsxruntime.jsx.call(void 0, _material.Stack,{spacing:1,children:s.map(o=>{let r=x(o);return _jsxruntime.jsxs.call(void 0, _material.Stack,{direction:"row",spacing:1,alignItems:"center",children:[_jsxruntime.jsx.call(void 0, _material.Typography,{variant:"body2",sx:{minWidth:100,fontFamily:"monospace"},children:o}),_jsxruntime.jsxs.call(void 0, _material.ToggleButtonGroup,{value:r,exclusive:!0,size:"small",children:[_jsxruntime.jsxs.call(void 0, _material.ToggleButton,{value:"allow",onClick:()=>d(o,"allow"),disabled:m,sx:{px:2,color:r==="allow"?"#ffffff":"#6b7280",backgroundColor:r==="allow"?"#16a34a":"#f3f4f6",borderColor:r==="allow"?"#16a34a":"#d1d5db","&:hover":{backgroundColor:r==="allow"?"#15803d":"#e5e7eb",borderColor:r==="allow"?"#15803d":"#9ca3af"},"&.Mui-selected":{backgroundColor:"#16a34a",color:"#ffffff","&:hover":{backgroundColor:"#15803d"}}},children:[_jsxruntime.jsx.call(void 0, _iconsmaterial.CheckCircle,{sx:{fontSize:16,mr:.5}}),n("modules.form.publicPolicies.fields.conditions.states.allow")]}),_jsxruntime.jsx.call(void 0, _material.ToggleButton,{value:"owner_allow",onClick:()=>d(o,"owner_allow"),disabled:m,sx:{px:2,color:r==="owner_allow"?"#ffffff":"#6b7280",backgroundColor:r==="owner_allow"?"#0ea5e9":"#f3f4f6",borderColor:r==="owner_allow"?"#0ea5e9":"#d1d5db","&:hover":{backgroundColor:r==="owner_allow"?"#0284c7":"#e5e7eb",borderColor:r==="owner_allow"?"#0284c7":"#9ca3af"},"&.Mui-selected":{backgroundColor:"#0ea5e9",color:"#ffffff","&:hover":{backgroundColor:"#0284c7"}}},children:n("modules.form.publicPolicies.fields.conditions.states.ownerAllow")}),_jsxruntime.jsxs.call(void 0, _material.ToggleButton,{value:"deny",onClick:()=>d(o,"deny"),disabled:m,sx:{px:2,color:r==="deny"?"#ffffff":"#6b7280",backgroundColor:r==="deny"?"#dc2626":"#f3f4f6",borderColor:r==="deny"?"#dc2626":"#d1d5db","&:hover":{backgroundColor:r==="deny"?"#b91c1c":"#e5e7eb",borderColor:r==="deny"?"#b91c1c":"#9ca3af"},"&.Mui-selected":{backgroundColor:"#dc2626",color:"#ffffff","&:hover":{backgroundColor:"#b91c1c"}}},children:[_jsxruntime.jsx.call(void 0, _iconsmaterial.Cancel,{sx:{fontSize:16,mr:.5}}),n("modules.form.publicPolicies.fields.conditions.states.deny")]})]})]},o)})})]}),a&&_jsxruntime.jsx.call(void 0, _material.FormHelperText,{error:!0,sx:{mt:1},children:a})]})},He=st;var bt=_react.forwardRef.call(void 0, ({policy:e,onChange:t,onRemove:s,availableFields:a,isSubmitting:m=!1,usedActions:n,error:i},p)=>{let{t:l}=_reacti18next.useTranslation.call(void 0, ),y=new Set(Array.from(n||[]));y.delete(e.action);let c=Ao.map(x=>({value:x,label:l(`modules.form.publicPolicies.fields.action.options.${x}`)}));return _jsxruntime.jsxs.call(void 0, _material.Paper,{ref:p,sx:{p:3,border:"1px solid #d1d9e0",borderRadius:2,position:"relative",backgroundColor:"#ffffff"},children:[_jsxruntime.jsxs.call(void 0, _material.Box,{sx:{display:"flex",justifyContent:"space-between",alignItems:"flex-start",mb:3},children:[_jsxruntime.jsx.call(void 0, _material.Typography,{variant:"subtitle1",sx:{fontWeight:600,color:"#111418",fontSize:"1rem"},children:l("modules.form.publicPolicies.policyTitle")}),_jsxruntime.jsx.call(void 0, _material.IconButton,{onClick:s,size:"small",disabled:m,"aria-label":l("modules.form.publicPolicies.removePolicy"),sx:{color:"#656d76","&:hover":{color:"#cf222e",backgroundColor:"rgba(207, 34, 46, 0.1)"}},children:_jsxruntime.jsx.call(void 0, _iconsmaterial.Delete,{})})]}),_jsxruntime.jsxs.call(void 0, _material.Stack,{spacing:3,children:[_jsxruntime.jsx.call(void 0, _material.Stack,{direction:{xs:"column",md:"row"},spacing:2,children:_jsxruntime.jsx.call(void 0, _material.Box,{sx:{flex:1,minWidth:200},children:_jsxruntime.jsxs.call(void 0, _material.FormControl,{fullWidth:!0,children:[_jsxruntime.jsx.call(void 0, _material.InputLabel,{children:l("modules.form.publicPolicies.fields.action.label")}),_jsxruntime.jsx.call(void 0, _material.Select,{value:e.action,label:l("modules.form.publicPolicies.fields.action.label"),disabled:m,onChange:x=>{let d=x.target.value,o={...e,action:d};d==="delete"?(o.permission="deny",delete o.fields):(o.fields={allow:[],owner_allow:[],deny:a},delete o.permission),t(o)},sx:{backgroundColor:"#ffffff","&:hover .MuiOutlinedInput-notchedOutline":{borderColor:"#8c959f"},"&.Mui-focused .MuiOutlinedInput-notchedOutline":{borderColor:"#0969da",borderWidth:2}},children:c.map(x=>{let d=y.has(x.value);return _jsxruntime.jsx.call(void 0, _material.MenuItem,{value:x.value,disabled:d,children:x.label},x.value)})}),i&&_jsxruntime.jsx.call(void 0, _material.FormHelperText,{error:!0,children:i})]})})}),e.action==="delete"?_jsxruntime.jsxs.call(void 0, _material.Box,{children:[_jsxruntime.jsx.call(void 0, _material.Typography,{variant:"body2",color:"text.secondary",sx:{mb:2},children:l("modules.form.publicPolicies.fields.conditions.label")}),_jsxruntime.jsxs.call(void 0, _material.Stack,{direction:"row",spacing:1,sx:{mb:3},children:[_jsxruntime.jsx.call(void 0, _material.Button,{variant:e.permission==="*"?"contained":"outlined",startIcon:_jsxruntime.jsx.call(void 0, _iconsmaterial.SelectAll,{}),onClick:()=>t({...e,permission:"*"}),disabled:m,size:"small",sx:{minWidth:140,whiteSpace:"nowrap",...e.permission==="*"&&{backgroundColor:"#16a34a","&:hover":{backgroundColor:"#15803d"}}},children:l("modules.form.publicPolicies.fields.conditions.allFields")}),_jsxruntime.jsx.call(void 0, _material.Button,{variant:e.permission==="owner"?"contained":"outlined",onClick:()=>t({...e,permission:"owner"}),disabled:m,size:"small",sx:{minWidth:140,whiteSpace:"nowrap",...e.permission==="owner"&&{backgroundColor:"#0ea5e9","&:hover":{backgroundColor:"#0284c7"}}},children:l("modules.form.publicPolicies.fields.conditions.states.ownerAllow")}),_jsxruntime.jsx.call(void 0, _material.Button,{variant:e.permission==="deny"?"contained":"outlined",startIcon:_jsxruntime.jsx.call(void 0, _iconsmaterial.ClearAll,{}),onClick:()=>t({...e,permission:"deny"}),disabled:m,size:"small",sx:{minWidth:140,whiteSpace:"nowrap",...e.permission==="deny"&&{backgroundColor:"#cf222e","&:hover":{backgroundColor:"#bc1f2c"}}},children:l("modules.form.publicPolicies.fields.conditions.noFields")})]})]}):_jsxruntime.jsx.call(void 0, He,{value:e.fields||{allow:[],owner_allow:[],deny:[]},onChange:x=>t({...e,fields:x}),availableFields:a,disabled:m}),_jsxruntime.jsx.call(void 0, _material.Paper,{variant:"outlined",sx:{p:2,backgroundColor:"#f9fafb"},children:e.action==="delete"?_jsxruntime.jsxs.call(void 0, _material.Typography,{variant:"body2",sx:{fontFamily:"monospace",color:"text.secondary"},children:[_jsxruntime.jsxs.call(void 0, _material.Box,{component:"span",sx:{color:e.permission==="*"?"#16a34a":e.permission==="owner"?"#0ea5e9":"#dc2626"},children:[l("modules.form.publicPolicies.fields.conditions.states.allow"),":"]})," ",e.permission||"-"]}):_jsxruntime.jsxs.call(void 0, _material.Stack,{spacing:.5,divider:_jsxruntime.jsx.call(void 0, _material.Divider,{sx:{borderColor:"#e5e7eb"}}),children:[_jsxruntime.jsxs.call(void 0, _material.Typography,{variant:"body2",sx:{fontFamily:"monospace",color:"text.secondary"},children:[_jsxruntime.jsxs.call(void 0, _material.Box,{component:"span",sx:{color:"#16a34a"},children:[l("modules.form.publicPolicies.fields.conditions.states.allow"),":"]})," ",(_optionalChain([e, 'optionalAccess', _48 => _48.fields, 'optionalAccess', _49 => _49.allow])||[]).join(", ")||"-"]}),_jsxruntime.jsxs.call(void 0, _material.Typography,{variant:"body2",sx:{fontFamily:"monospace",color:"text.secondary"},children:[_jsxruntime.jsxs.call(void 0, _material.Box,{component:"span",sx:{color:"#0ea5e9"},children:[l("modules.form.publicPolicies.fields.conditions.states.ownerAllow"),":"]})," ",(_optionalChain([e, 'optionalAccess', _50 => _50.fields, 'optionalAccess', _51 => _51.owner_allow])||[]).join(", ")||"-"]}),_jsxruntime.jsxs.call(void 0, _material.Typography,{variant:"body2",sx:{fontFamily:"monospace",color:"text.secondary"},children:[_jsxruntime.jsxs.call(void 0, _material.Box,{component:"span",sx:{color:"#dc2626"},children:[l("modules.form.publicPolicies.fields.conditions.states.deny"),":"]})," ",(_optionalChain([e, 'optionalAccess', _52 => _52.fields, 'optionalAccess', _53 => _53.deny])||[]).join(", ")||"-"]})]})})]})]})}),je=bt;var St=()=>{let e=_optionalChain([globalThis, 'optionalAccess', _54 => _54.crypto]);return e&&typeof e.randomUUID=="function"?e.randomUUID():`${Date.now()}-${Math.random().toString(16).slice(2)}`},kt=({policies:e,onChange:t,availableFields:s,errors:a,isSubmitting:m=!1})=>{let{t:n}=_reacti18next.useTranslation.call(void 0, ),i=_react.useRef.call(void 0, {}),p=new Set((e||[]).map(r=>r.action).filter(Boolean)),l=Io.filter(r=>!p.has(r)),y=l.length>0,c=()=>{let r=l[0]||"create",u={id:St(),action:r};r==="delete"?u.permission="deny":u.fields={allow:[],owner_allow:[],deny:s};let C=[...e||[],u];t(C),setTimeout(()=>{let P=C.length-1,f=i.current[P];f&&f.scrollIntoView({behavior:"smooth",block:"center"})},100)},x=r=>{let u=[...e];u.splice(r,1),t(u)},d=(()=>{if(!a)return null;if(typeof a=="string")return a;let r=a._error;return typeof r=="string"?r:null})(),o=new Set((e||[]).map(r=>r.action));return _jsxruntime.jsxs.call(void 0, _jsxruntime.Fragment,{children:[_jsxruntime.jsx.call(void 0, _material.Divider,{sx:{borderColor:"#e0e4e7"}}),_jsxruntime.jsxs.call(void 0, _material.Box,{children:[_jsxruntime.jsx.call(void 0, _material.Box,{display:"flex",justifyContent:"space-between",alignItems:"center",mb:3,children:_jsxruntime.jsxs.call(void 0, _material.Box,{children:[_jsxruntime.jsx.call(void 0, _material.Typography,{variant:"h6",sx:{fontWeight:600,color:"#111418",mb:1},children:n("modules.form.publicPolicies.title")}),_jsxruntime.jsx.call(void 0, _material.Typography,{variant:"body2",color:"text.secondary",sx:{fontSize:"0.875rem"},children:n("modules.form.publicPolicies.description")})]})}),d&&_jsxruntime.jsx.call(void 0, _material.Alert,{severity:"error",sx:{mb:3},children:d}),_jsxruntime.jsxs.call(void 0, _material.Stack,{spacing:3,children:[(e||[]).length===0?_jsxruntime.jsx.call(void 0, _material.Alert,{severity:"info",children:n("modules.form.publicPolicies.noPolicies")}):e.map((r,u)=>_jsxruntime.jsx.call(void 0, je,{ref:C=>{i.current[u]=C},policy:r,onChange:C=>{let P=[...e];P[u]=C,t(P)},onRemove:()=>x(u),availableFields:s,isSubmitting:m,usedActions:o,error:typeof a=="object"&&a&&r.id in a?a[r.id]:void 0},r.id)),y&&_jsxruntime.jsx.call(void 0, _material.Box,{children:_jsxruntime.jsx.call(void 0, _material.Button,{type:"button",variant:"outlined",startIcon:_jsxruntime.jsx.call(void 0, _iconsmaterial.Add,{}),onClick:c,disabled:m,sx:{borderColor:"#d0d7de",color:"#656d76","&:hover":{borderColor:"#8c959f",backgroundColor:"transparent"}},children:n("modules.form.publicPolicies.addPolicy")})})]})]})]})},Ti= exports.e =kt;function Ii(){let[e,t]=_react.useState.call(void 0, ""),[s,a]=_react.useState.call(void 0, ""),[m,n]=_react.useState.call(void 0, !1),{isAuthenticated:i,isLoading:p,error:l,login:y,logout:c,refreshTokens:x,clearError:d,isExpiringSoon:o,expiresIn:r}=_chunk2OSNNNIDjs.g.call(void 0, ),u=async f=>{if(f.preventDefault(),!e||!s)return;(await y(e,s)).success&&(t(""),a(""),n(!1))},C=async()=>{await c()},P=async()=>{await x()};return i?_jsxruntime.jsxs.call(void 0, _material.Box,{sx:{maxWidth:600,mx:"auto",p:3},children:[_jsxruntime.jsx.call(void 0, _material.Typography,{variant:"h4",gutterBottom:!0,children:"Welcome! \u{1F389}"}),_jsxruntime.jsx.call(void 0, _material.Alert,{severity:"success",sx:{mb:3},children:"You are successfully logged in with Refresh Token Pattern enabled"}),_jsxruntime.jsxs.call(void 0, _material.Box,{sx:{mb:3,p:2,bgcolor:"background.paper",border:1,borderColor:"divider",borderRadius:1},children:[_jsxruntime.jsx.call(void 0, _material.Typography,{variant:"h6",gutterBottom:!0,children:"Token Status"}),_jsxruntime.jsxs.call(void 0, _material.Typography,{variant:"body2",color:"text.secondary",children:["Access Token expires in: ",Math.round(r/1e3/60)," minutes"]}),o&&_jsxruntime.jsx.call(void 0, _material.Alert,{severity:"warning",sx:{mt:1},children:"Token expires soon - automatic refresh will happen"})]}),_jsxruntime.jsxs.call(void 0, _material.Box,{sx:{display:"flex",gap:2,flexWrap:"wrap"},children:[_jsxruntime.jsx.call(void 0, _material.Button,{variant:"contained",onClick:P,disabled:p,startIcon:p?_jsxruntime.jsx.call(void 0, _material.CircularProgress,{size:16}):null,children:"Refresh Tokens"}),_jsxruntime.jsx.call(void 0, _material.Button,{variant:"outlined",color:"error",onClick:C,disabled:p,children:"Logout"})]}),l&&_jsxruntime.jsx.call(void 0, _material.Alert,{severity:"error",sx:{mt:2},onClose:d,children:l})]}):_jsxruntime.jsxs.call(void 0, _material.Box,{sx:{maxWidth:400,mx:"auto",p:3},children:[_jsxruntime.jsx.call(void 0, _material.Typography,{variant:"h4",gutterBottom:!0,align:"center",children:"Login with Refresh Tokens"}),_jsxruntime.jsx.call(void 0, _material.Alert,{severity:"info",sx:{mb:3},children:"This demo shows the new Refresh Token Pattern with automatic session management"}),m?_jsxruntime.jsxs.call(void 0, "form",{onSubmit:u,children:[_jsxruntime.jsx.call(void 0, _material.TextField,{fullWidth:!0,label:"Email",type:"email",value:e,onChange:f=>t(f.target.value),margin:"normal",required:!0,autoComplete:"email"}),_jsxruntime.jsx.call(void 0, _material.TextField,{fullWidth:!0,label:"Password",type:"password",value:s,onChange:f=>a(f.target.value),margin:"normal",required:!0,autoComplete:"current-password"}),_jsxruntime.jsx.call(void 0, _material.Button,{type:"submit",fullWidth:!0,variant:"contained",size:"large",disabled:p,startIcon:p?_jsxruntime.jsx.call(void 0, _material.CircularProgress,{size:16}):null,sx:{mt:3,mb:2},children:p?"Logging in...":"Login"})]}):_jsxruntime.jsx.call(void 0, _material.Button,{fullWidth:!0,variant:"contained",size:"large",onClick:()=>n(!0),sx:{mt:2},children:"Show Login Form"}),l&&_jsxruntime.jsx.call(void 0, _material.Alert,{severity:"error",sx:{mt:2},onClose:d,children:l})]})}function Bi(){let{isAuthenticated:e,isLoading:t,isExpiringSoon:s,expiresIn:a}=_chunk2OSNNNIDjs.g.call(void 0, );return t?_jsxruntime.jsxs.call(void 0, _material.Box,{sx:{display:"flex",alignItems:"center",gap:1},children:[_jsxruntime.jsx.call(void 0, _material.CircularProgress,{size:16}),_jsxruntime.jsx.call(void 0, _material.Typography,{variant:"caption",children:"Loading session..."})]}):e?_jsxruntime.jsxs.call(void 0, _material.Box,{children:[_jsxruntime.jsx.call(void 0, _material.Typography,{variant:"caption",color:"success.main",children:"\u2713 Authenticated"}),s&&_jsxruntime.jsxs.call(void 0, _material.Typography,{variant:"caption",color:"warning.main",display:"block",children:["\u26A0 Token expires in ",Math.round(a/1e3/60)," min"]})]}):_jsxruntime.jsx.call(void 0, _material.Typography,{variant:"caption",color:"text.secondary",children:"Not logged in"})}exports.a = Wn; exports.b = Yr; exports.c = Ao; exports.d = Io; exports.e = Ti; exports.f = Ii; exports.g = Bi;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a as D,b as F,f as G,g as Y}from"./chunk-YS3C7YG5.mjs";import C from"crypto-js";var a=class a{static setStorageType(e){a.storageType=e}static generateEncryptionKey(){let e=[navigator.userAgent,navigator.language,navigator.platform,screen.width,screen.height,Date.now().toString(),Math.random().toString(36)].join("|");return C.SHA256(e).toString()}static getEncryptionKey(){if(a.encryptionKey)return a.encryptionKey;let e=window.localStorage;if(!e)return a.encryptionKey=a.generateEncryptionKey(),a.encryptionKey;try{let t=e.getItem(a.ENCRYPTION_KEY_STORAGE);return(!t||t.length<32)&&(t=a.generateEncryptionKey(),e.setItem(a.ENCRYPTION_KEY_STORAGE,t)),a.encryptionKey=t,t}catch{return console.warn("Crudify: Cannot persist encryption key, using temporary key"),a.encryptionKey=a.generateEncryptionKey(),a.encryptionKey}}static isStorageAvailable(e){try{let t=window[e],r="__storage_test__";return t.setItem(r,"test"),t.removeItem(r),!0}catch{return!1}}static getStorage(){return a.storageType==="none"?null:a.isStorageAvailable(a.storageType)?window[a.storageType]:(console.warn(`Crudify: ${a.storageType} not available, tokens won't persist`),null)}static encrypt(e){try{let t=a.getEncryptionKey();return C.AES.encrypt(e,t).toString()}catch(t){return console.error("Crudify: Encryption failed",t),e}}static decrypt(e){try{let t=a.getEncryptionKey();return C.AES.decrypt(e,t).toString(C.enc.Utf8)||e}catch(t){return console.error("Crudify: Decryption failed",t),e}}static saveTokens(e){let t=a.getStorage();if(t)try{let r={accessToken:e.accessToken,refreshToken:e.refreshToken,expiresAt:e.expiresAt,refreshExpiresAt:e.refreshExpiresAt,savedAt:Date.now()},i=a.encrypt(JSON.stringify(r));t.setItem(a.TOKEN_KEY,i),console.debug("Crudify: Tokens saved successfully")}catch(r){console.error("Crudify: Failed to save tokens",r)}}static getTokens(){let e=a.getStorage();if(!e)return null;try{let t=e.getItem(a.TOKEN_KEY);if(!t)return null;let r=a.decrypt(t),i=JSON.parse(r);return!i.accessToken||!i.refreshToken||!i.expiresAt||!i.refreshExpiresAt?(console.warn("Crudify: Incomplete token data found, clearing storage"),a.clearTokens(),null):Date.now()>=i.refreshExpiresAt?(console.info("Crudify: Refresh token expired, clearing storage"),a.clearTokens(),null):{accessToken:i.accessToken,refreshToken:i.refreshToken,expiresAt:i.expiresAt,refreshExpiresAt:i.refreshExpiresAt}}catch(t){return console.error("Crudify: Failed to retrieve tokens",t),a.clearTokens(),null}}static clearTokens(){let e=a.getStorage();if(e)try{e.removeItem(a.TOKEN_KEY),console.debug("Crudify: Tokens cleared from storage")}catch(t){console.error("Crudify: Failed to clear tokens",t)}}static rotateEncryptionKey(){try{a.clearTokens(),a.encryptionKey=null;let e=window.localStorage;e&&e.removeItem(a.ENCRYPTION_KEY_STORAGE),console.info("Crudify: Encryption key rotated successfully")}catch(e){console.error("Crudify: Failed to rotate encryption key",e)}}static hasValidTokens(){return a.getTokens()!==null}static getExpirationInfo(){let e=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 updateAccessToken(e,t){let r=a.getTokens();if(!r){console.warn("Crudify: Cannot update access token, no existing tokens found");return}a.saveTokens({...r,accessToken:e,expiresAt:t})}};a.TOKEN_KEY="crudify_tokens",a.ENCRYPTION_KEY_STORAGE="crudify_enc_key",a.encryptionKey=null,a.storageType="localStorage";var g=a;import m from"@nocios/crudify-browser";var P=class o{constructor(){this.config={};this.initialized=!1;this.lastActivityTime=0}static getInstance(){return o.instance||(o.instance=new o),o.instance}async initialize(e={}){if(this.initialized){console.warn("SessionManager: Already initialized");return}this.config={storageType:"localStorage",autoRestore:!0,enableLogging:!1,...e},g.setStorageType(this.config.storageType||"localStorage"),this.config.enableLogging,this.config.autoRestore&&await this.restoreSession(),this.initialized=!0,this.log("SessionManager initialized successfully")}async login(e,t){try{this.log("Attempting login...");let r=await m.login(e,t);if(!r.success)return this.log("Login failed:",r.errors),{success:!1,error:this.formatError(r.errors),rawResponse:r};let i={accessToken:r.data.token,refreshToken:r.data.refreshToken,expiresAt:r.data.expiresAt,refreshExpiresAt:r.data.refreshExpiresAt};return g.saveTokens(i),this.lastActivityTime=Date.now(),this.log("Login successful, tokens saved"),this.config.onLoginSuccess?.(i),{success:!0,tokens:i,data:r.data}}catch(r){return this.log("Login error:",r),{success:!1,error:r instanceof Error?r.message:"Unknown error"}}}async logout(){try{this.log("Logging out..."),await m.logout(),g.clearTokens(),this.log("Logout successful"),this.config.onLogout?.()}catch(e){this.log("Logout error:",e),g.clearTokens()}}async restoreSession(){try{this.log("Attempting to restore session...");let e=g.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"),g.clearTokens(),!1;if(m.setTokens({accessToken:e.accessToken,refreshToken:e.refreshToken,expiresAt:e.expiresAt,refreshExpiresAt:e.refreshExpiresAt}),m.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 i=g.getTokens();return i&&this.config.onSessionRestored?.(i),!0}return g.clearTokens(),await m.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:",e),g.clearTokens(),await m.logout(),!1}}isAuthenticated(){return m.isLogin()||g.hasValidTokens()}getTokenInfo(){let e=m.getTokenData(),t=g.getExpirationInfo();return{isLoggedIn:this.isAuthenticated(),crudifyTokens:e,storageInfo:t,hasValidTokens:g.hasValidTokens()}}async refreshTokens(){try{this.log("Manually refreshing tokens...");let e=await m.refreshAccessToken();if(!e.success)return this.log("Token refresh failed:",e.errors),g.clearTokens(),this.config.showNotification?.(this.getSessionExpiredMessage(),"warning"),this.config.onSessionExpired?.(),!1;let t={accessToken:e.data.token,refreshToken:e.data.refreshToken,expiresAt:e.data.expiresAt,refreshExpiresAt:e.data.refreshExpiresAt};return g.saveTokens(t),this.log("Tokens refreshed and saved successfully"),this.lastActivityTime=Date.now(),!0}catch(e){return this.log("Token refresh error:",e),g.clearTokens(),this.config.showNotification?.(this.getSessionExpiredMessage(),"warning"),this.config.onSessionExpired?.(),!1}}setupResponseInterceptor(){m.setResponseInterceptor(async e=>{this.updateLastActivity();let t=this.detectAuthorizationError(e);if(t.isAuthError){if(console.warn("\u{1F6A8} SessionManager - Authorization error detected:",{errorType:t.errorType,errorDetails:t.errorDetails,fullResponse:e}),t.isRefreshTokenInvalid||t.isTokenRefreshFailed)return this.log("Refresh token invalid or refresh already failed, clearing session"),g.clearTokens(),this.config.showNotification?.(this.getSessionExpiredMessage(),"warning"),this.config.onSessionExpired?.(),e;g.hasValidTokens()&&!t.isIrrecoverable?(this.log("Auth error detected, attempting token refresh..."),await this.refreshTokens()||(this.log("Token refresh failed, triggering session expired"),this.config.onSessionExpired?.())):(this.log("Auth error with no valid tokens or irrecoverable error, triggering session expired"),g.clearTokens(),this.config.showNotification?.(this.getSessionExpiredMessage(),"warning"),this.config.onSessionExpired?.())}return e}),this.log("Response interceptor configured")}detectAuthorizationError(e){let t={isAuthError:!1,isRefreshTokenInvalid:!1,isTokenRefreshFailed:!1,isIrrecoverable:!1,errorType:"",errorDetails:null};if(e.errors){if(Array.isArray(e.errors))e.errors.some(i=>i.errorType==="Unauthorized"||i.message?.includes("Unauthorized")||i.message?.includes("Not Authorized")||i.message?.includes("Token")||i.extensions?.code==="UNAUTHENTICATED"||i.message?.includes("NOT_AUTHORIZED"))&&(t.isAuthError=!0,t.errorType="GraphQL Array Format",t.errorDetails=e.errors);else if(typeof e.errors=="object"){let r=Object.values(e.errors).flat();r.some(u=>typeof u=="string"&&(u.includes("NOT_AUTHORIZED")||u.includes("TOKEN_REFRESH_FAILED")||u.includes("PLEASE_LOGIN")||u.includes("Unauthorized")||u.includes("UNAUTHENTICATED")||u.includes("Token")))&&(t.isAuthError=!0,t.errorType="GraphQL Object Format",t.errorDetails=e.errors,t.isTokenRefreshFailed=r.some(u=>typeof u=="string"&&u.includes("TOKEN_REFRESH_FAILED")))}}if(!t.isAuthError&&e.data?.response?.status==="UNAUTHORIZED"&&(t.isAuthError=!0,t.errorType="Status UNAUTHORIZED",t.errorDetails=e.data.response,t.isIrrecoverable=!0),!t.isAuthError&&e.data?.response?.data)try{let r=JSON.parse(e.data.response.data);(r.error==="REFRESH_TOKEN_INVALID"||r.error==="TOKEN_EXPIRED")&&(t.isAuthError=!0,t.errorType="Parsed Data Format",t.errorDetails=r,t.isRefreshTokenInvalid=!0,t.isIrrecoverable=!0)}catch{}if(!t.isAuthError&&e.errorCode){let r=e.errorCode;(r==="UNAUTHORIZED"||r==="UNAUTHENTICATED"||r==="TOKEN_EXPIRED")&&(t.isAuthError=!0,t.errorType="Error Code Format",t.errorDetails={errorCode:r})}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(),t=m.getTokenData();if(this.lastActivityTime===0)return"none";let r=900*1e3,i=300*1e3,u=300*1e3;return e>r?(this.log(`Inactivity timeout: ${Math.floor(e/6e4)} minutes since last activity`),"logout"):e<i&&t.expiresIn<u&&t.expiresIn>0?(this.log(`User active recently (${Math.floor(e/6e4)}min ago) and token expiring soon, should refresh`),"refresh"):"none"}clearSession(){g.clearTokens(),m.logout(),this.lastActivityTime=0,this.log("Session cleared completely")}getSessionExpiredMessage(){return this.config.translateFn?F("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&&console.log(`[SessionManager] ${e}`,...t)}formatError(e){return e?typeof e=="string"?e:typeof e=="object"?Object.values(e).flat().join(", "):"Authentication failed":"Unknown error"}};import{useState as ee,useEffect as V,useCallback as w}from"react";function j(o={}){let[e,t]=ee({isAuthenticated:!1,isLoading:!0,isInitialized:!1,tokens:null,error:null}),r=P.getInstance(),i=w(async()=>{try{t(s=>({...s,isLoading:!0,error:null}));let l={autoRestore:o.autoRestore??!0,enableLogging:o.enableLogging??!1,showNotification:o.showNotification,translateFn:o.translateFn,onSessionExpired:()=>{t(s=>({...s,isAuthenticated:!1,tokens:null,error:"Session expired"})),o.onSessionExpired?.()},onSessionRestored:s=>{t(d=>({...d,isAuthenticated:!0,tokens:s,error:null})),o.onSessionRestored?.(s)},onLoginSuccess:s=>{t(d=>({...d,isAuthenticated:!0,tokens:s,error:null}))},onLogout:()=>{t(s=>({...s,isAuthenticated:!1,tokens:null,error:null}))}};await r.initialize(l),r.setupResponseInterceptor();let n=r.isAuthenticated(),c=r.getTokenInfo();t(s=>({...s,isAuthenticated:n,isInitialized:!0,isLoading:!1,tokens:c.crudifyTokens.accessToken?{accessToken:c.crudifyTokens.accessToken,refreshToken:c.crudifyTokens.refreshToken,expiresAt:c.crudifyTokens.expiresAt,refreshExpiresAt:c.crudifyTokens.refreshExpiresAt}:null}))}catch(l){let n=l instanceof Error?l.message:"Initialization failed";t(c=>({...c,isLoading:!1,isInitialized:!0,error:n}))}},[o.autoRestore,o.enableLogging,o.onSessionExpired,o.onSessionRestored]),u=w(async(l,n)=>{t(c=>({...c,isLoading:!0,error:null}));try{let c=await r.login(l,n);return c.success&&c.tokens?t(s=>({...s,isAuthenticated:!0,tokens:c.tokens,isLoading:!1,error:null})):t(s=>({...s,isAuthenticated:!1,tokens:null,isLoading:!1,error:null})),c}catch(c){let s=c instanceof Error?c.message:"Login failed",d=s.includes("INVALID_CREDENTIALS")||s.includes("Invalid email")||s.includes("Invalid password")||s.includes("credentials");return t(T=>({...T,isAuthenticated:!1,tokens:null,isLoading:!1,error:d?null:s})),{success:!1,error:s}}},[r]),v=w(async()=>{t(l=>({...l,isLoading:!0}));try{await r.logout(),t(l=>({...l,isAuthenticated:!1,tokens:null,isLoading:!1,error:null}))}catch(l){t(n=>({...n,isAuthenticated:!1,tokens:null,isLoading:!1,error:l instanceof Error?l.message:"Logout error"}))}},[r]),p=w(async()=>{try{let l=await r.refreshTokens();if(l){let n=r.getTokenInfo();t(c=>({...c,tokens:n.crudifyTokens.accessToken?{accessToken:n.crudifyTokens.accessToken,refreshToken:n.crudifyTokens.refreshToken,expiresAt:n.crudifyTokens.expiresAt,refreshExpiresAt:n.crudifyTokens.refreshExpiresAt}:null,error:null}))}else t(n=>({...n,isAuthenticated:!1,tokens:null,error:"Token refresh failed"}));return l}catch(l){return t(n=>({...n,isAuthenticated:!1,tokens:null,error:l instanceof Error?l.message:"Token refresh failed"})),!1}},[r]),x=w(()=>{t(l=>({...l,error:null}))},[]),k=w(()=>r.getTokenInfo(),[r]);V(()=>{i()},[i]),V(()=>{if(!e.isAuthenticated||!e.tokens)return;let l=()=>{r.updateLastActivity(),o.enableLogging&&console.log("\u{1F4CD} User navigating - activity updated")};window.addEventListener("popstate",l);let n=window.history.pushState,c=window.history.replaceState;window.history.pushState=function(...d){let T=n.apply(this,d);return l(),T},window.history.replaceState=function(...d){let T=c.apply(this,d);return l(),T};let s=setInterval(async()=>{let d=r.checkInactivity();if(d==="logout")o.enableLogging&&console.log("\u23F1\uFE0F Inactivity timeout - logging out user"),await v();else if(d==="refresh"&&(o.enableLogging&&console.log("\u{1F504} User active, token expiring soon - refreshing..."),await r.refreshTokens())){let h=r.getTokenInfo();t(b=>({...b,tokens:h.crudifyTokens.accessToken?{accessToken:h.crudifyTokens.accessToken,refreshToken:h.crudifyTokens.refreshToken,expiresAt:h.crudifyTokens.expiresAt,refreshExpiresAt:h.crudifyTokens.refreshExpiresAt}:null}))}},120*1e3);return()=>{clearInterval(s),window.removeEventListener("popstate",l),window.history.pushState=n,window.history.replaceState=c}},[e.isAuthenticated,e.tokens,r,o.enableLogging,v]);let S=w(()=>{r.updateLastActivity()},[r]);return{...e,login:u,logout:v,refreshTokens:p,clearError:x,getTokenInfo:k,updateActivity:S,isExpiringSoon:e.tokens?e.tokens.expiresAt-Date.now()<300*1e3:!1,expiresIn:e.tokens?Math.max(0,e.tokens.expiresAt-Date.now()):0,refreshExpiresIn:e.tokens?Math.max(0,e.tokens.refreshExpiresAt-Date.now()):0}}import{useState as W,createContext as te,useContext as re,useCallback as O,useEffect as oe}from"react";import{Snackbar as ne,Alert as ie,Box as se,Portal as ae}from"@mui/material";import{v4 as ce}from"uuid";import le from"dompurify";import{jsx as I,jsxs as de}from"react/jsx-runtime";var B=te(null),ue=o=>le.sanitize(o,{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}),J=({children:o,maxNotifications:e=5,defaultAutoHideDuration:t=6e3,position:r={vertical:"top",horizontal:"right"},enabled:i=!1,allowHtml:u=!1})=>{let[v,p]=W([]),x=O((n,c="info",s)=>{if(!i)return"";if(!n||typeof n!="string")return console.warn("\u26A0\uFE0F GlobalNotificationProvider: Invalid message provided"),"";n.length>1e3&&(console.warn("\u26A0\uFE0F GlobalNotificationProvider: Message too long, truncating"),n=n.substring(0,1e3)+"...");let d=ce(),T={id:d,message:n,severity:c,autoHideDuration:s?.autoHideDuration??t,persistent:s?.persistent??!1,allowHtml:s?.allowHtml??u};return p(h=>[...h.length>=e?h.slice(-(e-1)):h,T]),d},[e,t,i,u]),k=O(n=>{p(c=>c.filter(s=>s.id!==n))},[]),S=O(()=>{p([])},[]),l={showNotification:x,hideNotification:k,clearAllNotifications:S};return de(B.Provider,{value:l,children:[o,i&&I(ae,{children:I(se,{sx:{position:"fixed",zIndex:9999,[r.vertical]:(r.vertical==="top",24),[r.horizontal]:r.horizontal==="right"||r.horizontal==="left"?24:"50%",...r.horizontal==="center"&&{transform:"translateX(-50%)"},display:"flex",flexDirection:r.vertical==="top"?"column":"column-reverse",gap:1,maxWidth:"400px",width:"auto"},children:v.map(n=>I(fe,{notification:n,onClose:()=>k(n.id)},n.id))})})]})},fe=({notification:o,onClose:e})=>{let[t,r]=W(!0),i=O((u,v)=>{v!=="clickaway"&&(r(!1),setTimeout(e,300))},[e]);return oe(()=>{if(!o.persistent&&o.autoHideDuration){let u=setTimeout(()=>{i()},o.autoHideDuration);return()=>clearTimeout(u)}},[o.autoHideDuration,o.persistent,i]),I(ne,{open:t,onClose:i,sx:{position:"relative","& .MuiSnackbarContent-root":{minWidth:"auto"}},TransitionProps:{enter:!0,exit:!0},children:I(ie,{variant:"filled",severity:o.severity,onClose:i,sx:{width:"100%",minWidth:"280px",maxWidth:"400px",wordBreak:"break-word"},children:o.allowHtml?I("span",{dangerouslySetInnerHTML:{__html:ue(o.message)}}):I("span",{children:o.message})})})},_=()=>{let o=re(B);if(!o)throw new Error("useGlobalNotification debe ser usado dentro de un GlobalNotificationProvider");return o};import ge,{createContext as pe,useContext as he,useMemo as $}from"react";import{Fragment as M,jsx as y,jsxs as A}from"react/jsx-runtime";var X=pe(void 0);function ye({children:o,options:e={},config:t,showNotifications:r=!1,notificationOptions:i={}}){let u;try{let{showNotification:n}=_();u=n}catch{}let v=ge.useMemo(()=>({...e,showNotification:u,onSessionExpired:()=>{e.onSessionExpired?.()}}),[e,u]),p=j(v),x=$(()=>{let n,c,s,d,T,h="unknown";if(t?.publicApiKey&&(n=t.publicApiKey,h="props"),t?.env&&(c=t.env),t?.appName&&(s=t.appName),t?.loginActions&&(d=t.loginActions),t?.logo&&(T=t.logo),!n){let b=D("publicApiKey"),N=D("environment"),R=D("appName"),E=D("loginActions"),f=D("logo");b&&(n=b,h="cookies"),N&&["dev","stg","prod"].includes(N)&&(c=N),R&&(s=decodeURIComponent(R)),E&&(d=decodeURIComponent(E).split(",").map(L=>L.trim()).filter(Boolean)),f&&(T=decodeURIComponent(f))}return{publicApiKey:n,env:c,appName:s,loginActions:d,logo:T}},[t]),k=$(()=>{if(!p.tokens?.accessToken||!p.isAuthenticated)return null;try{let n=G(p.tokens.accessToken);if(n&&n.sub&&n.email&&n.subscriber){let c={_id:n.sub,email:n.email,subscriberKey:n.subscriber};return Object.keys(n).forEach(s=>{["sub","email","subscriber"].includes(s)||(c[s]=n[s])}),c}}catch(n){console.error("Error decoding JWT token for sessionData:",n)}return null},[p.tokens?.accessToken,p.isAuthenticated]),S={...p,sessionData:k,config:x},l={enabled:r,maxNotifications:i.maxNotifications||5,defaultAutoHideDuration:i.defaultAutoHideDuration||6e3,position:i.position||{vertical:"top",horizontal:"right"}};return y(X.Provider,{value:S,children:o})}function Be(o){let e={enabled:o.showNotifications,maxNotifications:o.notificationOptions?.maxNotifications||5,defaultAutoHideDuration:o.notificationOptions?.defaultAutoHideDuration||6e3,position:o.notificationOptions?.position||{vertical:"top",horizontal:"right"},allowHtml:o.notificationOptions?.allowHtml||!1};return y(J,{...e,children:y(ye,{...o})})}function Z(){let o=he(X);if(o===void 0)throw new Error("useSessionContext must be used within a SessionProvider");return o}function Je({children:o,fallback:e=y("div",{children:"Please log in to access this content"}),redirectTo:t}){let{isAuthenticated:r,isLoading:i,isInitialized:u}=Z();return!u||i?y("div",{children:"Loading..."}):r?y(M,{children:o}):t?(t(),null):y(M,{children:e})}function _e(){let o=Z();return o.isInitialized?A("div",{style:{padding:"10px",margin:"10px",border:"1px solid #ccc",borderRadius:"4px",fontSize:"12px",fontFamily:"monospace"},children:[y("h4",{children:"Session Debug Info"}),A("div",{children:[y("strong",{children:"Authenticated:"})," ",o.isAuthenticated?"Yes":"No"]}),A("div",{children:[y("strong",{children:"Loading:"})," ",o.isLoading?"Yes":"No"]}),A("div",{children:[y("strong",{children:"Error:"})," ",o.error||"None"]}),o.tokens&&A(M,{children:[A("div",{children:[y("strong",{children:"Access Token:"})," ",o.tokens.accessToken.substring(0,20),"..."]}),A("div",{children:[y("strong",{children:"Refresh Token:"})," ",o.tokens.refreshToken.substring(0,20),"..."]}),A("div",{children:[y("strong",{children:"Access Expires In:"})," ",Math.round(o.expiresIn/1e3/60)," minutes"]}),A("div",{children:[y("strong",{children:"Refresh Expires In:"})," ",Math.round(o.refreshExpiresIn/1e3/60/60)," hours"]}),A("div",{children:[y("strong",{children:"Expiring Soon:"})," ",o.isExpiringSoon?"Yes":"No"]})]})]}):y("div",{children:"Session not initialized"})}import{useState as U,useEffect as q,useCallback as Q,useRef as K}from"react";import Te from"@nocios/crudify-browser";var et=(o={})=>{let{autoFetch:e=!0,retryOnError:t=!1,maxRetries:r=3}=o,[i,u]=U(null),[v,p]=U(!1),[x,k]=U(null),[S,l]=U({}),n=K(null),c=K(!0),s=K(0),d=K(0),T=Q(()=>{u(null),k(null),p(!1),l({})},[]),h=Q(async()=>{let b=Y();if(!b){c.current&&(k("No user email available"),p(!1));return}n.current&&n.current.abort();let N=new AbortController;n.current=N;let R=++s.current;try{c.current&&(p(!0),k(null));let E=await Te.readItems("users",{filter:{email:b},pagination:{limit:1}});if(R===s.current&&c.current&&!N.signal.aborted)if(E.success&&E.data&&E.data.length>0){let f=E.data[0];u(f);let H={fullProfile:f,totalFields:Object.keys(f).length,displayData:{id:f.id,email:f.email,username:f.username,firstName:f.firstName,lastName:f.lastName,fullName:f.fullName||`${f.firstName||""} ${f.lastName||""}`.trim(),role:f.role,permissions:f.permissions||[],isActive:f.isActive,lastLogin:f.lastLogin,createdAt:f.createdAt,updatedAt:f.updatedAt,...Object.keys(f).filter(L=>!["id","email","username","firstName","lastName","fullName","role","permissions","isActive","lastLogin","createdAt","updatedAt"].includes(L)).reduce((L,z)=>({...L,[z]:f[z]}),{})}};l(H),k(null),d.current=0}else k("User profile not found"),u(null),l({})}catch(E){if(R===s.current&&c.current){let f=E;if(f.name==="AbortError")return;t&&d.current<r&&(f.message?.includes("Network Error")||f.message?.includes("Failed to fetch"))?(d.current++,setTimeout(()=>{c.current&&h()},1e3*d.current)):(k("Failed to load user profile"),u(null),l({}))}}finally{R===s.current&&c.current&&p(!1),n.current===N&&(n.current=null)}},[t,r]);return q(()=>{e&&h()},[e,h]),q(()=>(c.current=!0,()=>{c.current=!1,n.current&&(n.current.abort(),n.current=null)}),[]),{userProfile:i,loading:v,error:x,extendedData:S,refreshProfile:h,clearProfile:T}};export{g as a,P as b,j as c,J as d,_ as e,Be as f,Z as g,Je as h,_e as i,et as j};
|
package/dist/components.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports, "__esModule", {value: true});var
|
|
1
|
+
"use strict";Object.defineProperty(exports, "__esModule", {value: true});var _chunkQ7FTH5JWjs = require('./chunk-Q7FTH5JW.js');var _chunk2OSNNNIDjs = require('./chunk-2OSNNNID.js');require('./chunk-YIIUEOXC.js');require('./chunk-6EBMA4HZ.js');exports.CrudifyLogin = _chunkQ7FTH5JWjs.a; exports.GlobalNotificationProvider = _chunk2OSNNNIDjs.d; exports.LoginComponent = _chunkQ7FTH5JWjs.f; exports.Policies = _chunkQ7FTH5JWjs.e; exports.SessionStatus = _chunkQ7FTH5JWjs.g; exports.UserProfileDisplay = _chunkQ7FTH5JWjs.b; exports.useGlobalNotification = _chunk2OSNNNIDjs.e;
|
package/dist/components.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as r,b as t,e,f,g as n}from"./chunk-
|
|
1
|
+
import{a as r,b as t,e,f,g as n}from"./chunk-5PZJJNHP.mjs";import{d as o,e as i}from"./chunk-VVXZWBHL.mjs";import"./chunk-BJ6PIVZR.mjs";import"./chunk-YS3C7YG5.mjs";export{r as CrudifyLogin,o as GlobalNotificationProvider,f as LoginComponent,e as Policies,n as SessionStatus,t as UserProfileDisplay,i as useGlobalNotification};
|
package/dist/hooks.d.mts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export { d as SessionState, j as UseAuthReturn, l as UseDataReturn, U as UseSessionOptions, g as UseUserDataOptions, f as UseUserDataReturn, h as UserData, i as useAuth, n as useCrudifyWithNotifications, k as useData, u as useSession, e as useUserData, m as useUserProfile } from './index-
|
|
1
|
+
export { d as SessionState, j as UseAuthReturn, l as UseDataReturn, U as UseSessionOptions, g as UseUserDataOptions, f as UseUserDataReturn, h as UserData, i as useAuth, n as useCrudifyWithNotifications, k as useData, u as useSession, e as useUserData, m as useUserProfile } from './index-BoWx_rFw.mjs';
|
|
2
2
|
import './api-Djqihi4n.mjs';
|
|
3
3
|
import './GlobalNotificationProvider-C3iWgM1z.mjs';
|
|
4
4
|
import 'react';
|
package/dist/hooks.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export { d as SessionState, j as UseAuthReturn, l as UseDataReturn, U as UseSessionOptions, g as UseUserDataOptions, f as UseUserDataReturn, h as UserData, i as useAuth, n as useCrudifyWithNotifications, k as useData, u as useSession, e as useUserData, m as useUserProfile } from './index-
|
|
1
|
+
export { d as SessionState, j as UseAuthReturn, l as UseDataReturn, U as UseSessionOptions, g as UseUserDataOptions, f as UseUserDataReturn, h as UserData, i as useAuth, n as useCrudifyWithNotifications, k as useData, u as useSession, e as useUserData, m as useUserProfile } from './index-CQttyYlB.js';
|
|
2
2
|
import './api-Djqihi4n.js';
|
|
3
3
|
import './GlobalNotificationProvider-C3iWgM1z.js';
|
|
4
4
|
import 'react';
|
package/dist/hooks.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports, "__esModule", {value: true});var
|
|
1
|
+
"use strict";Object.defineProperty(exports, "__esModule", {value: true});var _chunk3SLGRD36js = require('./chunk-3SLGRD36.js');var _chunk2OSNNNIDjs = require('./chunk-2OSNNNID.js');require('./chunk-6EBMA4HZ.js');exports.useAuth = _chunk3SLGRD36js.b; exports.useCrudifyWithNotifications = _chunk3SLGRD36js.d; exports.useData = _chunk3SLGRD36js.c; exports.useSession = _chunk2OSNNNIDjs.c; exports.useUserData = _chunk3SLGRD36js.a; exports.useUserProfile = _chunk2OSNNNIDjs.j;
|
package/dist/hooks.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as s,b as r,c as o,d as a}from"./chunk-
|
|
1
|
+
import{a as s,b as r,c as o,d as a}from"./chunk-5INZZQD6.mjs";import{c as e,j as t}from"./chunk-VVXZWBHL.mjs";import"./chunk-YS3C7YG5.mjs";export{r as useAuth,a as useCrudifyWithNotifications,o as useData,e as useSession,s as useUserData,t as useUserProfile};
|
|
@@ -99,6 +99,7 @@ declare class SessionManager {
|
|
|
99
99
|
private static instance;
|
|
100
100
|
private config;
|
|
101
101
|
private initialized;
|
|
102
|
+
private lastActivityTime;
|
|
102
103
|
private constructor();
|
|
103
104
|
static getInstance(): SessionManager;
|
|
104
105
|
/**
|
|
@@ -157,6 +158,20 @@ declare class SessionManager {
|
|
|
157
158
|
* Detectar errores de autorización en todos los formatos posibles
|
|
158
159
|
*/
|
|
159
160
|
private detectAuthorizationError;
|
|
161
|
+
/**
|
|
162
|
+
* ✅ FASE 2: Actualizar timestamp de última actividad del usuario
|
|
163
|
+
* Debe llamarse cuando el usuario realiza cualquier acción (CRUD, navegación, etc.)
|
|
164
|
+
*/
|
|
165
|
+
updateLastActivity(): void;
|
|
166
|
+
/**
|
|
167
|
+
* ✅ FASE 2: Obtener tiempo transcurrido desde última actividad (en milisegundos)
|
|
168
|
+
*/
|
|
169
|
+
getTimeSinceLastActivity(): number;
|
|
170
|
+
/**
|
|
171
|
+
* ✅ FASE 2: Verificar inactividad y determinar acción necesaria
|
|
172
|
+
* @returns 'logout' si debe desloguear, 'refresh' si debe renovar, 'none' si no hace nada
|
|
173
|
+
*/
|
|
174
|
+
checkInactivity(): "logout" | "refresh" | "none";
|
|
160
175
|
/**
|
|
161
176
|
* Limpiar sesión completamente
|
|
162
177
|
*/
|
|
@@ -210,6 +225,7 @@ declare function useSession(options?: UseSessionOptions): {
|
|
|
210
225
|
} | null;
|
|
211
226
|
hasValidTokens: boolean;
|
|
212
227
|
};
|
|
228
|
+
updateActivity: () => void;
|
|
213
229
|
isExpiringSoon: boolean;
|
|
214
230
|
expiresIn: number;
|
|
215
231
|
refreshExpiresIn: number;
|
|
@@ -99,6 +99,7 @@ declare class SessionManager {
|
|
|
99
99
|
private static instance;
|
|
100
100
|
private config;
|
|
101
101
|
private initialized;
|
|
102
|
+
private lastActivityTime;
|
|
102
103
|
private constructor();
|
|
103
104
|
static getInstance(): SessionManager;
|
|
104
105
|
/**
|
|
@@ -157,6 +158,20 @@ declare class SessionManager {
|
|
|
157
158
|
* Detectar errores de autorización en todos los formatos posibles
|
|
158
159
|
*/
|
|
159
160
|
private detectAuthorizationError;
|
|
161
|
+
/**
|
|
162
|
+
* ✅ FASE 2: Actualizar timestamp de última actividad del usuario
|
|
163
|
+
* Debe llamarse cuando el usuario realiza cualquier acción (CRUD, navegación, etc.)
|
|
164
|
+
*/
|
|
165
|
+
updateLastActivity(): void;
|
|
166
|
+
/**
|
|
167
|
+
* ✅ FASE 2: Obtener tiempo transcurrido desde última actividad (en milisegundos)
|
|
168
|
+
*/
|
|
169
|
+
getTimeSinceLastActivity(): number;
|
|
170
|
+
/**
|
|
171
|
+
* ✅ FASE 2: Verificar inactividad y determinar acción necesaria
|
|
172
|
+
* @returns 'logout' si debe desloguear, 'refresh' si debe renovar, 'none' si no hace nada
|
|
173
|
+
*/
|
|
174
|
+
checkInactivity(): "logout" | "refresh" | "none";
|
|
160
175
|
/**
|
|
161
176
|
* Limpiar sesión completamente
|
|
162
177
|
*/
|
|
@@ -210,6 +225,7 @@ declare function useSession(options?: UseSessionOptions): {
|
|
|
210
225
|
} | null;
|
|
211
226
|
hasValidTokens: boolean;
|
|
212
227
|
};
|
|
228
|
+
updateActivity: () => void;
|
|
213
229
|
isExpiringSoon: boolean;
|
|
214
230
|
expiresIn: number;
|
|
215
231
|
refreshExpiresIn: number;
|
package/dist/index.d.mts
CHANGED
|
@@ -2,8 +2,8 @@ export * from '@nocios/crudify-browser';
|
|
|
2
2
|
export { default as crudify } from '@nocios/crudify-browser';
|
|
3
3
|
export { B as BoxScreenType, C as CrudifyLogin, d as CrudifyLoginConfig, e as CrudifyLoginProps, f as CrudifyLoginTranslations, L as LoginComponent, a as POLICY_ACTIONS, b as PREFERRED_POLICY_ORDER, P as Policies, c as PolicyAction, S as SessionStatus, g as UserLoginData, U as UserProfileDisplay } from './index-CY6Qkw3q.mjs';
|
|
4
4
|
export { A as ApiError, C as CrudifyApiResponse, a as CrudifyTransactionResponse, F as ForgotPasswordRequest, J as JwtPayload, b as LoginRequest, L as LoginResponse, R as ResetPasswordRequest, T as TransactionResponseData, U as UserProfile, V as ValidateCodeRequest, c as ValidationError } from './api-Djqihi4n.mjs';
|
|
5
|
-
import { U as UseSessionOptions, T as TokenData, L as LoginResult } from './index-
|
|
6
|
-
export { a as SessionConfig, S as SessionManager, d as SessionState, c as StorageType, b as TokenStorage, j as UseAuthReturn, l as UseDataReturn, g as UseUserDataOptions, f as UseUserDataReturn, h as UserData, i as useAuth, n as useCrudifyWithNotifications, k as useData, u as useSession, e as useUserData, m as useUserProfile } from './index-
|
|
5
|
+
import { U as UseSessionOptions, T as TokenData, L as LoginResult } from './index-BoWx_rFw.mjs';
|
|
6
|
+
export { a as SessionConfig, S as SessionManager, d as SessionState, c as StorageType, b as TokenStorage, j as UseAuthReturn, l as UseDataReturn, g as UseUserDataOptions, f as UseUserDataReturn, h as UserData, i as useAuth, n as useCrudifyWithNotifications, k as useData, u as useSession, e as useUserData, m as useUserProfile } from './index-BoWx_rFw.mjs';
|
|
7
7
|
import * as react_jsx_runtime from 'react/jsx-runtime';
|
|
8
8
|
import { ReactNode } from 'react';
|
|
9
9
|
export { ERROR_CODES, ERROR_SEVERITY_MAP, ErrorCode, ErrorSeverity, ErrorTranslationConfig, ParsedError, createErrorTranslator, decodeJwtSafely, getCookie, getCurrentUserEmail, getErrorMessage, handleCrudifyError, isTokenExpired, parseApiError, parseJavaScriptError, parseTransactionError, secureLocalStorage, secureSessionStorage, translateError, translateErrorCode, translateErrorCodes } from './utils.mjs';
|
package/dist/index.d.ts
CHANGED
|
@@ -2,8 +2,8 @@ export * from '@nocios/crudify-browser';
|
|
|
2
2
|
export { default as crudify } from '@nocios/crudify-browser';
|
|
3
3
|
export { B as BoxScreenType, C as CrudifyLogin, d as CrudifyLoginConfig, e as CrudifyLoginProps, f as CrudifyLoginTranslations, L as LoginComponent, a as POLICY_ACTIONS, b as PREFERRED_POLICY_ORDER, P as Policies, c as PolicyAction, S as SessionStatus, g as UserLoginData, U as UserProfileDisplay } from './index-DxFMT2hN.js';
|
|
4
4
|
export { A as ApiError, C as CrudifyApiResponse, a as CrudifyTransactionResponse, F as ForgotPasswordRequest, J as JwtPayload, b as LoginRequest, L as LoginResponse, R as ResetPasswordRequest, T as TransactionResponseData, U as UserProfile, V as ValidateCodeRequest, c as ValidationError } from './api-Djqihi4n.js';
|
|
5
|
-
import { U as UseSessionOptions, T as TokenData, L as LoginResult } from './index-
|
|
6
|
-
export { a as SessionConfig, S as SessionManager, d as SessionState, c as StorageType, b as TokenStorage, j as UseAuthReturn, l as UseDataReturn, g as UseUserDataOptions, f as UseUserDataReturn, h as UserData, i as useAuth, n as useCrudifyWithNotifications, k as useData, u as useSession, e as useUserData, m as useUserProfile } from './index-
|
|
5
|
+
import { U as UseSessionOptions, T as TokenData, L as LoginResult } from './index-CQttyYlB.js';
|
|
6
|
+
export { a as SessionConfig, S as SessionManager, d as SessionState, c as StorageType, b as TokenStorage, j as UseAuthReturn, l as UseDataReturn, g as UseUserDataOptions, f as UseUserDataReturn, h as UserData, i as useAuth, n as useCrudifyWithNotifications, k as useData, u as useSession, e as useUserData, m as useUserProfile } from './index-CQttyYlB.js';
|
|
7
7
|
import * as react_jsx_runtime from 'react/jsx-runtime';
|
|
8
8
|
import { ReactNode } from 'react';
|
|
9
9
|
export { ERROR_CODES, ERROR_SEVERITY_MAP, ErrorCode, ErrorSeverity, ErrorTranslationConfig, ParsedError, createErrorTranslator, decodeJwtSafely, getCookie, getCurrentUserEmail, getErrorMessage, handleCrudifyError, isTokenExpired, parseApiError, parseJavaScriptError, parseTransactionError, secureLocalStorage, secureSessionStorage, translateError, translateErrorCode, translateErrorCodes } from './utils.js';
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _createStarExport(obj) { Object.keys(obj) .filter((key) => key !== "default" && key !== "__esModule") .forEach((key) => { if (exports.hasOwnProperty(key)) { return; } Object.defineProperty(exports, key, {enumerable: true, configurable: true, get: () => obj[key]}); }); }var
|
|
1
|
+
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _createStarExport(obj) { Object.keys(obj) .filter((key) => key !== "default" && key !== "__esModule") .forEach((key) => { if (exports.hasOwnProperty(key)) { return; } Object.defineProperty(exports, key, {enumerable: true, configurable: true, get: () => obj[key]}); }); }var _chunkQ7FTH5JWjs = require('./chunk-Q7FTH5JW.js');var _chunk3SLGRD36js = require('./chunk-3SLGRD36.js');var _chunk2OSNNNIDjs = require('./chunk-2OSNNNID.js');var _chunkNNY4A73Vjs = require('./chunk-NNY4A73V.js');var _chunkYIIUEOXCjs = require('./chunk-YIIUEOXC.js');var _chunk6EBMA4HZjs = require('./chunk-6EBMA4HZ.js');var _crudifybrowser = require('@nocios/crudify-browser'); var _crudifybrowser2 = _interopRequireDefault(_crudifybrowser); _createStarExport(_crudifybrowser);exports.CrudifyLogin = _chunkQ7FTH5JWjs.a; exports.ERROR_CODES = _chunkYIIUEOXCjs.a; exports.ERROR_SEVERITY_MAP = _chunkYIIUEOXCjs.b; exports.GlobalNotificationProvider = _chunk2OSNNNIDjs.d; exports.LoginComponent = _chunkQ7FTH5JWjs.f; exports.POLICY_ACTIONS = _chunkQ7FTH5JWjs.c; exports.PREFERRED_POLICY_ORDER = _chunkQ7FTH5JWjs.d; exports.Policies = _chunkQ7FTH5JWjs.e; exports.ProtectedRoute = _chunk2OSNNNIDjs.h; exports.SessionDebugInfo = _chunk2OSNNNIDjs.i; exports.SessionManager = _chunk2OSNNNIDjs.b; exports.SessionProvider = _chunk2OSNNNIDjs.f; exports.SessionStatus = _chunkQ7FTH5JWjs.g; exports.TokenStorage = _chunk2OSNNNIDjs.a; exports.UserProfileDisplay = _chunkQ7FTH5JWjs.b; exports.createErrorTranslator = _chunk6EBMA4HZjs.e; exports.crudify = _crudifybrowser2.default; exports.decodeJwtSafely = _chunk6EBMA4HZjs.f; exports.getCookie = _chunk6EBMA4HZjs.a; exports.getCurrentUserEmail = _chunk6EBMA4HZjs.g; exports.getErrorMessage = _chunkYIIUEOXCjs.e; exports.handleCrudifyError = _chunkYIIUEOXCjs.g; exports.isTokenExpired = _chunk6EBMA4HZjs.h; exports.parseApiError = _chunkYIIUEOXCjs.c; exports.parseJavaScriptError = _chunkYIIUEOXCjs.f; exports.parseTransactionError = _chunkYIIUEOXCjs.d; exports.secureLocalStorage = _chunkNNY4A73Vjs.b; exports.secureSessionStorage = _chunkNNY4A73Vjs.a; exports.translateError = _chunk6EBMA4HZjs.d; exports.translateErrorCode = _chunk6EBMA4HZjs.b; exports.translateErrorCodes = _chunk6EBMA4HZjs.c; exports.useAuth = _chunk3SLGRD36js.b; exports.useCrudifyWithNotifications = _chunk3SLGRD36js.d; exports.useData = _chunk3SLGRD36js.c; exports.useGlobalNotification = _chunk2OSNNNIDjs.e; exports.useSession = _chunk2OSNNNIDjs.c; exports.useSessionContext = _chunk2OSNNNIDjs.g; exports.useUserData = _chunk3SLGRD36js.a; exports.useUserProfile = _chunk2OSNNNIDjs.j;
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as U,b as L,c as v,d as O,e as h,f as k,g as A}from"./chunk-
|
|
1
|
+
import{a as U,b as L,c as v,d as O,e as h,f as k,g as A}from"./chunk-5PZJJNHP.mjs";import{a as N,b,c as _,d as w}from"./chunk-5INZZQD6.mjs";import{a as r,b as a,c as n,d as m,e as l,f as x,g as d,h as y,i as c,j as T}from"./chunk-VVXZWBHL.mjs";import{a as I,b as q}from"./chunk-T2CPA46I.mjs";import{a as S,b as P,c as R,d as g,e as E,f as C,g as D}from"./chunk-BJ6PIVZR.mjs";import{a as o,b as e,c as t,d as s,e as i,f as p,g as f,h as u}from"./chunk-YS3C7YG5.mjs";import{default as J}from"@nocios/crudify-browser";export*from"@nocios/crudify-browser";export{U as CrudifyLogin,S as ERROR_CODES,P as ERROR_SEVERITY_MAP,m as GlobalNotificationProvider,k as LoginComponent,v as POLICY_ACTIONS,O as PREFERRED_POLICY_ORDER,h as Policies,y as ProtectedRoute,c as SessionDebugInfo,a as SessionManager,x as SessionProvider,A as SessionStatus,r as TokenStorage,L as UserProfileDisplay,i as createErrorTranslator,J as crudify,p as decodeJwtSafely,o as getCookie,f as getCurrentUserEmail,E as getErrorMessage,D as handleCrudifyError,u as isTokenExpired,R as parseApiError,C as parseJavaScriptError,g as parseTransactionError,q as secureLocalStorage,I as secureSessionStorage,s as translateError,e as translateErrorCode,t as translateErrorCodes,b as useAuth,w as useCrudifyWithNotifications,_ as useData,l as useGlobalNotification,n as useSession,d as useSessionContext,N as useUserData,T as useUserProfile};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@nocios/crudify-ui",
|
|
3
|
-
"version": "4.0.
|
|
3
|
+
"version": "4.0.94",
|
|
4
4
|
"description": "Biblioteca de componentes UI para Crudify",
|
|
5
5
|
"author": "Nocios",
|
|
6
6
|
"license": "MIT",
|
|
@@ -36,7 +36,7 @@
|
|
|
36
36
|
"prepublishOnly": "npm run build"
|
|
37
37
|
},
|
|
38
38
|
"dependencies": {
|
|
39
|
-
"@nocios/crudify-browser": "^4.0.
|
|
39
|
+
"@nocios/crudify-browser": "^4.0.4",
|
|
40
40
|
"crypto-js": "^4.2.0",
|
|
41
41
|
"dompurify": "^3.2.7",
|
|
42
42
|
"uuid": "^13.0.0"
|
package/dist/chunk-EP4KANK7.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 _chunk6EBMA4HZjs = require('./chunk-6EBMA4HZ.js');var _cryptojs = require('crypto-js'); var _cryptojs2 = _interopRequireDefault(_cryptojs);var i=class i{static setStorageType(e){i.storageType=e}static generateEncryptionKey(){let e=[navigator.userAgent,navigator.language,navigator.platform,screen.width,screen.height,Date.now().toString(),Math.random().toString(36)].join("|");return _cryptojs2.default.SHA256(e).toString()}static getEncryptionKey(){if(i.encryptionKey)return i.encryptionKey;let e=window.localStorage;if(!e)return i.encryptionKey=i.generateEncryptionKey(),i.encryptionKey;try{let t=e.getItem(i.ENCRYPTION_KEY_STORAGE);return(!t||t.length<32)&&(t=i.generateEncryptionKey(),e.setItem(i.ENCRYPTION_KEY_STORAGE,t)),i.encryptionKey=t,t}catch (e2){return console.warn("Crudify: Cannot persist encryption key, using temporary key"),i.encryptionKey=i.generateEncryptionKey(),i.encryptionKey}}static isStorageAvailable(e){try{let t=window[e],r="__storage_test__";return t.setItem(r,"test"),t.removeItem(r),!0}catch (e3){return!1}}static getStorage(){return i.storageType==="none"?null:i.isStorageAvailable(i.storageType)?window[i.storageType]:(console.warn(`Crudify: ${i.storageType} not available, tokens won't persist`),null)}static encrypt(e){try{let t=i.getEncryptionKey();return _cryptojs2.default.AES.encrypt(e,t).toString()}catch(t){return console.error("Crudify: Encryption failed",t),e}}static decrypt(e){try{let t=i.getEncryptionKey();return _cryptojs2.default.AES.decrypt(e,t).toString(_cryptojs2.default.enc.Utf8)||e}catch(t){return console.error("Crudify: Decryption failed",t),e}}static saveTokens(e){let t=i.getStorage();if(t)try{let r={accessToken:e.accessToken,refreshToken:e.refreshToken,expiresAt:e.expiresAt,refreshExpiresAt:e.refreshExpiresAt,savedAt:Date.now()},s=i.encrypt(JSON.stringify(r));t.setItem(i.TOKEN_KEY,s),console.debug("Crudify: Tokens saved successfully")}catch(r){console.error("Crudify: Failed to save tokens",r)}}static getTokens(){let e=i.getStorage();if(!e)return null;try{let t=e.getItem(i.TOKEN_KEY);if(!t)return null;let r=i.decrypt(t),s=JSON.parse(r);return!s.accessToken||!s.refreshToken||!s.expiresAt||!s.refreshExpiresAt?(console.warn("Crudify: Incomplete token data found, clearing storage"),i.clearTokens(),null):Date.now()>=s.refreshExpiresAt?(console.info("Crudify: Refresh token expired, clearing storage"),i.clearTokens(),null):{accessToken:s.accessToken,refreshToken:s.refreshToken,expiresAt:s.expiresAt,refreshExpiresAt:s.refreshExpiresAt}}catch(t){return console.error("Crudify: Failed to retrieve tokens",t),i.clearTokens(),null}}static clearTokens(){let e=i.getStorage();if(e)try{e.removeItem(i.TOKEN_KEY),console.debug("Crudify: Tokens cleared from storage")}catch(t){console.error("Crudify: Failed to clear tokens",t)}}static rotateEncryptionKey(){try{i.clearTokens(),i.encryptionKey=null;let e=window.localStorage;e&&e.removeItem(i.ENCRYPTION_KEY_STORAGE),console.info("Crudify: Encryption key rotated successfully")}catch(e){console.error("Crudify: Failed to rotate encryption key",e)}}static hasValidTokens(){return i.getTokens()!==null}static getExpirationInfo(){let e=i.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 updateAccessToken(e,t){let r=i.getTokens();if(!r){console.warn("Crudify: Cannot update access token, no existing tokens found");return}i.saveTokens({...r,accessToken:e,expiresAt:t})}};i.TOKEN_KEY="crudify_tokens",i.ENCRYPTION_KEY_STORAGE="crudify_enc_key",i.encryptionKey=null,i.storageType="localStorage";var g=i;var _crudifybrowser = require('@nocios/crudify-browser'); var _crudifybrowser2 = _interopRequireDefault(_crudifybrowser);var L=class n{constructor(){this.config={};this.initialized=!1}static getInstance(){return n.instance||(n.instance=new n),n.instance}async initialize(e={}){if(this.initialized){console.warn("SessionManager: Already initialized");return}this.config={storageType:"localStorage",autoRestore:!0,enableLogging:!1,...e},g.setStorageType(this.config.storageType||"localStorage"),this.config.enableLogging,this.config.autoRestore&&await this.restoreSession(),this.initialized=!0,this.log("SessionManager initialized successfully")}async login(e,t){try{this.log("Attempting login...");let r=await _crudifybrowser2.default.login(e,t);if(!r.success)return this.log("Login failed:",r.errors),{success:!1,error:this.formatError(r.errors),rawResponse:r};let s={accessToken:r.data.token,refreshToken:r.data.refreshToken,expiresAt:r.data.expiresAt,refreshExpiresAt:r.data.refreshExpiresAt};return g.saveTokens(s),this.log("Login successful, tokens saved"),_optionalChain([this, 'access', _2 => _2.config, 'access', _3 => _3.onLoginSuccess, 'optionalCall', _4 => _4(s)]),{success:!0,tokens:s,data:r.data}}catch(r){return this.log("Login error:",r),{success:!1,error:r instanceof Error?r.message:"Unknown error"}}}async logout(){try{this.log("Logging out..."),await _crudifybrowser2.default.logout(),g.clearTokens(),this.log("Logout successful"),_optionalChain([this, 'access', _5 => _5.config, 'access', _6 => _6.onLogout, 'optionalCall', _7 => _7()])}catch(e){this.log("Logout error:",e),g.clearTokens()}}async restoreSession(){try{this.log("Attempting to restore session...");let e=g.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"),g.clearTokens(),!1;if(_crudifybrowser2.default.setTokens({accessToken:e.accessToken,refreshToken:e.refreshToken,expiresAt:e.expiresAt,refreshExpiresAt:e.refreshExpiresAt}),_crudifybrowser2.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 s=g.getTokens();return s&&_optionalChain([this, 'access', _8 => _8.config, 'access', _9 => _9.onSessionRestored, 'optionalCall', _10 => _10(s)]),!0}return g.clearTokens(),await _crudifybrowser2.default.logout(),!1}return this.log("Session restored successfully"),_optionalChain([this, 'access', _11 => _11.config, 'access', _12 => _12.onSessionRestored, 'optionalCall', _13 => _13(e)]),!0}catch(e){return this.log("Session restore error:",e),g.clearTokens(),await _crudifybrowser2.default.logout(),!1}}isAuthenticated(){return _crudifybrowser2.default.isLogin()||g.hasValidTokens()}getTokenInfo(){let e=_crudifybrowser2.default.getTokenData(),t=g.getExpirationInfo();return{isLoggedIn:this.isAuthenticated(),crudifyTokens:e,storageInfo:t,hasValidTokens:g.hasValidTokens()}}async refreshTokens(){try{this.log("Manually refreshing tokens...");let e=await _crudifybrowser2.default.refreshAccessToken();if(!e.success)return this.log("Token refresh failed:",e.errors),g.clearTokens(),_optionalChain([this, 'access', _14 => _14.config, 'access', _15 => _15.showNotification, 'optionalCall', _16 => _16(this.getSessionExpiredMessage(),"warning")]),_optionalChain([this, 'access', _17 => _17.config, 'access', _18 => _18.onSessionExpired, 'optionalCall', _19 => _19()]),!1;let t={accessToken:e.data.token,refreshToken:e.data.refreshToken,expiresAt:e.data.expiresAt,refreshExpiresAt:e.data.refreshExpiresAt};return g.saveTokens(t),this.log("Tokens refreshed and saved successfully"),!0}catch(e){return this.log("Token refresh error:",e),g.clearTokens(),_optionalChain([this, 'access', _20 => _20.config, 'access', _21 => _21.showNotification, 'optionalCall', _22 => _22(this.getSessionExpiredMessage(),"warning")]),_optionalChain([this, 'access', _23 => _23.config, 'access', _24 => _24.onSessionExpired, 'optionalCall', _25 => _25()]),!1}}setupResponseInterceptor(){_crudifybrowser2.default.setResponseInterceptor(async e=>{let t=this.detectAuthorizationError(e);if(t.isAuthError){if(console.warn("\u{1F6A8} SessionManager - Authorization error detected:",{errorType:t.errorType,errorDetails:t.errorDetails,fullResponse:e}),t.isRefreshTokenInvalid||t.isTokenRefreshFailed)return this.log("Refresh token invalid or refresh already failed, clearing session"),g.clearTokens(),_optionalChain([this, 'access', _26 => _26.config, 'access', _27 => _27.showNotification, 'optionalCall', _28 => _28(this.getSessionExpiredMessage(),"warning")]),_optionalChain([this, 'access', _29 => _29.config, 'access', _30 => _30.onSessionExpired, 'optionalCall', _31 => _31()]),e;g.hasValidTokens()&&!t.isIrrecoverable?(this.log("Auth error detected, attempting token refresh..."),await this.refreshTokens()||(this.log("Token refresh failed, triggering session expired"),_optionalChain([this, 'access', _32 => _32.config, 'access', _33 => _33.onSessionExpired, 'optionalCall', _34 => _34()]))):(this.log("Auth error with no valid tokens or irrecoverable error, triggering session expired"),g.clearTokens(),_optionalChain([this, 'access', _35 => _35.config, 'access', _36 => _36.showNotification, 'optionalCall', _37 => _37(this.getSessionExpiredMessage(),"warning")]),_optionalChain([this, 'access', _38 => _38.config, 'access', _39 => _39.onSessionExpired, 'optionalCall', _40 => _40()]))}return e}),this.log("Response interceptor configured")}detectAuthorizationError(e){let t={isAuthError:!1,isRefreshTokenInvalid:!1,isTokenRefreshFailed:!1,isIrrecoverable:!1,errorType:"",errorDetails:null};if(e.errors){if(Array.isArray(e.errors))e.errors.some(s=>s.errorType==="Unauthorized"||_optionalChain([s, 'access', _41 => _41.message, 'optionalAccess', _42 => _42.includes, 'call', _43 => _43("Unauthorized")])||_optionalChain([s, 'access', _44 => _44.message, 'optionalAccess', _45 => _45.includes, 'call', _46 => _46("Not Authorized")])||_optionalChain([s, 'access', _47 => _47.message, 'optionalAccess', _48 => _48.includes, 'call', _49 => _49("Token")])||_optionalChain([s, 'access', _50 => _50.extensions, 'optionalAccess', _51 => _51.code])==="UNAUTHENTICATED"||_optionalChain([s, 'access', _52 => _52.message, 'optionalAccess', _53 => _53.includes, 'call', _54 => _54("NOT_AUTHORIZED")]))&&(t.isAuthError=!0,t.errorType="GraphQL Array Format",t.errorDetails=e.errors);else if(typeof e.errors=="object"){let r=Object.values(e.errors).flat();r.some(l=>typeof l=="string"&&(l.includes("NOT_AUTHORIZED")||l.includes("TOKEN_REFRESH_FAILED")||l.includes("PLEASE_LOGIN")||l.includes("Unauthorized")||l.includes("UNAUTHENTICATED")||l.includes("Token")))&&(t.isAuthError=!0,t.errorType="GraphQL Object Format",t.errorDetails=e.errors,t.isTokenRefreshFailed=r.some(l=>typeof l=="string"&&l.includes("TOKEN_REFRESH_FAILED")))}}if(!t.isAuthError&&_optionalChain([e, 'access', _55 => _55.data, 'optionalAccess', _56 => _56.response, 'optionalAccess', _57 => _57.status])==="UNAUTHORIZED"&&(t.isAuthError=!0,t.errorType="Status UNAUTHORIZED",t.errorDetails=e.data.response,t.isIrrecoverable=!0),!t.isAuthError&&_optionalChain([e, 'access', _58 => _58.data, 'optionalAccess', _59 => _59.response, 'optionalAccess', _60 => _60.data]))try{let r=JSON.parse(e.data.response.data);(r.error==="REFRESH_TOKEN_INVALID"||r.error==="TOKEN_EXPIRED")&&(t.isAuthError=!0,t.errorType="Parsed Data Format",t.errorDetails=r,t.isRefreshTokenInvalid=!0,t.isIrrecoverable=!0)}catch (e4){}if(!t.isAuthError&&e.errorCode){let r=e.errorCode;(r==="UNAUTHORIZED"||r==="UNAUTHENTICATED"||r==="TOKEN_EXPIRED")&&(t.isAuthError=!0,t.errorType="Error Code Format",t.errorDetails={errorCode:r})}return t}clearSession(){g.clearTokens(),_crudifybrowser2.default.logout(),this.log("Session cleared completely")}getSessionExpiredMessage(){return this.config.translateFn?_chunk6EBMA4HZjs.b.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&&console.log(`[SessionManager] ${e}`,...t)}formatError(e){return e?typeof e=="string"?e:typeof e=="object"?Object.values(e).flat().join(", "):"Authentication failed":"Unknown error"}};var _react = require('react'); var _react2 = _interopRequireDefault(_react);function V(n={}){let[e,t]=_react.useState.call(void 0, {isAuthenticated:!1,isLoading:!0,isInitialized:!1,tokens:null,error:null}),r=L.getInstance(),s=_react.useCallback.call(void 0, async()=>{try{t(a=>({...a,isLoading:!0,error:null}));let c={autoRestore:_nullishCoalesce(n.autoRestore, () => (!0)),enableLogging:_nullishCoalesce(n.enableLogging, () => (!1)),showNotification:n.showNotification,translateFn:n.translateFn,onSessionExpired:()=>{t(a=>({...a,isAuthenticated:!1,tokens:null,error:"Session expired"})),_optionalChain([n, 'access', _61 => _61.onSessionExpired, 'optionalCall', _62 => _62()])},onSessionRestored:a=>{t(d=>({...d,isAuthenticated:!0,tokens:a,error:null})),_optionalChain([n, 'access', _63 => _63.onSessionRestored, 'optionalCall', _64 => _64(a)])},onLoginSuccess:a=>{t(d=>({...d,isAuthenticated:!0,tokens:a,error:null}))},onLogout:()=>{t(a=>({...a,isAuthenticated:!1,tokens:null,error:null}))}};await r.initialize(c),r.setupResponseInterceptor();let f=r.isAuthenticated(),o=r.getTokenInfo();t(a=>({...a,isAuthenticated:f,isInitialized:!0,isLoading:!1,tokens:o.crudifyTokens.accessToken?{accessToken:o.crudifyTokens.accessToken,refreshToken:o.crudifyTokens.refreshToken,expiresAt:o.crudifyTokens.expiresAt,refreshExpiresAt:o.crudifyTokens.refreshExpiresAt}:null}))}catch(c){let f=c instanceof Error?c.message:"Initialization failed";t(o=>({...o,isLoading:!1,isInitialized:!0,error:f}))}},[n.autoRestore,n.enableLogging,n.onSessionExpired,n.onSessionRestored]),l=_react.useCallback.call(void 0, async(c,f)=>{t(o=>({...o,isLoading:!0,error:null}));try{let o=await r.login(c,f);return o.success&&o.tokens?t(a=>({...a,isAuthenticated:!0,tokens:o.tokens,isLoading:!1,error:null})):t(a=>({...a,isAuthenticated:!1,tokens:null,isLoading:!1,error:null})),o}catch(o){let a=o instanceof Error?o.message:"Login failed",d=a.includes("INVALID_CREDENTIALS")||a.includes("Invalid email")||a.includes("Invalid password")||a.includes("credentials");return t(k=>({...k,isAuthenticated:!1,tokens:null,isLoading:!1,error:d?null:a})),{success:!1,error:a}}},[r]),v=_react.useCallback.call(void 0, async()=>{t(c=>({...c,isLoading:!0}));try{await r.logout(),t(c=>({...c,isAuthenticated:!1,tokens:null,isLoading:!1,error:null}))}catch(c){t(f=>({...f,isAuthenticated:!1,tokens:null,isLoading:!1,error:c instanceof Error?c.message:"Logout error"}))}},[r]),p=_react.useCallback.call(void 0, async()=>{try{let c=await r.refreshTokens();if(c){let f=r.getTokenInfo();t(o=>({...o,tokens:f.crudifyTokens.accessToken?{accessToken:f.crudifyTokens.accessToken,refreshToken:f.crudifyTokens.refreshToken,expiresAt:f.crudifyTokens.expiresAt,refreshExpiresAt:f.crudifyTokens.refreshExpiresAt}:null,error:null}))}else t(f=>({...f,isAuthenticated:!1,tokens:null,error:"Token refresh failed"}));return c}catch(c){return t(f=>({...f,isAuthenticated:!1,tokens:null,error:c instanceof Error?c.message:"Token refresh failed"})),!1}},[r]),x=_react.useCallback.call(void 0, ()=>{t(c=>({...c,error:null}))},[]),y=_react.useCallback.call(void 0, ()=>r.getTokenInfo(),[r]);return _react.useEffect.call(void 0, ()=>{s()},[s]),{...e,login:l,logout:v,refreshTokens:p,clearError:x,getTokenInfo:y,isExpiringSoon:e.tokens?e.tokens.expiresAt-Date.now()<300*1e3:!1,expiresIn:e.tokens?Math.max(0,e.tokens.expiresAt-Date.now()):0,refreshExpiresIn:e.tokens?Math.max(0,e.tokens.refreshExpiresAt-Date.now()):0}}var _material = require('@mui/material');var _uuid = require('uuid');var _dompurify = require('dompurify'); var _dompurify2 = _interopRequireDefault(_dompurify);var _jsxruntime = require('react/jsx-runtime');var W=_react.createContext.call(void 0, null),ue=n=>_dompurify2.default.sanitize(n,{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}),B= exports.d =({children:n,maxNotifications:e=5,defaultAutoHideDuration:t=6e3,position:r={vertical:"top",horizontal:"right"},enabled:s=!1,allowHtml:l=!1})=>{let[v,p]=_react.useState.call(void 0, []),x=_react.useCallback.call(void 0, (o,a="info",d)=>{if(!s)return"";if(!o||typeof o!="string")return console.warn("\u26A0\uFE0F GlobalNotificationProvider: Invalid message provided"),"";o.length>1e3&&(console.warn("\u26A0\uFE0F GlobalNotificationProvider: Message too long, truncating"),o=o.substring(0,1e3)+"...");let k=_uuid.v4.call(void 0, ),b={id:k,message:o,severity:a,autoHideDuration:_nullishCoalesce(_optionalChain([d, 'optionalAccess', _65 => _65.autoHideDuration]), () => (t)),persistent:_nullishCoalesce(_optionalChain([d, 'optionalAccess', _66 => _66.persistent]), () => (!1)),allowHtml:_nullishCoalesce(_optionalChain([d, 'optionalAccess', _67 => _67.allowHtml]), () => (l))};return p(T=>[...T.length>=e?T.slice(-(e-1)):T,b]),k},[e,t,s,l]),y=_react.useCallback.call(void 0, o=>{p(a=>a.filter(d=>d.id!==o))},[]),c=_react.useCallback.call(void 0, ()=>{p([])},[]),f={showNotification:x,hideNotification:y,clearAllNotifications:c};return _jsxruntime.jsxs.call(void 0, W.Provider,{value:f,children:[n,s&&_jsxruntime.jsx.call(void 0, _material.Portal,{children:_jsxruntime.jsx.call(void 0, _material.Box,{sx:{position:"fixed",zIndex:9999,[r.vertical]:(r.vertical==="top",24),[r.horizontal]:r.horizontal==="right"||r.horizontal==="left"?24:"50%",...r.horizontal==="center"&&{transform:"translateX(-50%)"},display:"flex",flexDirection:r.vertical==="top"?"column":"column-reverse",gap:1,maxWidth:"400px",width:"auto"},children:v.map(o=>_jsxruntime.jsx.call(void 0, fe,{notification:o,onClose:()=>y(o.id)},o.id))})})]})},fe=({notification:n,onClose:e})=>{let[t,r]=_react.useState.call(void 0, !0),s=_react.useCallback.call(void 0, (l,v)=>{v!=="clickaway"&&(r(!1),setTimeout(e,300))},[e]);return _react.useEffect.call(void 0, ()=>{if(!n.persistent&&n.autoHideDuration){let l=setTimeout(()=>{s()},n.autoHideDuration);return()=>clearTimeout(l)}},[n.autoHideDuration,n.persistent,s]),_jsxruntime.jsx.call(void 0, _material.Snackbar,{open:t,onClose:s,sx:{position:"relative","& .MuiSnackbarContent-root":{minWidth:"auto"}},TransitionProps:{enter:!0,exit:!0},children:_jsxruntime.jsx.call(void 0, _material.Alert,{variant:"filled",severity:n.severity,onClose:s,sx:{width:"100%",minWidth:"280px",maxWidth:"400px",wordBreak:"break-word"},children:n.allowHtml?_jsxruntime.jsx.call(void 0, "span",{dangerouslySetInnerHTML:{__html:ue(n.message)}}):_jsxruntime.jsx.call(void 0, "span",{children:n.message})})})},J= exports.e =()=>{let n=_react.useContext.call(void 0, W);if(!n)throw new Error("useGlobalNotification debe ser usado dentro de un GlobalNotificationProvider");return n};var X=_react.createContext.call(void 0, void 0);function ye({children:n,options:e={},config:t,showNotifications:r=!1,notificationOptions:s={}}){let l;try{let{showNotification:o}=J();l=o}catch (e5){}let v=_react2.default.useMemo(()=>({...e,showNotification:l,onSessionExpired:()=>{_optionalChain([e, 'access', _68 => _68.onSessionExpired, 'optionalCall', _69 => _69()])}}),[e,l]),p=V(v),x=_react.useMemo.call(void 0, ()=>{let o,a,d,k,b,T="unknown";if(_optionalChain([t, 'optionalAccess', _70 => _70.publicApiKey])&&(o=t.publicApiKey,T="props"),_optionalChain([t, 'optionalAccess', _71 => _71.env])&&(a=t.env),_optionalChain([t, 'optionalAccess', _72 => _72.appName])&&(d=t.appName),_optionalChain([t, 'optionalAccess', _73 => _73.loginActions])&&(k=t.loginActions),_optionalChain([t, 'optionalAccess', _74 => _74.logo])&&(b=t.logo),!o){let R=_chunk6EBMA4HZjs.a.call(void 0, "publicApiKey"),S=_chunk6EBMA4HZjs.a.call(void 0, "environment"),I=_chunk6EBMA4HZjs.a.call(void 0, "appName"),A=_chunk6EBMA4HZjs.a.call(void 0, "loginActions"),u=_chunk6EBMA4HZjs.a.call(void 0, "logo");R&&(o=R,T="cookies"),S&&["dev","stg","prod"].includes(S)&&(a=S),I&&(d=decodeURIComponent(I)),A&&(k=decodeURIComponent(A).split(",").map(C=>C.trim()).filter(Boolean)),u&&(b=decodeURIComponent(u))}return{publicApiKey:o,env:a,appName:d,loginActions:k,logo:b}},[t]),y=_react.useMemo.call(void 0, ()=>{if(!_optionalChain([p, 'access', _75 => _75.tokens, 'optionalAccess', _76 => _76.accessToken])||!p.isAuthenticated)return null;try{let o=_chunk6EBMA4HZjs.f.call(void 0, p.tokens.accessToken);if(o&&o.sub&&o.email&&o.subscriber){let a={_id:o.sub,email:o.email,subscriberKey:o.subscriber};return Object.keys(o).forEach(d=>{["sub","email","subscriber"].includes(d)||(a[d]=o[d])}),a}}catch(o){console.error("Error decoding JWT token for sessionData:",o)}return null},[_optionalChain([p, 'access', _77 => _77.tokens, 'optionalAccess', _78 => _78.accessToken]),p.isAuthenticated]),c={...p,sessionData:y,config:x},f={enabled:r,maxNotifications:s.maxNotifications||5,defaultAutoHideDuration:s.defaultAutoHideDuration||6e3,position:s.position||{vertical:"top",horizontal:"right"}};return _jsxruntime.jsx.call(void 0, X.Provider,{value:c,children:n})}function Be(n){let e={enabled:n.showNotifications,maxNotifications:_optionalChain([n, 'access', _79 => _79.notificationOptions, 'optionalAccess', _80 => _80.maxNotifications])||5,defaultAutoHideDuration:_optionalChain([n, 'access', _81 => _81.notificationOptions, 'optionalAccess', _82 => _82.defaultAutoHideDuration])||6e3,position:_optionalChain([n, 'access', _83 => _83.notificationOptions, 'optionalAccess', _84 => _84.position])||{vertical:"top",horizontal:"right"},allowHtml:_optionalChain([n, 'access', _85 => _85.notificationOptions, 'optionalAccess', _86 => _86.allowHtml])||!1};return _jsxruntime.jsx.call(void 0, B,{...e,children:_jsxruntime.jsx.call(void 0, ye,{...n})})}function $(){let n=_react.useContext.call(void 0, X);if(n===void 0)throw new Error("useSessionContext must be used within a SessionProvider");return n}function Je({children:n,fallback:e=_jsxruntime.jsx.call(void 0, "div",{children:"Please log in to access this content"}),redirectTo:t}){let{isAuthenticated:r,isLoading:s,isInitialized:l}=$();return!l||s?_jsxruntime.jsx.call(void 0, "div",{children:"Loading..."}):r?_jsxruntime.jsx.call(void 0, _jsxruntime.Fragment,{children:n}):t?(t(),null):_jsxruntime.jsx.call(void 0, _jsxruntime.Fragment,{children:e})}function Ze(){let n=$();return n.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:"})," ",n.isAuthenticated?"Yes":"No"]}),_jsxruntime.jsxs.call(void 0, "div",{children:[_jsxruntime.jsx.call(void 0, "strong",{children:"Loading:"})," ",n.isLoading?"Yes":"No"]}),_jsxruntime.jsxs.call(void 0, "div",{children:[_jsxruntime.jsx.call(void 0, "strong",{children:"Error:"})," ",n.error||"None"]}),n.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:"})," ",n.tokens.accessToken.substring(0,20),"..."]}),_jsxruntime.jsxs.call(void 0, "div",{children:[_jsxruntime.jsx.call(void 0, "strong",{children:"Refresh Token:"})," ",n.tokens.refreshToken.substring(0,20),"..."]}),_jsxruntime.jsxs.call(void 0, "div",{children:[_jsxruntime.jsx.call(void 0, "strong",{children:"Access Expires In:"})," ",Math.round(n.expiresIn/1e3/60)," minutes"]}),_jsxruntime.jsxs.call(void 0, "div",{children:[_jsxruntime.jsx.call(void 0, "strong",{children:"Refresh Expires In:"})," ",Math.round(n.refreshExpiresIn/1e3/60/60)," hours"]}),_jsxruntime.jsxs.call(void 0, "div",{children:[_jsxruntime.jsx.call(void 0, "strong",{children:"Expiring Soon:"})," ",n.isExpiringSoon?"Yes":"No"]})]})]}):_jsxruntime.jsx.call(void 0, "div",{children:"Session not initialized"})}var et=(n={})=>{let{autoFetch:e=!0,retryOnError:t=!1,maxRetries:r=3}=n,[s,l]=_react.useState.call(void 0, null),[v,p]=_react.useState.call(void 0, !1),[x,y]=_react.useState.call(void 0, null),[c,f]=_react.useState.call(void 0, {}),o=_react.useRef.call(void 0, null),a=_react.useRef.call(void 0, !0),d=_react.useRef.call(void 0, 0),k=_react.useRef.call(void 0, 0),b=_react.useCallback.call(void 0, ()=>{l(null),y(null),p(!1),f({})},[]),T=_react.useCallback.call(void 0, async()=>{let R=_chunk6EBMA4HZjs.g.call(void 0, );if(!R){a.current&&(y("No user email available"),p(!1));return}o.current&&o.current.abort();let S=new AbortController;o.current=S;let I=++d.current;try{a.current&&(p(!0),y(null));let A=await _crudifybrowser2.default.readItems("users",{filter:{email:R},pagination:{limit:1}});if(I===d.current&&a.current&&!S.signal.aborted)if(A.success&&A.data&&A.data.length>0){let u=A.data[0];l(u);let z={fullProfile:u,totalFields:Object.keys(u).length,displayData:{id:u.id,email:u.email,username:u.username,firstName:u.firstName,lastName:u.lastName,fullName:u.fullName||`${u.firstName||""} ${u.lastName||""}`.trim(),role:u.role,permissions:u.permissions||[],isActive:u.isActive,lastLogin:u.lastLogin,createdAt:u.createdAt,updatedAt:u.updatedAt,...Object.keys(u).filter(C=>!["id","email","username","firstName","lastName","fullName","role","permissions","isActive","lastLogin","createdAt","updatedAt"].includes(C)).reduce((C,F)=>({...C,[F]:u[F]}),{})}};f(z),y(null),k.current=0}else y("User profile not found"),l(null),f({})}catch(A){if(I===d.current&&a.current){let u=A;if(u.name==="AbortError")return;t&&k.current<r&&(_optionalChain([u, 'access', _87 => _87.message, 'optionalAccess', _88 => _88.includes, 'call', _89 => _89("Network Error")])||_optionalChain([u, 'access', _90 => _90.message, 'optionalAccess', _91 => _91.includes, 'call', _92 => _92("Failed to fetch")]))?(k.current++,setTimeout(()=>{a.current&&T()},1e3*k.current)):(y("Failed to load user profile"),l(null),f({}))}}finally{I===d.current&&a.current&&p(!1),o.current===S&&(o.current=null)}},[t,r]);return _react.useEffect.call(void 0, ()=>{e&&T()},[e,T]),_react.useEffect.call(void 0, ()=>(a.current=!0,()=>{a.current=!1,o.current&&(o.current.abort(),o.current=null)}),[]),{userProfile:s,loading:v,error:x,extendedData:c,refreshProfile:T,clearProfile:b}};exports.a = g; exports.b = L; exports.c = V; exports.d = B; exports.e = J; exports.f = Be; exports.g = $; exports.h = Je; exports.i = Ze; exports.j = et;
|
package/dist/chunk-TKYA4Q4U.mjs
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{a as w,b as M,f as G,g as Y}from"./chunk-YS3C7YG5.mjs";import P from"crypto-js";var i=class i{static setStorageType(e){i.storageType=e}static generateEncryptionKey(){let e=[navigator.userAgent,navigator.language,navigator.platform,screen.width,screen.height,Date.now().toString(),Math.random().toString(36)].join("|");return P.SHA256(e).toString()}static getEncryptionKey(){if(i.encryptionKey)return i.encryptionKey;let e=window.localStorage;if(!e)return i.encryptionKey=i.generateEncryptionKey(),i.encryptionKey;try{let t=e.getItem(i.ENCRYPTION_KEY_STORAGE);return(!t||t.length<32)&&(t=i.generateEncryptionKey(),e.setItem(i.ENCRYPTION_KEY_STORAGE,t)),i.encryptionKey=t,t}catch{return console.warn("Crudify: Cannot persist encryption key, using temporary key"),i.encryptionKey=i.generateEncryptionKey(),i.encryptionKey}}static isStorageAvailable(e){try{let t=window[e],r="__storage_test__";return t.setItem(r,"test"),t.removeItem(r),!0}catch{return!1}}static getStorage(){return i.storageType==="none"?null:i.isStorageAvailable(i.storageType)?window[i.storageType]:(console.warn(`Crudify: ${i.storageType} not available, tokens won't persist`),null)}static encrypt(e){try{let t=i.getEncryptionKey();return P.AES.encrypt(e,t).toString()}catch(t){return console.error("Crudify: Encryption failed",t),e}}static decrypt(e){try{let t=i.getEncryptionKey();return P.AES.decrypt(e,t).toString(P.enc.Utf8)||e}catch(t){return console.error("Crudify: Decryption failed",t),e}}static saveTokens(e){let t=i.getStorage();if(t)try{let r={accessToken:e.accessToken,refreshToken:e.refreshToken,expiresAt:e.expiresAt,refreshExpiresAt:e.refreshExpiresAt,savedAt:Date.now()},s=i.encrypt(JSON.stringify(r));t.setItem(i.TOKEN_KEY,s),console.debug("Crudify: Tokens saved successfully")}catch(r){console.error("Crudify: Failed to save tokens",r)}}static getTokens(){let e=i.getStorage();if(!e)return null;try{let t=e.getItem(i.TOKEN_KEY);if(!t)return null;let r=i.decrypt(t),s=JSON.parse(r);return!s.accessToken||!s.refreshToken||!s.expiresAt||!s.refreshExpiresAt?(console.warn("Crudify: Incomplete token data found, clearing storage"),i.clearTokens(),null):Date.now()>=s.refreshExpiresAt?(console.info("Crudify: Refresh token expired, clearing storage"),i.clearTokens(),null):{accessToken:s.accessToken,refreshToken:s.refreshToken,expiresAt:s.expiresAt,refreshExpiresAt:s.refreshExpiresAt}}catch(t){return console.error("Crudify: Failed to retrieve tokens",t),i.clearTokens(),null}}static clearTokens(){let e=i.getStorage();if(e)try{e.removeItem(i.TOKEN_KEY),console.debug("Crudify: Tokens cleared from storage")}catch(t){console.error("Crudify: Failed to clear tokens",t)}}static rotateEncryptionKey(){try{i.clearTokens(),i.encryptionKey=null;let e=window.localStorage;e&&e.removeItem(i.ENCRYPTION_KEY_STORAGE),console.info("Crudify: Encryption key rotated successfully")}catch(e){console.error("Crudify: Failed to rotate encryption key",e)}}static hasValidTokens(){return i.getTokens()!==null}static getExpirationInfo(){let e=i.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 updateAccessToken(e,t){let r=i.getTokens();if(!r){console.warn("Crudify: Cannot update access token, no existing tokens found");return}i.saveTokens({...r,accessToken:e,expiresAt:t})}};i.TOKEN_KEY="crudify_tokens",i.ENCRYPTION_KEY_STORAGE="crudify_enc_key",i.encryptionKey=null,i.storageType="localStorage";var g=i;import m from"@nocios/crudify-browser";var L=class n{constructor(){this.config={};this.initialized=!1}static getInstance(){return n.instance||(n.instance=new n),n.instance}async initialize(e={}){if(this.initialized){console.warn("SessionManager: Already initialized");return}this.config={storageType:"localStorage",autoRestore:!0,enableLogging:!1,...e},g.setStorageType(this.config.storageType||"localStorage"),this.config.enableLogging,this.config.autoRestore&&await this.restoreSession(),this.initialized=!0,this.log("SessionManager initialized successfully")}async login(e,t){try{this.log("Attempting login...");let r=await m.login(e,t);if(!r.success)return this.log("Login failed:",r.errors),{success:!1,error:this.formatError(r.errors),rawResponse:r};let s={accessToken:r.data.token,refreshToken:r.data.refreshToken,expiresAt:r.data.expiresAt,refreshExpiresAt:r.data.refreshExpiresAt};return g.saveTokens(s),this.log("Login successful, tokens saved"),this.config.onLoginSuccess?.(s),{success:!0,tokens:s,data:r.data}}catch(r){return this.log("Login error:",r),{success:!1,error:r instanceof Error?r.message:"Unknown error"}}}async logout(){try{this.log("Logging out..."),await m.logout(),g.clearTokens(),this.log("Logout successful"),this.config.onLogout?.()}catch(e){this.log("Logout error:",e),g.clearTokens()}}async restoreSession(){try{this.log("Attempting to restore session...");let e=g.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"),g.clearTokens(),!1;if(m.setTokens({accessToken:e.accessToken,refreshToken:e.refreshToken,expiresAt:e.expiresAt,refreshExpiresAt:e.refreshExpiresAt}),m.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 s=g.getTokens();return s&&this.config.onSessionRestored?.(s),!0}return g.clearTokens(),await m.logout(),!1}return this.log("Session restored successfully"),this.config.onSessionRestored?.(e),!0}catch(e){return this.log("Session restore error:",e),g.clearTokens(),await m.logout(),!1}}isAuthenticated(){return m.isLogin()||g.hasValidTokens()}getTokenInfo(){let e=m.getTokenData(),t=g.getExpirationInfo();return{isLoggedIn:this.isAuthenticated(),crudifyTokens:e,storageInfo:t,hasValidTokens:g.hasValidTokens()}}async refreshTokens(){try{this.log("Manually refreshing tokens...");let e=await m.refreshAccessToken();if(!e.success)return this.log("Token refresh failed:",e.errors),g.clearTokens(),this.config.showNotification?.(this.getSessionExpiredMessage(),"warning"),this.config.onSessionExpired?.(),!1;let t={accessToken:e.data.token,refreshToken:e.data.refreshToken,expiresAt:e.data.expiresAt,refreshExpiresAt:e.data.refreshExpiresAt};return g.saveTokens(t),this.log("Tokens refreshed and saved successfully"),!0}catch(e){return this.log("Token refresh error:",e),g.clearTokens(),this.config.showNotification?.(this.getSessionExpiredMessage(),"warning"),this.config.onSessionExpired?.(),!1}}setupResponseInterceptor(){m.setResponseInterceptor(async e=>{let t=this.detectAuthorizationError(e);if(t.isAuthError){if(console.warn("\u{1F6A8} SessionManager - Authorization error detected:",{errorType:t.errorType,errorDetails:t.errorDetails,fullResponse:e}),t.isRefreshTokenInvalid||t.isTokenRefreshFailed)return this.log("Refresh token invalid or refresh already failed, clearing session"),g.clearTokens(),this.config.showNotification?.(this.getSessionExpiredMessage(),"warning"),this.config.onSessionExpired?.(),e;g.hasValidTokens()&&!t.isIrrecoverable?(this.log("Auth error detected, attempting token refresh..."),await this.refreshTokens()||(this.log("Token refresh failed, triggering session expired"),this.config.onSessionExpired?.())):(this.log("Auth error with no valid tokens or irrecoverable error, triggering session expired"),g.clearTokens(),this.config.showNotification?.(this.getSessionExpiredMessage(),"warning"),this.config.onSessionExpired?.())}return e}),this.log("Response interceptor configured")}detectAuthorizationError(e){let t={isAuthError:!1,isRefreshTokenInvalid:!1,isTokenRefreshFailed:!1,isIrrecoverable:!1,errorType:"",errorDetails:null};if(e.errors){if(Array.isArray(e.errors))e.errors.some(s=>s.errorType==="Unauthorized"||s.message?.includes("Unauthorized")||s.message?.includes("Not Authorized")||s.message?.includes("Token")||s.extensions?.code==="UNAUTHENTICATED"||s.message?.includes("NOT_AUTHORIZED"))&&(t.isAuthError=!0,t.errorType="GraphQL Array Format",t.errorDetails=e.errors);else if(typeof e.errors=="object"){let r=Object.values(e.errors).flat();r.some(l=>typeof l=="string"&&(l.includes("NOT_AUTHORIZED")||l.includes("TOKEN_REFRESH_FAILED")||l.includes("PLEASE_LOGIN")||l.includes("Unauthorized")||l.includes("UNAUTHENTICATED")||l.includes("Token")))&&(t.isAuthError=!0,t.errorType="GraphQL Object Format",t.errorDetails=e.errors,t.isTokenRefreshFailed=r.some(l=>typeof l=="string"&&l.includes("TOKEN_REFRESH_FAILED")))}}if(!t.isAuthError&&e.data?.response?.status==="UNAUTHORIZED"&&(t.isAuthError=!0,t.errorType="Status UNAUTHORIZED",t.errorDetails=e.data.response,t.isIrrecoverable=!0),!t.isAuthError&&e.data?.response?.data)try{let r=JSON.parse(e.data.response.data);(r.error==="REFRESH_TOKEN_INVALID"||r.error==="TOKEN_EXPIRED")&&(t.isAuthError=!0,t.errorType="Parsed Data Format",t.errorDetails=r,t.isRefreshTokenInvalid=!0,t.isIrrecoverable=!0)}catch{}if(!t.isAuthError&&e.errorCode){let r=e.errorCode;(r==="UNAUTHORIZED"||r==="UNAUTHENTICATED"||r==="TOKEN_EXPIRED")&&(t.isAuthError=!0,t.errorType="Error Code Format",t.errorDetails={errorCode:r})}return t}clearSession(){g.clearTokens(),m.logout(),this.log("Session cleared completely")}getSessionExpiredMessage(){return this.config.translateFn?M("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&&console.log(`[SessionManager] ${e}`,...t)}formatError(e){return e?typeof e=="string"?e:typeof e=="object"?Object.values(e).flat().join(", "):"Authentication failed":"Unknown error"}};import{useState as _,useEffect as ee,useCallback as D}from"react";function V(n={}){let[e,t]=_({isAuthenticated:!1,isLoading:!0,isInitialized:!1,tokens:null,error:null}),r=L.getInstance(),s=D(async()=>{try{t(a=>({...a,isLoading:!0,error:null}));let c={autoRestore:n.autoRestore??!0,enableLogging:n.enableLogging??!1,showNotification:n.showNotification,translateFn:n.translateFn,onSessionExpired:()=>{t(a=>({...a,isAuthenticated:!1,tokens:null,error:"Session expired"})),n.onSessionExpired?.()},onSessionRestored:a=>{t(d=>({...d,isAuthenticated:!0,tokens:a,error:null})),n.onSessionRestored?.(a)},onLoginSuccess:a=>{t(d=>({...d,isAuthenticated:!0,tokens:a,error:null}))},onLogout:()=>{t(a=>({...a,isAuthenticated:!1,tokens:null,error:null}))}};await r.initialize(c),r.setupResponseInterceptor();let f=r.isAuthenticated(),o=r.getTokenInfo();t(a=>({...a,isAuthenticated:f,isInitialized:!0,isLoading:!1,tokens:o.crudifyTokens.accessToken?{accessToken:o.crudifyTokens.accessToken,refreshToken:o.crudifyTokens.refreshToken,expiresAt:o.crudifyTokens.expiresAt,refreshExpiresAt:o.crudifyTokens.refreshExpiresAt}:null}))}catch(c){let f=c instanceof Error?c.message:"Initialization failed";t(o=>({...o,isLoading:!1,isInitialized:!0,error:f}))}},[n.autoRestore,n.enableLogging,n.onSessionExpired,n.onSessionRestored]),l=D(async(c,f)=>{t(o=>({...o,isLoading:!0,error:null}));try{let o=await r.login(c,f);return o.success&&o.tokens?t(a=>({...a,isAuthenticated:!0,tokens:o.tokens,isLoading:!1,error:null})):t(a=>({...a,isAuthenticated:!1,tokens:null,isLoading:!1,error:null})),o}catch(o){let a=o instanceof Error?o.message:"Login failed",d=a.includes("INVALID_CREDENTIALS")||a.includes("Invalid email")||a.includes("Invalid password")||a.includes("credentials");return t(k=>({...k,isAuthenticated:!1,tokens:null,isLoading:!1,error:d?null:a})),{success:!1,error:a}}},[r]),v=D(async()=>{t(c=>({...c,isLoading:!0}));try{await r.logout(),t(c=>({...c,isAuthenticated:!1,tokens:null,isLoading:!1,error:null}))}catch(c){t(f=>({...f,isAuthenticated:!1,tokens:null,isLoading:!1,error:c instanceof Error?c.message:"Logout error"}))}},[r]),p=D(async()=>{try{let c=await r.refreshTokens();if(c){let f=r.getTokenInfo();t(o=>({...o,tokens:f.crudifyTokens.accessToken?{accessToken:f.crudifyTokens.accessToken,refreshToken:f.crudifyTokens.refreshToken,expiresAt:f.crudifyTokens.expiresAt,refreshExpiresAt:f.crudifyTokens.refreshExpiresAt}:null,error:null}))}else t(f=>({...f,isAuthenticated:!1,tokens:null,error:"Token refresh failed"}));return c}catch(c){return t(f=>({...f,isAuthenticated:!1,tokens:null,error:c instanceof Error?c.message:"Token refresh failed"})),!1}},[r]),x=D(()=>{t(c=>({...c,error:null}))},[]),y=D(()=>r.getTokenInfo(),[r]);return ee(()=>{s()},[s]),{...e,login:l,logout:v,refreshTokens:p,clearError:x,getTokenInfo:y,isExpiringSoon:e.tokens?e.tokens.expiresAt-Date.now()<300*1e3:!1,expiresIn:e.tokens?Math.max(0,e.tokens.expiresAt-Date.now()):0,refreshExpiresIn:e.tokens?Math.max(0,e.tokens.refreshExpiresAt-Date.now()):0}}import{useState as j,createContext as te,useContext as re,useCallback as O,useEffect as oe}from"react";import{Snackbar as ne,Alert as se,Box as ie,Portal as ae}from"@mui/material";import{v4 as le}from"uuid";import ce from"dompurify";import{jsx as N,jsxs as de}from"react/jsx-runtime";var W=te(null),ue=n=>ce.sanitize(n,{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}),B=({children:n,maxNotifications:e=5,defaultAutoHideDuration:t=6e3,position:r={vertical:"top",horizontal:"right"},enabled:s=!1,allowHtml:l=!1})=>{let[v,p]=j([]),x=O((o,a="info",d)=>{if(!s)return"";if(!o||typeof o!="string")return console.warn("\u26A0\uFE0F GlobalNotificationProvider: Invalid message provided"),"";o.length>1e3&&(console.warn("\u26A0\uFE0F GlobalNotificationProvider: Message too long, truncating"),o=o.substring(0,1e3)+"...");let k=le(),b={id:k,message:o,severity:a,autoHideDuration:d?.autoHideDuration??t,persistent:d?.persistent??!1,allowHtml:d?.allowHtml??l};return p(T=>[...T.length>=e?T.slice(-(e-1)):T,b]),k},[e,t,s,l]),y=O(o=>{p(a=>a.filter(d=>d.id!==o))},[]),c=O(()=>{p([])},[]),f={showNotification:x,hideNotification:y,clearAllNotifications:c};return de(W.Provider,{value:f,children:[n,s&&N(ae,{children:N(ie,{sx:{position:"fixed",zIndex:9999,[r.vertical]:(r.vertical==="top",24),[r.horizontal]:r.horizontal==="right"||r.horizontal==="left"?24:"50%",...r.horizontal==="center"&&{transform:"translateX(-50%)"},display:"flex",flexDirection:r.vertical==="top"?"column":"column-reverse",gap:1,maxWidth:"400px",width:"auto"},children:v.map(o=>N(fe,{notification:o,onClose:()=>y(o.id)},o.id))})})]})},fe=({notification:n,onClose:e})=>{let[t,r]=j(!0),s=O((l,v)=>{v!=="clickaway"&&(r(!1),setTimeout(e,300))},[e]);return oe(()=>{if(!n.persistent&&n.autoHideDuration){let l=setTimeout(()=>{s()},n.autoHideDuration);return()=>clearTimeout(l)}},[n.autoHideDuration,n.persistent,s]),N(ne,{open:t,onClose:s,sx:{position:"relative","& .MuiSnackbarContent-root":{minWidth:"auto"}},TransitionProps:{enter:!0,exit:!0},children:N(se,{variant:"filled",severity:n.severity,onClose:s,sx:{width:"100%",minWidth:"280px",maxWidth:"400px",wordBreak:"break-word"},children:n.allowHtml?N("span",{dangerouslySetInnerHTML:{__html:ue(n.message)}}):N("span",{children:n.message})})})},J=()=>{let n=re(W);if(!n)throw new Error("useGlobalNotification debe ser usado dentro de un GlobalNotificationProvider");return n};import ge,{createContext as pe,useContext as he,useMemo as Z}from"react";import{Fragment as H,jsx as h,jsxs as E}from"react/jsx-runtime";var X=pe(void 0);function ye({children:n,options:e={},config:t,showNotifications:r=!1,notificationOptions:s={}}){let l;try{let{showNotification:o}=J();l=o}catch{}let v=ge.useMemo(()=>({...e,showNotification:l,onSessionExpired:()=>{e.onSessionExpired?.()}}),[e,l]),p=V(v),x=Z(()=>{let o,a,d,k,b,T="unknown";if(t?.publicApiKey&&(o=t.publicApiKey,T="props"),t?.env&&(a=t.env),t?.appName&&(d=t.appName),t?.loginActions&&(k=t.loginActions),t?.logo&&(b=t.logo),!o){let R=w("publicApiKey"),S=w("environment"),I=w("appName"),A=w("loginActions"),u=w("logo");R&&(o=R,T="cookies"),S&&["dev","stg","prod"].includes(S)&&(a=S),I&&(d=decodeURIComponent(I)),A&&(k=decodeURIComponent(A).split(",").map(C=>C.trim()).filter(Boolean)),u&&(b=decodeURIComponent(u))}return{publicApiKey:o,env:a,appName:d,loginActions:k,logo:b}},[t]),y=Z(()=>{if(!p.tokens?.accessToken||!p.isAuthenticated)return null;try{let o=G(p.tokens.accessToken);if(o&&o.sub&&o.email&&o.subscriber){let a={_id:o.sub,email:o.email,subscriberKey:o.subscriber};return Object.keys(o).forEach(d=>{["sub","email","subscriber"].includes(d)||(a[d]=o[d])}),a}}catch(o){console.error("Error decoding JWT token for sessionData:",o)}return null},[p.tokens?.accessToken,p.isAuthenticated]),c={...p,sessionData:y,config:x},f={enabled:r,maxNotifications:s.maxNotifications||5,defaultAutoHideDuration:s.defaultAutoHideDuration||6e3,position:s.position||{vertical:"top",horizontal:"right"}};return h(X.Provider,{value:c,children:n})}function Be(n){let e={enabled:n.showNotifications,maxNotifications:n.notificationOptions?.maxNotifications||5,defaultAutoHideDuration:n.notificationOptions?.defaultAutoHideDuration||6e3,position:n.notificationOptions?.position||{vertical:"top",horizontal:"right"},allowHtml:n.notificationOptions?.allowHtml||!1};return h(B,{...e,children:h(ye,{...n})})}function $(){let n=he(X);if(n===void 0)throw new Error("useSessionContext must be used within a SessionProvider");return n}function Je({children:n,fallback:e=h("div",{children:"Please log in to access this content"}),redirectTo:t}){let{isAuthenticated:r,isLoading:s,isInitialized:l}=$();return!l||s?h("div",{children:"Loading..."}):r?h(H,{children:n}):t?(t(),null):h(H,{children:e})}function Ze(){let n=$();return n.isInitialized?E("div",{style:{padding:"10px",margin:"10px",border:"1px solid #ccc",borderRadius:"4px",fontSize:"12px",fontFamily:"monospace"},children:[h("h4",{children:"Session Debug Info"}),E("div",{children:[h("strong",{children:"Authenticated:"})," ",n.isAuthenticated?"Yes":"No"]}),E("div",{children:[h("strong",{children:"Loading:"})," ",n.isLoading?"Yes":"No"]}),E("div",{children:[h("strong",{children:"Error:"})," ",n.error||"None"]}),n.tokens&&E(H,{children:[E("div",{children:[h("strong",{children:"Access Token:"})," ",n.tokens.accessToken.substring(0,20),"..."]}),E("div",{children:[h("strong",{children:"Refresh Token:"})," ",n.tokens.refreshToken.substring(0,20),"..."]}),E("div",{children:[h("strong",{children:"Access Expires In:"})," ",Math.round(n.expiresIn/1e3/60)," minutes"]}),E("div",{children:[h("strong",{children:"Refresh Expires In:"})," ",Math.round(n.refreshExpiresIn/1e3/60/60)," hours"]}),E("div",{children:[h("strong",{children:"Expiring Soon:"})," ",n.isExpiringSoon?"Yes":"No"]})]})]}):h("div",{children:"Session not initialized"})}import{useState as U,useEffect as q,useCallback as Q,useRef as K}from"react";import ke from"@nocios/crudify-browser";var et=(n={})=>{let{autoFetch:e=!0,retryOnError:t=!1,maxRetries:r=3}=n,[s,l]=U(null),[v,p]=U(!1),[x,y]=U(null),[c,f]=U({}),o=K(null),a=K(!0),d=K(0),k=K(0),b=Q(()=>{l(null),y(null),p(!1),f({})},[]),T=Q(async()=>{let R=Y();if(!R){a.current&&(y("No user email available"),p(!1));return}o.current&&o.current.abort();let S=new AbortController;o.current=S;let I=++d.current;try{a.current&&(p(!0),y(null));let A=await ke.readItems("users",{filter:{email:R},pagination:{limit:1}});if(I===d.current&&a.current&&!S.signal.aborted)if(A.success&&A.data&&A.data.length>0){let u=A.data[0];l(u);let z={fullProfile:u,totalFields:Object.keys(u).length,displayData:{id:u.id,email:u.email,username:u.username,firstName:u.firstName,lastName:u.lastName,fullName:u.fullName||`${u.firstName||""} ${u.lastName||""}`.trim(),role:u.role,permissions:u.permissions||[],isActive:u.isActive,lastLogin:u.lastLogin,createdAt:u.createdAt,updatedAt:u.updatedAt,...Object.keys(u).filter(C=>!["id","email","username","firstName","lastName","fullName","role","permissions","isActive","lastLogin","createdAt","updatedAt"].includes(C)).reduce((C,F)=>({...C,[F]:u[F]}),{})}};f(z),y(null),k.current=0}else y("User profile not found"),l(null),f({})}catch(A){if(I===d.current&&a.current){let u=A;if(u.name==="AbortError")return;t&&k.current<r&&(u.message?.includes("Network Error")||u.message?.includes("Failed to fetch"))?(k.current++,setTimeout(()=>{a.current&&T()},1e3*k.current)):(y("Failed to load user profile"),l(null),f({}))}}finally{I===d.current&&a.current&&p(!1),o.current===S&&(o.current=null)}},[t,r]);return q(()=>{e&&T()},[e,T]),q(()=>(a.current=!0,()=>{a.current=!1,o.current&&(o.current.abort(),o.current=null)}),[]),{userProfile:s,loading:v,error:x,extendedData:c,refreshProfile:T,clearProfile:b}};export{g as a,L as b,V as c,B as d,J as e,Be as f,$ as g,Je as h,Ze as i,et as j};
|