@nocios/crudify-ui 4.4.58 → 4.4.62
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{CrudiaMarkdownField-BB1lfJl2.d.ts → CrudiaMarkdownField-Bs940oF4.d.ts} +10 -16
- package/dist/{CrudiaMarkdownField-DolyQn1x.d.mts → CrudiaMarkdownField-CKPdr2JL.d.mts} +10 -16
- package/dist/{chunk-W46IJS4Y.mjs → chunk-A65BF4BB.mjs} +1 -1
- package/dist/{chunk-7ICLHPYK.js → chunk-YA2ON7ZR.js} +1 -1
- package/dist/components.d.mts +1 -1
- package/dist/components.d.ts +1 -1
- package/dist/components.js +1 -1
- package/dist/components.mjs +1 -1
- package/dist/index.d.mts +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +2 -2
- package/dist/index.mjs +1 -1
- package/package.json +2 -2
|
@@ -241,34 +241,28 @@ declare const CrudiaFileField: React.FC<CrudiaFileFieldProps>;
|
|
|
241
241
|
* - Saves content as markdown string
|
|
242
242
|
*/
|
|
243
243
|
|
|
244
|
-
/**
|
|
245
|
-
* Props del componente CrudiaMarkdownField
|
|
246
|
-
*/
|
|
247
244
|
interface CrudiaMarkdownFieldProps {
|
|
248
|
-
/**
|
|
245
|
+
/** Field label */
|
|
249
246
|
label?: string;
|
|
250
|
-
/**
|
|
247
|
+
/** Current value (markdown string) */
|
|
251
248
|
value?: string;
|
|
252
|
-
/** Callback
|
|
249
|
+
/** Callback when content changes */
|
|
253
250
|
onChange?: (value: string) => void;
|
|
254
|
-
/**
|
|
251
|
+
/** Required field */
|
|
255
252
|
required?: boolean;
|
|
256
|
-
/**
|
|
253
|
+
/** Disabled/readonly field */
|
|
257
254
|
disabled?: boolean;
|
|
258
|
-
/**
|
|
255
|
+
/** External error state */
|
|
259
256
|
error?: boolean;
|
|
260
|
-
/**
|
|
257
|
+
/** Helper or error text */
|
|
261
258
|
helperText?: string;
|
|
262
|
-
/**
|
|
259
|
+
/** Placeholder text */
|
|
263
260
|
placeholder?: string;
|
|
264
|
-
/**
|
|
261
|
+
/** Minimum editor height in pixels */
|
|
265
262
|
minHeight?: number;
|
|
266
|
-
/**
|
|
263
|
+
/** Maximum editor height in pixels (scrolls after) */
|
|
267
264
|
maxHeight?: number;
|
|
268
265
|
}
|
|
269
|
-
/**
|
|
270
|
-
* CrudiaMarkdownField - Editor de Markdown con soporte completo de MDXEditor
|
|
271
|
-
*/
|
|
272
266
|
declare const CrudiaMarkdownField: React.FC<CrudiaMarkdownFieldProps>;
|
|
273
267
|
|
|
274
268
|
export { type BoxScreenType as B, CrudifyLogin as C, LoginComponent as L, Policies as P, SessionStatus as S, UserProfileDisplay as U, CrudiaAutoGenerate as a, CrudiaFileField as b, CrudiaMarkdownField as c, type CrudifyLoginConfig as d, type CrudifyLoginProps as e, type CrudifyLoginTranslations as f, type UserLoginData as g, type PolicyAction as h, type CrudiaAutoGenerateProps as i, type CrudiaFileFieldProps as j, type CrudiaMarkdownFieldProps as k, POLICY_ACTIONS as l, PREFERRED_POLICY_ORDER as m };
|
|
@@ -241,34 +241,28 @@ declare const CrudiaFileField: React.FC<CrudiaFileFieldProps>;
|
|
|
241
241
|
* - Saves content as markdown string
|
|
242
242
|
*/
|
|
243
243
|
|
|
244
|
-
/**
|
|
245
|
-
* Props del componente CrudiaMarkdownField
|
|
246
|
-
*/
|
|
247
244
|
interface CrudiaMarkdownFieldProps {
|
|
248
|
-
/**
|
|
245
|
+
/** Field label */
|
|
249
246
|
label?: string;
|
|
250
|
-
/**
|
|
247
|
+
/** Current value (markdown string) */
|
|
251
248
|
value?: string;
|
|
252
|
-
/** Callback
|
|
249
|
+
/** Callback when content changes */
|
|
253
250
|
onChange?: (value: string) => void;
|
|
254
|
-
/**
|
|
251
|
+
/** Required field */
|
|
255
252
|
required?: boolean;
|
|
256
|
-
/**
|
|
253
|
+
/** Disabled/readonly field */
|
|
257
254
|
disabled?: boolean;
|
|
258
|
-
/**
|
|
255
|
+
/** External error state */
|
|
259
256
|
error?: boolean;
|
|
260
|
-
/**
|
|
257
|
+
/** Helper or error text */
|
|
261
258
|
helperText?: string;
|
|
262
|
-
/**
|
|
259
|
+
/** Placeholder text */
|
|
263
260
|
placeholder?: string;
|
|
264
|
-
/**
|
|
261
|
+
/** Minimum editor height in pixels */
|
|
265
262
|
minHeight?: number;
|
|
266
|
-
/**
|
|
263
|
+
/** Maximum editor height in pixels (scrolls after) */
|
|
267
264
|
maxHeight?: number;
|
|
268
265
|
}
|
|
269
|
-
/**
|
|
270
|
-
* CrudiaMarkdownField - Editor de Markdown con soporte completo de MDXEditor
|
|
271
|
-
*/
|
|
272
266
|
declare const CrudiaMarkdownField: React.FC<CrudiaMarkdownFieldProps>;
|
|
273
267
|
|
|
274
268
|
export { type BoxScreenType as B, CrudifyLogin as C, LoginComponent as L, Policies as P, SessionStatus as S, UserProfileDisplay as U, CrudiaAutoGenerate as a, CrudiaFileField as b, CrudiaMarkdownField as c, type CrudifyLoginConfig as d, type CrudifyLoginProps as e, type CrudifyLoginTranslations as f, type UserLoginData as g, type PolicyAction as h, type CrudiaAutoGenerateProps as i, type CrudiaFileFieldProps as j, type CrudiaMarkdownFieldProps as k, POLICY_ACTIONS as l, PREFERRED_POLICY_ORDER as m };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{b as Tr,c as ne,h as Rr,j as ge,l as Ir,m as Sr,p as kr}from"./chunk-5PKTOZAY.mjs";import{g as K}from"./chunk-BJ6PIVZR.mjs";import{a as Pr,b as vr,g as Er}from"./chunk-6GPSBDW6.mjs";var ce={es:{"checkCode.codeLabel":"C\xF3digo de Verificaci\xF3n","checkCode.codePlaceholder":"Ingresa el c\xF3digo de 6 d\xEDgitos","checkCode.codeRequired":"El c\xF3digo es obligatorio","checkCode.emailLabel":"Correo Electr\xF3nico","checkCode.emailPlaceholder":"Ingresa tu correo electr\xF3nico","checkCode.emailRequired":"El correo electr\xF3nico es obligatorio","checkCode.instructions":"Ingresa el c\xF3digo de 6 d\xEDgitos que enviamos a tu correo electr\xF3nico.","checkCode.invalidEmail":"Ingresa un correo electr\xF3nico v\xE1lido","checkCode.resendCodeLink":"Reenviar c\xF3digo","checkCode.title":"Verificar C\xF3digo","checkCode.verifyButton":"Verificar C\xF3digo","common.back":"Volver","common.backToLogin":"Volver","error.app.config":"Error de Configuraci\xF3n: {{message}}","error.app.initialization":"Error durante la inicializaci\xF3n final de la aplicaci\xF3n.","error.transaction":"Error en la operaci\xF3n","error.unknown":"Ocurri\xF3 un error desconocido.","errors.DUPLICATE":"El campo <b>{{field}}</b> debe ser \xFAnico.","errors.FOREIGN_KEY_NOT_FOUND":"El campo <b>{{field}}</b> debe referenciar un \xEDtem existente.","errors.INVALID_EMAIL":"El campo <b>{{field}}</b> debe ser un correo electr\xF3nico v\xE1lido.","errors.INVALID_OBJECT_ID":"El campo <b>{{field}}</b> debe ser un valor v\xE1lido.","errors.IN_USE":"El \xEDtem est\xE1 en uso y no puede ser eliminado.","errors.MAX_LENGTH":"El campo <b>{{field}}</b> no debe exceder los <b>{{length}}</b> caracteres.","errors.MIN_LENGTH":"El campo <b>{{field}}</b> debe tener al menos <b>{{length}}</b> caracteres.","errors.MUST_NOT_BE_EMAIL":"El campo <b>{{field}}</b> no debe ser un correo electr\xF3nico.","errors.NO_PERMISSION":"No tienes permiso para realizar esta acci\xF3n.","errors.NO_SPACES":"El campo <b>{{field}}</b> no debe contener espacios.","errors.ONE_OR_MORE_OPERATIONS_FAILED":"Error en la operaci\xF3n","errors.REQUIRED":"El campo <b>{{field}}</b> es obligatorio.","errors.TOKEN_HAS_EXPIRED":"La sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente.","errors.TOO_MANY_REQUESTS":"L\xEDmite de solicitudes alcanzado. Por favor intenta m\xE1s tarde.","errors.UNAUTHORIZED":"No est\xE1s autorizado para realizar esta acci\xF3n.","errors.all_password_fields_required":"Todos los campos de contrase\xF1a son obligatorios","errors.auth.INVALID_API_KEY":"Clave de API inv\xE1lida","errors.auth.INVALID_CREDENTIALS":"Usuario y/o contrase\xF1a incorrectos","errors.auth.NO_PERMISSION":"No tienes permisos suficientes","errors.auth.SESSION_EXPIRED":"Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente.","errors.auth.TOO_MANY_REQUESTS":"Demasiados intentos. Por favor espera 15 minutos e intenta nuevamente","errors.auth.UNAUTHORIZED":"No tienes permisos para realizar esta acci\xF3n","errors.auth.USER_NOT_ACTIVE":"Usuario no activo","errors.auth.USER_NOT_FOUND":"Usuario no encontrado","errors.data.BAD_REQUEST":"Solicitud inv\xE1lida","errors.data.FIELD_ERROR":"Error en los datos ingresados","errors.data.IN_USE":"El elemento est\xE1 en uso y no puede ser eliminado","errors.data.ITEM_NOT_FOUND":"El elemento solicitado no fue encontrado","errors.data.NOT_FOUND":"No se encontr\xF3 lo solicitado","errors.internal_error_changing_password":"Error interno al cambiar la contrase\xF1a. Intenta nuevamente","errors.password_min_length":"La contrase\xF1a debe tener al menos 8 caracteres","errors.password_mismatch":"Las contrase\xF1as no coinciden","errors.password_must_be_different":"La nueva contrase\xF1a debe ser diferente a la actual","errors.system.DATABASE_CONNECTION_ERROR":"Error de conexi\xF3n. Verifica tu conexi\xF3n a internet.","errors.system.INTERNAL_SERVER_ERROR":"Error interno del servidor. Intenta nuevamente.","errors.system.INVALID_CONFIGURATION":"Error de configuraci\xF3n del sistema","errors.system.TOO_MANY_REQUESTS":"Demasiadas solicitudes. Por favor espera un momento e intenta nuevamente","errors.system.UNKNOWN_OPERATION":"Operaci\xF3n no reconocida","errors.users_module_not_configured":"M\xF3dulo de usuarios no configurado","footer.copyright":"Nocios S.R.L. Todos los derechos reservados.","footer.version":"Versi\xF3n","forgotPassword.checkEmailInstructions":"Revisa tu bandeja de entrada para el c\xF3digo de verificaci\xF3n","forgotPassword.codeAlreadyExistsMessage":"Ya se envi\xF3 un c\xF3digo y a\xFAn es v\xE1lido","forgotPassword.emailLabel":"Correo Electr\xF3nico","forgotPassword.emailPlaceholder":"Ingresa tu correo electr\xF3nico","forgotPassword.emailRequired":"El correo electr\xF3nico es obligatorio","forgotPassword.emailSentMessage":"C\xF3digo enviado exitosamente","forgotPassword.enterCodeLink":"Ingresar C\xF3digo","forgotPassword.instructions":"Ingresa tu correo electr\xF3nico y te enviaremos un c\xF3digo para restablecer tu contrase\xF1a.","forgotPassword.invalidEmail":"Ingresa un correo electr\xF3nico v\xE1lido","forgotPassword.sendCodeButton":"Enviar C\xF3digo","forgotPassword.title":"Recuperar Contrase\xF1a","loading.app.configInitial":"Cargando configuraci\xF3n inicial...","loading.app.generic":"Cargando...","loading.app.starting":"Iniciando aplicaci\xF3n...","loading.app.themeSetup":"Generando tema...","loading.app.validatingSession":"Validando sesi\xF3n...","login.alreadyHaveCodeLink":"\xBFYa tienes un c\xF3digo?","login.forgotPasswordLink":"\xBFOlvidaste tu contrase\xF1a?","login.initializationError":"Error de inicializaci\xF3n","login.initializing":"Inicializando...","login.loginButton":"Iniciar Sesi\xF3n","login.logoAlt":"Logotipo","login.noAccountPrompt":"\xBFNo tienes una cuenta?","login.notInitialized":"Sistema no inicializado","login.passwordLabel":"Contrase\xF1a","login.passwordPlaceholder":"Ingresa tu contrase\xF1a","login.passwordRequired":"Contrase\xF1a es obligatoria","login.signUpLink":"Reg\xEDstrate","login.usernameOrEmailLabel":"Correo Electr\xF3nico","login.usernameOrEmailPlaceholder":"Ingresa tu correo electr\xF3nico","login.usernameRequired":"Correo electr\xF3nico es obligatorio","resetPassword.codeExpiredOrInvalid":"El c\xF3digo ha expirado o es inv\xE1lido","resetPassword.confirmPasswordLabel":"Confirmar Contrase\xF1a","resetPassword.confirmPasswordPlaceholder":"Confirma tu nueva contrase\xF1a","resetPassword.confirmPasswordRequired":"Confirma tu contrase\xF1a","resetPassword.goToLoginButton":"Ir al Login","resetPassword.instructions":"Ingresa tu nueva contrase\xF1a.","resetPassword.invalidCode":"El c\xF3digo de verificaci\xF3n es inv\xE1lido. Por favor, verifica el enlace o solicita uno nuevo.","resetPassword.missingParameters":"Faltan par\xE1metros obligatorios","resetPassword.newPasswordLabel":"Nueva Contrase\xF1a","resetPassword.newPasswordPlaceholder":"Ingresa tu nueva contrase\xF1a","resetPassword.newPasswordRequired":"La nueva contrase\xF1a es obligatoria","resetPassword.passwordTooShort":"La contrase\xF1a debe tener al menos 8 caracteres","resetPassword.passwordsDoNotMatch":"Las contrase\xF1as no coinciden","resetPassword.requestNewCodeButton":"Solicitar Nuevo C\xF3digo","resetPassword.resetPasswordButton":"Restablecer Contrase\xF1a","resetPassword.successInstructions":"Ahora puedes iniciar sesi\xF3n con tu nueva contrase\xF1a","resetPassword.successMessage":"Contrase\xF1a restablecida exitosamente","resetPassword.title":"Nueva Contrase\xF1a","resetPassword.validatingCode":"Validando c\xF3digo...","modules.form.publicPolicies.fields.conditions.customEdit":"Edici\xF3n personalizada"},en:{"checkCode.codeLabel":"Verification Code","checkCode.codePlaceholder":"Enter 6-digit code","checkCode.codeRequired":"Code is required","checkCode.emailLabel":"Email Address","checkCode.emailPlaceholder":"Enter your email address","checkCode.emailRequired":"Email address is required","checkCode.instructions":"Enter the 6-digit code we sent to your email address.","checkCode.invalidEmail":"Enter a valid email address","checkCode.resendCodeLink":"Resend code","checkCode.title":"Verify Code","checkCode.verifyButton":"Verify Code","common.back":"Back","common.backToLogin":"Back to Login","error.app.config":"Configuration Error: {{message}}","error.app.initialization":"Error during final application initialization.","error.transaction":"Operation error","error.unknown":"An unknown error occurred.","errors.DUPLICATE":"The field <b>{{field}}</b> must be unique.","errors.FOREIGN_KEY_NOT_FOUND":"The field <b>{{field}}</b> must reference an existing item.","errors.INVALID_EMAIL":"The field <b>{{field}}</b> must be a valid email address.","errors.INVALID_OBJECT_ID":"The field <b>{{field}}</b> must be a valid value.","errors.IN_USE":"The item is currently in use and cannot be deleted.","errors.MAX_LENGTH":"The field <b>{{field}}</b> must not exceed <b>{{maxLength}}</b> characters.","errors.MIN_LENGTH":"The field <b>{{field}}</b> must have at least <b>{{minLength}}</b> characters.","errors.MUST_NOT_BE_EMAIL":"The field <b>{{field}}</b> must not be an email address.","errors.NO_PERMISSION":"You do not have permission to perform this action.","errors.NO_SPACES":"The field <b>{{field}}</b> must not contain spaces.","errors.ONE_OR_MORE_OPERATIONS_FAILED":"Operation error","errors.REQUIRED":"The field <b>{{field}}</b> is required.","errors.TOKEN_HAS_EXPIRED":"Your session has expired, please log in again.","errors.TOO_MANY_REQUESTS":"Request limit reached. Please try again later.","errors.UNAUTHORIZED":"You are not authorized to perform this action.","errors.all_password_fields_required":"All password fields are required","errors.auth.INVALID_API_KEY":"Invalid API key","errors.auth.INVALID_CREDENTIALS":"Incorrect username and/or password","errors.auth.NO_PERMISSION":"Insufficient permissions","errors.auth.SESSION_EXPIRED":"Your session has expired. Please log in again.","errors.auth.TOO_MANY_REQUESTS":"Too many attempts. Please wait 15 minutes and try again","errors.auth.UNAUTHORIZED":"You don't have permission to perform this action","errors.auth.USER_NOT_ACTIVE":"User account is not active","errors.auth.USER_NOT_FOUND":"User not found","errors.data.BAD_REQUEST":"Invalid request","errors.data.FIELD_ERROR":"Error in the provided data","errors.data.IN_USE":"The item is in use and cannot be deleted","errors.data.ITEM_NOT_FOUND":"The requested item was not found","errors.data.NOT_FOUND":"The requested resource was not found","errors.internal_error_changing_password":"Internal error changing password. Please try again","errors.password_min_length":"Password must be at least 8 characters","errors.password_mismatch":"Passwords do not match","errors.password_must_be_different":"New password must be different from current password","errors.system.DATABASE_CONNECTION_ERROR":"Connection error. Please check your internet connection.","errors.system.INTERNAL_SERVER_ERROR":"Internal server error. Please try again.","errors.system.INVALID_CONFIGURATION":"System configuration error","errors.system.TOO_MANY_REQUESTS":"Too many requests. Please wait a moment and try again","errors.system.UNKNOWN_OPERATION":"Unrecognized operation","errors.users_module_not_configured":"Users module not configured","footer.copyright":"Nocios S.R.L. All Rights Reserved.","footer.version":"Version","forgotPassword.checkEmailInstructions":"Check your inbox for the verification code","forgotPassword.codeAlreadyExistsMessage":"A code was already sent and is still valid","forgotPassword.emailLabel":"Email Address","forgotPassword.emailPlaceholder":"Enter your email address","forgotPassword.emailRequired":"Email address is required","forgotPassword.emailSentMessage":"Code sent successfully","forgotPassword.enterCodeLink":"Enter Code","forgotPassword.instructions":"Enter your email address and we'll send you a code to reset your password.","forgotPassword.invalidEmail":"Enter a valid email address","forgotPassword.sendCodeButton":"Send Code","forgotPassword.title":"Reset Password","loading.app.configInitial":"Loading initial configuration...","loading.app.generic":"Loading...","loading.app.starting":"Starting application...","loading.app.themeSetup":"Generating theme...","loading.app.validatingSession":"Validating session...","login.alreadyHaveCodeLink":"Already have a code?","login.forgotPasswordLink":"Forgot Password?","login.initializationError":"Initialization error","login.initializing":"Initializing...","login.loginButton":"Log In","login.logoAlt":"Logo","login.noAccountPrompt":"Don't have an account?","login.notInitialized":"System not initialized","login.passwordLabel":"Password","login.passwordPlaceholder":"Enter your password","login.passwordRequired":"Password is required","login.signUpLink":"Sign up","login.usernameOrEmailLabel":"Username or Email","login.usernameOrEmailPlaceholder":"Enter your username or email","login.usernameRequired":"Username or email is required","resetPassword.codeExpiredOrInvalid":"Code expired or invalid","resetPassword.confirmPasswordLabel":"Confirm Password","resetPassword.confirmPasswordPlaceholder":"Confirm your new password","resetPassword.confirmPasswordRequired":"Confirm your password","resetPassword.goToLoginButton":"Go to Login","resetPassword.instructions":"Enter your new password.","resetPassword.invalidCode":"The verification code is invalid. Please check the link or request a new one.","resetPassword.missingParameters":"Missing required parameters","resetPassword.newPasswordLabel":"New Password","resetPassword.newPasswordPlaceholder":"Enter your new password","resetPassword.newPasswordRequired":"New password is required","resetPassword.passwordTooShort":"Password must be at least 8 characters","resetPassword.passwordsDoNotMatch":"Passwords do not match","resetPassword.requestNewCodeButton":"Request New Code","resetPassword.resetPasswordButton":"Reset Password","resetPassword.successInstructions":"You can now log in with your new password","resetPassword.successMessage":"Password reset successfully","resetPassword.title":"New Password","resetPassword.validatingCode":"Validating code...","modules.form.publicPolicies.fields.conditions.customEdit":"Custom Edit"}},fs=()=>Object.keys(ce),ys=e=>ce[e]||ce.es;import Ve from"@nocios/crudify-browser";var Lr="crudify_translations_",Ao=3600*1e3;function Ar(e){let r=0;for(let o=0;o<e.length;o++){let t=e.charCodeAt(o);r=(r<<5)-r+t,r=r&r}return Math.abs(r).toString(36)}var rr=class e{constructor(){this.enableDebug=!1;this.initializationPromise=null;this.isInitialized=!1}static getInstance(){return e.instance||(e.instance=new e),e.instance}setDebug(r){this.enableDebug=r}async ensureCrudifyInitialized(r,o){if(!this.isInitialized)return this.initializationPromise?(this.enableDebug&&console.log("[TranslationService] Waiting for crudify initialization..."),this.initializationPromise):(this.enableDebug&&console.log("[TranslationService] Initializing crudify SDK..."),this.initializationPromise=(async()=>{try{let t=Ve.getTokenData();if(t&&t.endpoint){this.enableDebug&&console.log("[TranslationService] Crudify already initialized"),this.isInitialized=!0;return}Ve.config(o);let i=await Ve.init(r,this.enableDebug?"debug":"none");if(i.success===!1)throw new Error(`Failed to initialize crudify: ${JSON.stringify(i.errors||"Unknown error")}`);this.isInitialized=!0,this.enableDebug&&console.log("[TranslationService] Crudify SDK initialized successfully")}catch(t){throw console.error("[TranslationService] Failed to initialize crudify:",t),this.initializationPromise=null,t}})(),this.initializationPromise)}async fetchTranslations(r){let{apiKey:o,featureKeys:t,crudifyEnv:i="stg",urlTranslations:n}=r;this.enableDebug&&console.log("[TranslationService] fetchTranslations called with:",{apiKeyHash:Ar(o),crudifyEnv:i,featureKeys:t,hasUrlTranslations:!!n});let s=this.getFromCache(o),l=s?this.isCacheExpired(s):!0;if(s&&!l)return this.enableDebug&&console.log("[TranslationService] Using cached translations"),this.mergeWithUrlTranslations(s.data.translations,n);try{await this.ensureCrudifyInitialized(o,i)}catch(c){return console.error("[TranslationService] \u274C Failed to initialize crudify:",c),s?(console.warn("[TranslationService] \u26A0\uFE0F Using expired cache (init failed)"),this.mergeWithUrlTranslations(s.data.translations,n)):(console.warn("[TranslationService] \u26A0\uFE0F Using critical bundle (init failed)"),this.getCriticalTranslationsOnly())}try{this.enableDebug&&console.log("[TranslationService] Fetching from API via crudify SDK");let c=await this.fetchFromAPI(t);this.hasDataChanged(s,c)||!s?this.saveToCache(o,c):this.refreshCacheTimestamp(o);let d=this.mergeWithUrlTranslations(c.translations,n);return this.enableDebug&&console.log("[TranslationService] Translations loaded:",{languages:Object.keys(d),keysCount:d[Object.keys(d)[0]]?Object.keys(d[Object.keys(d)[0]]).length:0}),d}catch(c){return console.error("[TranslationService] \u274C API fetch failed:",c),s?(console.warn("[TranslationService] \u26A0\uFE0F Using expired cache as fallback"),this.mergeWithUrlTranslations(s.data.translations,n)):(console.warn("[TranslationService] \u26A0\uFE0F Using critical bundle translations"),this.getCriticalTranslationsOnly())}}async fetchFromAPI(r){let o=await Ve.getTranslation(r);if(!o.success)throw new Error(`Crudify API error: ${o.errors?JSON.stringify(o.errors):"Unknown error"}`);if(!o.data)throw new Error("No translation data in response");return o.data}mergeWithUrlTranslations(r,o){if(!o||Object.keys(o).length===0)return r;let t={};return Object.keys(r).forEach(i=>{t[i]={...r[i],...o}}),t}hasDataChanged(r,o){if(!r||r.data.timestamp!==o.timestamp)return!0;let t=this.hashData(o.translations);return r.dataHash!==t}hashData(r){let o=JSON.stringify(r),t=0;for(let i=0;i<o.length;i++){let n=o.charCodeAt(i);t=(t<<5)-t+n,t=t&t}return t.toString(36)}saveToCache(r,o){try{let t=this.getCacheKey(r),i={data:o,cachedAt:Date.now(),dataHash:this.hashData(o.translations)};localStorage.setItem(t,JSON.stringify(i)),this.enableDebug&&console.log("[TranslationService] Saved to cache:",t)}catch(t){console.error("[TranslationService] Failed to save cache:",t)}}getFromCache(r){try{let o=this.getCacheKey(r),t=localStorage.getItem(o);return t?JSON.parse(t):null}catch(o){return console.error("[TranslationService] Failed to read cache:",o),null}}refreshCacheTimestamp(r){try{let o=this.getFromCache(r);if(o){o.cachedAt=Date.now();let t=this.getCacheKey(r);localStorage.setItem(t,JSON.stringify(o))}}catch(o){console.error("[TranslationService] Failed to refresh cache timestamp:",o)}}isCacheExpired(r){return Date.now()-r.cachedAt>Ao}hasValidCache(r){let o=this.getFromCache(r);return o?!this.isCacheExpired(o):!1}getCacheKey(r){return`${Lr}${Ar(r)}`}getCriticalTranslationsOnly(){return ce}invalidateCache(r){let o=this.getCacheKey(r);localStorage.removeItem(o),this.enableDebug&&console.log("[TranslationService] Cache invalidated:",o)}async prefetchTranslations(r){try{await this.fetchTranslations(r),this.enableDebug&&console.log("[TranslationService] Prefetch completed")}catch(o){console.error("[TranslationService] Prefetch failed:",o)}}clearAllCaches(){try{let o=Object.keys(localStorage).filter(t=>t.startsWith(Lr));o.forEach(t=>localStorage.removeItem(t)),this.enableDebug&&console.log(`[TranslationService] Cleared ${o.length} cache entries`)}catch(r){console.error("[TranslationService] Failed to clear caches:",r)}}},We=rr.getInstance();import{createContext as Fo,useContext as _o,useEffect as Or,useState as Ie,useMemo as Fr,useCallback as Oo}from"react";import{Fragment as No,jsx as qe}from"react/jsx-runtime";var He=null,or=!1,Br=Fo(null);function _r(e,r,o){return{...e,...r,...o||{}}}function Bo(e,r,o,t,i){Or(()=>{if(!t||!e||!r)return;let n=o||typeof window<"u"&&window.i18next||typeof window<"u"&&window.i18n;if(!n||!n.addResourceBundle){i&&console.log("[TranslationsProvider] i18next not found, skipping auto-sync");return}i&&console.log("[TranslationsProvider] Auto-syncing translations with i18next",{languages:Object.keys(e),currentLanguage:r}),Object.keys(e).forEach(s=>{e[s]&&Object.keys(e[s]).length>0&&(n.addResourceBundle(s,"translation",e[s],!0,!0),i&&console.log(`[TranslationsProvider] Synced ${Object.keys(e[s]).length} keys for language: ${s}`))}),n.language!==r&&(n.changeLanguage(r),i&&console.log(`[TranslationsProvider] Changed i18next language to: ${r}`))},[e,r,o,t,i])}var Rs=({children:e,apiKey:r,crudifyEnv:o="prod",featureKeys:t,language:i="es",devTranslations:n,translationUrl:s,enableDebug:l=!1,skipAutoInit:c=!0,autoSyncI18n:w=!0,i18nInstance:d,loadingFallback:h,waitForInitialLoad:g=!0})=>{let a=Fr(()=>vr({publicApiKey:r,env:o,featureKeys:t,enableDebug:l}),[r,o,t,l]),u=a.publicApiKey||"",b=a.env||o||"prod",p=a.featureKeys||t,[y,m]=Ie({}),[C,R]=Ie(!0),[M,x]=Ie(!0),[f,P]=Ie(null),[L,_]=Ie(void 0),[ae,we]=Ie(!1),te=Oo(async()=>{if(!u){l&&console.log("[TranslationsProvider] No apiKey - skipping translation fetch"),R(!1),x(!1);return}if(ae){l&&console.log("[TranslationsProvider] Skipping reload - using fallback translations");return}if(We.hasValidCache(u)&&M&&(l&&console.log("[TranslationsProvider] Valid cache found - not blocking initial render"),x(!1)),or&&He){l&&console.log("[TranslationsProvider] Fetch already in progress, waiting for existing promise");try{let I=await He;m(I),R(!1);return}catch{l&&console.warn("[TranslationsProvider] Global fetch failed, retrying")}}or=!0,R(!0),P(null);let F;if(s)try{l&&console.log(`[TranslationsProvider] Fetching translations from URL: ${s}`);let I=await fetch(s);if(!I.ok)throw new Error(`Failed to fetch translations: ${I.statusText}`);F=await I.json(),_(F),l&&console.log("[TranslationsProvider] URL translations loaded:",{keysCount:F?Object.keys(F).length:0})}catch(I){console.error("[TranslationsProvider] Failed to load URL translations:",I),F=void 0,_(void 0)}let Ee=(async()=>{try{We.setDebug(l);let I=await We.fetchTranslations({apiKey:u,crudifyEnv:b,featureKeys:p,urlTranslations:F}),H={};return Object.keys(I).forEach(v=>{let S=ce[v]||{},O=I[v]||{};H[v]=_r(S,O,n)}),l&&console.log("[TranslationsProvider] Loaded translations:",{languages:Object.keys(H),keysCount:Object.keys(H[i]||{}).length}),H}catch(I){console.error("[TranslationsProvider] Failed to load:",I),P(I.message),we(!0);let H={};return Object.keys(ce).forEach(v=>{let S=ce[v],O=F||L||{};H[v]=_r(S,O,n)}),l&&console.log("[TranslationsProvider] Using fallback translations (critical + URL)"),H}})();He=Ee;try{let I=await Ee;m(I)}finally{R(!1),x(!1),or=!1,setTimeout(()=>{He=null},1e3)}},[u,b,p,s,n,l,i,ae]);Or(()=>{te();let V=setInterval(te,3600*1e3);return()=>clearInterval(V)},[te]);let ue=Fr(()=>(V,F)=>{let I=(y[i]||{})[V];if(!I){let H=Object.keys(y);for(let v of H)if(y[v][V]){I=y[v][V];break}}return I||(l&&console.warn(`[TranslationsProvider] Missing translation: "${V}"`),I=V),F&&typeof I=="string"&&Object.entries(F).forEach(([H,v])=>{let S=new RegExp(`{{${H}}}`,"g");I=I.replace(S,String(v))}),I},[y,i,l]);Bo(y,i,d,w,l);let A={t:ue,language:i,availableLanguages:Object.keys(y),translations:y,isLoading:C,error:f,refreshTranslations:te};return u?g&&M&&C?h||qe("div",{style:{display:"flex",justifyContent:"center",alignItems:"center",height:"100vh"},children:qe("div",{children:"Loading translations..."})}):qe(Br.Provider,{value:A,children:e}):(l&&console.warn("[TranslationsProvider] No API key available. Skipping translations. Provide apiKey via props or ensure cookies are set by Lambda."),qe(No,{children:e}))},Nr=()=>{let e=_o(Br);if(!e)throw new Error("useTranslations must be used within TranslationsProvider");return e};import{Box as Ct,Typography as Pt}from"@mui/material";import{createContext as zo,useContext as Uo,useMemo as nr}from"react";import{useState as tr,useEffect as Do}from"react";var Dr=(e,r)=>{let[o,t]=tr({}),[i,n]=tr(!1),[s,l]=tr(null);return Do(()=>{if(console.log("\u{1F527} [I18nProvider] Hybrid translation loading:",{hasProvidedTranslations:!!r&&Object.keys(r).length>0,hasUrl:!!e,providedKeys:r?Object.keys(r).length:0}),r&&Object.keys(r).length>0){console.log("\u2705 [I18nProvider] Using provided translations (highest priority)"),t(r),n(!1),l(null);return}if(!e){console.log("\u26A0\uFE0F [I18nProvider] No translations provided, using empty object (keys will show as-is)"),t({}),n(!1),l(null);return}console.log("\u{1F310} [I18nProvider] Loading translations from URL:",e);let c=!1;return n(!0),l(null),fetch(e).then(w=>{if(!w.ok)throw new Error(`Failed to load translations: ${w.status}`);return w.json()}).then(w=>{c||(console.log("\u2705 [I18nProvider] Translations loaded successfully from URL:",{url:e,keysLoaded:Object.keys(w).length}),t(w),n(!1))}).catch(w=>{c||(console.error("\u274C [I18nProvider] Failed to load translations from URL:",e,w),l(w.message),console.log("\u{1F504} [I18nProvider] Falling back to empty translations (keys will show as-is)"),t({}),n(!1))}),()=>{c=!0}},[e,r]),{translations:o,loading:i,error:s}};import{jsx as zr}from"react/jsx-runtime";var Ur=zo(null),Mo=()=>{try{return Nr()}catch{return null}},Vo=(e,r)=>{if(r.includes(".")){let o=r.split(".").reduce((t,i)=>t&&typeof t=="object"?t[i]:void 0,e);if(o!==void 0)return o}if(e&&e[r])return e[r]},Mr=({children:e,translations:r,translationsUrl:o,language:t="en"})=>{let n=Mo()?.translations?.[t]||{},{translations:s,loading:l}=Dr(o,r),c=nr(()=>({...n,...s,...r||{}}),[n,s,r]),w=nr(()=>(h,g)=>{let a=Vo(c,h);return a==null&&(console.log(`\u{1F50D} [I18nProvider] Translation not found for key: "${h}" - showing key as-is`),a=h),g&&typeof a=="string"&&Object.entries(g).forEach(([u,b])=>{a=a.replace(new RegExp(`{{${u}}}`,"g"),b)}),typeof a=="string"?a:h},[c]),d=nr(()=>({t:w,language:t}),[w,t]);return l?zr("div",{children:"Loading translations..."}):zr(Ur.Provider,{value:d,children:e})},Q=()=>{let e=Uo(Ur);if(!e)throw new Error("useTranslation must be used within I18nProvider");return e};import{createContext as Wo,useContext as Ho,useReducer as qo,useEffect as Vr}from"react";import{jsx as $o}from"react/jsx-runtime";var Wr={currentScreen:"login",searchParams:{},formData:{username:"",password:"",email:"",code:"",newPassword:"",confirmPassword:""},loading:!1,errors:{global:[]},emailSent:!1,codeAlreadyExists:!1,codeValidated:!1,fromCodeVerification:!1,config:{}};function jo(e,r){switch(r.type){case"SET_SCREEN":let o={...e,currentScreen:r.payload.screen,searchParams:r.payload.params||e.searchParams,errors:{global:[]}},t=new URLSearchParams(o.searchParams),i=t.toString()?`?${t.toString()}`:window.location.pathname;try{window.history.replaceState({},"",i)}catch{}return o;case"SET_SEARCH_PARAMS":return{...e,searchParams:r.payload};case"UPDATE_FORM_DATA":return{...e,formData:{...e.formData,...r.payload},errors:{...e.errors,...Object.keys(r.payload).reduce((n,s)=>({...n,[s]:void 0}),{})}};case"SET_LOADING":return{...e,loading:r.payload};case"SET_ERRORS":return{...e,errors:{...e.errors,...r.payload}};case"CLEAR_ERRORS":return{...e,errors:{global:[]}};case"SET_EMAIL_SENT":return{...e,emailSent:r.payload};case"SET_CODE_ALREADY_EXISTS":return{...e,codeAlreadyExists:r.payload};case"SET_CODE_VALIDATED":return{...e,codeValidated:r.payload};case"SET_FROM_CODE_VERIFICATION":return{...e,fromCodeVerification:r.payload};case"RESET_FORM":return{...e,formData:Wr.formData,errors:{global:[]},loading:!1,emailSent:!1,codeAlreadyExists:!1,codeValidated:!1,fromCodeVerification:!1};case"INIT_CONFIG":return{...e,config:r.payload};default:return e}}var Hr=Wo(void 0),qr=({children:e,initialScreen:r="login",config:o,autoReadFromCookies:t=!0})=>{let[i,n]=qo(jo,{...Wr,currentScreen:r});Vr(()=>{n({type:"INIT_CONFIG",payload:(()=>{let a={};if(t)try{let u=Pr("logo");if(u){let b=decodeURIComponent(u);b.startsWith("http")&&(a.logo=b)}}catch(u){console.error("Error reading configuration from cookies:",u)}return{publicApiKey:o?.publicApiKey,env:o?.env,appName:o?.appName,logo:o?.logo||a.logo,loginActions:o?.loginActions}})()})},[o,t]),Vr(()=>{let g=new URLSearchParams(window.location.search),a={};g.forEach((u,b)=>{a[b]=u}),Object.keys(a).length>0&&n({type:"SET_SEARCH_PARAMS",payload:a}),r==="checkCode"&&a.email&&n({type:"UPDATE_FORM_DATA",payload:{email:a.email,code:a.code||""}}),r==="resetPassword"&&a.link&&n({type:"SET_SEARCH_PARAMS",payload:a})},[r]);let h={state:i,dispatch:n,setScreen:(g,a)=>{n({type:"SET_SCREEN",payload:{screen:g,params:a}})},updateFormData:g=>{n({type:"UPDATE_FORM_DATA",payload:g})},setFieldError:(g,a)=>{n({type:"SET_ERRORS",payload:{[g]:a}})},clearErrors:()=>{n({type:"CLEAR_ERRORS"})},setLoading:g=>{n({type:"SET_LOADING",payload:g})}};return $o(Hr.Provider,{value:h,children:e})},je=()=>{let e=Ho(Hr);if(e===void 0)throw new Error("useLoginState must be used within a LoginStateProvider");return e};import{useEffect as Ko,useRef as Go}from"react";import{Typography as sr,TextField as jr,Button as Yo,Box as _e,CircularProgress as Xo,Alert as Jo,Link as $r}from"@mui/material";import{Fragment as Zo,jsx as Z,jsxs as Oe}from"react/jsx-runtime";var Qo=({onScreenChange:e,onExternalNavigate:r,onLoginSuccess:o,onError:t,redirectUrl:i="/"})=>{let{crudify:n}=ne(),{state:s,updateFormData:l,setFieldError:c,clearErrors:w,setLoading:d}=je(),{login:h}=ge(),g=Q(),{t:a}=g,u=g.i18n,b=Go(null),p=Er(a,{currentLanguage:u?.language,enableDebug:!1}),y=()=>{if(s.searchParams.redirect)try{let f=decodeURIComponent(s.searchParams.redirect);if(f.startsWith("/")&&!f.startsWith("//"))return f}catch{}return i||"/"};Ko(()=>{let f=setTimeout(()=>{b.current&&b.current.focus()},100);return()=>clearTimeout(f)},[]);let m=f=>{console.log("\u{1F50D} [LoginForm] Translating parsed error:",f);let P=p.translateError({code:f.code,message:f.message,field:f.field});return console.log("\u{1F50D} [LoginForm] Translation result:",P),P},C=async()=>{if(!s.loading){if(!s.formData.username.trim()){c("username",a("login.usernameRequired"));return}if(!s.formData.password.trim()){c("password",a("login.passwordRequired"));return}w(),d(!0);try{let f=await h(s.formData.username,s.formData.password);if(d(!1),f.success){console.log("\u{1F510} LoginForm - Login successful via SessionProvider, calling onLoginSuccess");let P=y();o&&o(f.data,P)}else{let P=f.rawResponse||f;R(P)}}catch(f){d(!1);let L=K(f).map(m);c("global",L),t&&t(L.join(", "))}}},R=f=>{let P=K(f),L=[];P.forEach(_=>{_.field?c(_.field,m(_)):L.push(m(_))}),L.length>0&&c("global",L)};return Oe(Zo,{children:[Oe(_e,{component:"form",noValidate:!0,onSubmit:f=>{f.preventDefault(),C()},onKeyDown:f=>{f.key==="Enter"&&!s.loading&&(f.preventDefault(),C())},sx:{width:"100%",display:"flex",flexDirection:"column",gap:2},children:[Oe(_e,{sx:{mb:1},children:[Z(sr,{variant:"body2",component:"label",htmlFor:"email",sx:{display:"block",fontWeight:500,color:"grey.700",mb:.5},children:a("login.usernameOrEmailLabel")}),Z(jr,{fullWidth:!0,id:"email",name:"email",type:"email",value:s.formData.username,disabled:s.loading,onChange:f=>l({username:f.target.value}),error:!!s.errors.username,helperText:s.errors.username,autoComplete:"email",placeholder:a("login.usernameOrEmailPlaceholder"),inputRef:b,required:!0})]}),Oe(_e,{sx:{mb:1},children:[Z(sr,{variant:"body2",component:"label",htmlFor:"password",sx:{display:"block",fontWeight:500,color:"grey.700",mb:.5},children:a("login.passwordLabel")}),Z(jr,{fullWidth:!0,id:"password",name:"password",type:"password",value:s.formData.password,disabled:s.loading,onChange:f=>l({password:f.target.value}),error:!!s.errors.password,helperText:s.errors.password,autoComplete:"current-password",placeholder:a("login.passwordPlaceholder"),required:!0})]}),s.config.loginActions?.includes("forgotPassword")&&Z(_e,{sx:{display:"flex",justifyContent:"flex-end",alignItems:"center"},children:Z($r,{sx:{cursor:"pointer"},onClick:()=>{e?.("forgotPassword",s.searchParams)},variant:"body2",color:"secondary",children:a("login.forgotPasswordLink")})}),Z(Yo,{disabled:s.loading,type:"submit",fullWidth:!0,variant:"contained",color:"primary",sx:{mt:1,mb:2},children:s.loading?Z(Xo,{size:20}):a("login.loginButton")})]}),Z(_e,{children:s.errors.global&&s.errors.global.length>0&&s.errors.global.map((f,P)=>Z(Jo,{variant:"filled",sx:{mt:2},severity:"error",children:Z("div",{children:f})},P))}),s.config.loginActions?.includes("createUser")&&Oe(sr,{variant:"body2",align:"center",sx:{color:"text.secondary",mt:3},children:[a("login.noAccountPrompt")," ",Z($r,{sx:{cursor:"pointer"},onClick:()=>{let P=`/public/users/create${Object.keys(s.searchParams).length>0?`?${new URLSearchParams(s.searchParams).toString()}`:""}`;r?.(P)},fontWeight:"medium",color:"secondary",children:a("login.signUpLink")})]})]})},Kr=Qo;import{useState as Se,useEffect as et,useRef as rt}from"react";import{Typography as ke,TextField as ot,Button as Gr,Box as me,CircularProgress as tt,Alert as nt,Link as ir}from"@mui/material";import{Fragment as Yr,jsx as U,jsxs as Ce}from"react/jsx-runtime";var st=({onScreenChange:e,onError:r})=>{let{crudify:o}=ne(),[t,i]=Se(""),[n,s]=Se(!1),[l,c]=Se([]),[w,d]=Se(null),[h,g]=Se(!1),[a,u]=Se(!1),b=rt(null),{t:p}=Q();et(()=>{b.current&&!h&&!a&&b.current.focus()},[h,a]);let y=f=>{let P=[`errors.auth.${f.code}`,`errors.data.${f.code}`,`errors.system.${f.code}`,`errors.${f.code}`,`forgotPassword.${f.code.toLowerCase()}`];for(let L of P){let _=p(L);if(_!==L)return _}return f.message||p("error.unknown")},m=f=>/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(f),C=async()=>{if(!(n||!o)){if(c([]),d(null),!t){d(p("forgotPassword.emailRequired"));return}if(!m(t)){d(p("forgotPassword.invalidEmail"));return}s(!0);try{let f=[{operation:"requestPasswordReset",data:{email:t}}],P=await o.transaction(f);if(P.success)P.data&&P.data.existingCodeValid?u(!0):g(!0);else{let _=K(P).map(y);c(_)}}catch(f){let L=K(f).map(y);c(L),r&&r(L.join(", "))}finally{s(!1)}}},R=()=>{e?.("login")},M=()=>{if(h||a){e?.("checkCode",{email:t});return}if(!t){d(p("forgotPassword.emailRequired"));return}if(!m(t)){d(p("forgotPassword.invalidEmail"));return}e?.("checkCode",{email:t})};return h||a?U(Yr,{children:Ce(me,{sx:{width:"100%",display:"flex",flexDirection:"column",gap:2,textAlign:"center"},children:[Ce(me,{sx:{mb:2},children:[U(ke,{variant:"h5",component:"h1",sx:{mb:1,fontWeight:600},children:p(a?"forgotPassword.codeAlreadyExistsMessage":"forgotPassword.emailSentMessage")}),U(ke,{variant:"body2",sx:{color:a?"success.main":"grey.600"},children:p("forgotPassword.checkEmailInstructions")})]}),U(Gr,{type:"button",onClick:M,fullWidth:!0,variant:"contained",color:"primary",sx:{mt:2,mb:2},children:p("forgotPassword.enterCodeLink")}),U(me,{sx:{display:"flex",justifyContent:"center",alignItems:"center"},children:U(ir,{sx:{cursor:"pointer"},onClick:R,variant:"body2",color:"secondary",children:p("common.back")})})]})}):Ce(Yr,{children:[Ce(me,{component:"form",noValidate:!0,onSubmit:f=>{f.preventDefault(),C()},sx:{width:"100%",display:"flex",flexDirection:"column",gap:2},children:[Ce(me,{sx:{mb:2},children:[U(ke,{variant:"h5",component:"h1",sx:{mb:1,fontWeight:600},children:p("forgotPassword.title")}),U(ke,{variant:"body2",sx:{color:"grey.600"},children:p("forgotPassword.instructions")})]}),Ce(me,{sx:{mb:1},children:[U(ke,{variant:"body2",component:"label",htmlFor:"email",sx:{display:"block",fontWeight:500,color:"grey.700",mb:.5},children:p("forgotPassword.emailLabel")}),U(ot,{fullWidth:!0,id:"email",name:"email",type:"email",value:t,disabled:n,onChange:f=>i(f.target.value),error:!!w,helperText:w,autoComplete:"email",placeholder:p("forgotPassword.emailPlaceholder"),required:!0,autoFocus:!0,inputRef:b})]}),U(Gr,{disabled:n,type:"submit",fullWidth:!0,variant:"contained",color:"primary",sx:{mt:2,mb:2},children:n?U(tt,{size:20}):p("forgotPassword.sendCodeButton")}),Ce(me,{sx:{display:"flex",justifyContent:"center",alignItems:"center",gap:2},children:[U(ir,{sx:{cursor:"pointer"},onClick:R,variant:"body2",color:"secondary",children:p("common.back")}),U(ke,{variant:"body2",sx:{color:"grey.400"},children:"\u2022"}),U(ir,{sx:{cursor:"pointer"},onClick:M,variant:"body2",color:"secondary",children:p("login.alreadyHaveCodeLink")})]})]}),U(me,{children:l.length>0&&l.map((f,P)=>U(nt,{variant:"filled",sx:{mt:2},severity:"error",children:f},P))})]})},Xr=st;import{useState as X,useEffect as Jr}from"react";import{Typography as $e,TextField as Qr,Button as it,Box as pe,CircularProgress as Zr,Alert as eo,Link as at}from"@mui/material";import{Fragment as ct,jsx as W,jsxs as Be}from"react/jsx-runtime";var lt=({onScreenChange:e,onError:r,searchParams:o,onResetSuccess:t})=>{let{crudify:i}=ne(),[n,s]=X(""),[l,c]=X(""),[w,d]=X(!1),[h,g]=X([]),[a,u]=X(null),[b,p]=X(null),[y,m]=X(""),[C,R]=X(""),[M,x]=X(!1),[f,P]=X(!0),[L,_]=X(!1),[ae,we]=X(null),[te,ue]=X(!1),{t:A}=Q(),V=v=>{let S=[`errors.auth.${v.code}`,`errors.data.${v.code}`,`errors.system.${v.code}`,`errors.${v.code}`,`resetPassword.${v.code.toLowerCase()}`];for(let O of S){let q=A(O);if(q!==O)return q}return v.message||A("error.unknown")},F=v=>o?o instanceof URLSearchParams?o.get(v):o[v]||null:null;Jr(()=>{if(o){if(o){let v=F("fromCodeVerification"),S=F("email"),O=F("code");if(v==="true"&&S&&O){m(S),R(O),x(!0),_(!0),P(!1);return}let q=F("link");if(q)try{let G=decodeURIComponent(q),[Y,le]=G.split("/");if(Y&&le&&Y.length===6){R(Y),m(le),x(!1),we({email:le,code:Y});return}}catch{}if(S&&O){m(S),R(O),x(!1),we({email:S,code:O});return}}g([A("resetPassword.invalidCode")]),P(!1),setTimeout(()=>e?.("forgotPassword"),3e3)}},[o,i,A,e]),Jr(()=>{i&&ae&&!te&&(ue(!0),(async(S,O)=>{try{let q=[{operation:"validatePasswordResetCode",data:{email:S,codePassword:O}}],G=await i.transaction(q);if(G.data&&Array.isArray(G.data)){let Y=G.data[0];if(Y&&Y.response&&Y.response.status==="OK"){_(!0);return}}if(G.success)_(!0);else{let le=K(G).map(V);g(le),setTimeout(()=>e?.("forgotPassword"),3e3)}}catch(q){let Y=K(q).map(V);g(Y),setTimeout(()=>e?.("forgotPassword"),3e3)}finally{P(!1),we(null),ue(!1)}})(ae.email,ae.code))},[i,ae,A,e]);let Ee=v=>v.length<8?A("resetPassword.passwordTooShort"):null,I=async()=>{if(w||!i)return;g([]),u(null),p(null);let v=!1;if(!n)u(A("resetPassword.newPasswordRequired")),v=!0;else{let S=Ee(n);S&&(u(S),v=!0)}if(l?n!==l&&(p(A("resetPassword.passwordsDoNotMatch")),v=!0):(p(A("resetPassword.confirmPasswordRequired")),v=!0),!v){d(!0);try{let S=[{operation:"validateAndResetPassword",data:{email:y,codePassword:C,newPassword:n}}],O=await i.transaction(S);if(O.success)g([]),setTimeout(()=>{t?.()},1e3);else{let G=K(O).map(V);g(G)}}catch(S){let q=K(S).map(V);g(q),r&&r(q.join(", "))}d(!1)}},H=()=>{M?e?.("checkCode",{email:y}):e?.("forgotPassword")};return f?W(pe,{sx:{display:"flex",justifyContent:"center",alignItems:"center",minHeight:"300px"},children:W(Zr,{})}):L?Be(ct,{children:[Be(pe,{component:"form",noValidate:!0,sx:{width:"100%",display:"flex",flexDirection:"column",gap:2},children:[Be(pe,{sx:{mb:2},children:[W($e,{variant:"h5",component:"h1",sx:{mb:1,fontWeight:600},children:A("resetPassword.title")}),W($e,{variant:"body2",sx:{color:"grey.600"},children:A("resetPassword.instructions")})]}),Be(pe,{sx:{mb:1},children:[W($e,{variant:"body2",component:"label",htmlFor:"newPassword",sx:{display:"block",fontWeight:500,color:"grey.700",mb:.5},children:A("resetPassword.newPasswordLabel")}),W(Qr,{fullWidth:!0,id:"newPassword",name:"newPassword",type:"password",value:n,disabled:w,onChange:v=>s(v.target.value),error:!!a,helperText:a,autoComplete:"new-password",placeholder:A("resetPassword.newPasswordPlaceholder"),required:!0})]}),Be(pe,{sx:{mb:1},children:[W($e,{variant:"body2",component:"label",htmlFor:"confirmPassword",sx:{display:"block",fontWeight:500,color:"grey.700",mb:.5},children:A("resetPassword.confirmPasswordLabel")}),W(Qr,{fullWidth:!0,id:"confirmPassword",name:"confirmPassword",type:"password",value:l,disabled:w,onChange:v=>c(v.target.value),error:!!b,helperText:b,autoComplete:"new-password",placeholder:A("resetPassword.confirmPasswordPlaceholder"),required:!0})]}),W(it,{disabled:w,type:"button",onClick:I,fullWidth:!0,variant:"contained",color:"primary",sx:{mt:2,mb:2},children:w?W(Zr,{size:20}):A("resetPassword.resetPasswordButton")}),W(pe,{sx:{display:"flex",justifyContent:"center",alignItems:"center"},children:W(at,{sx:{cursor:"pointer"},onClick:H,variant:"body2",color:"secondary",children:A("common.back")})})]}),W(pe,{children:h.length>0&&h.map((v,S)=>W(eo,{variant:"filled",sx:{mt:2},severity:"error",children:v},S))})]}):W(pe,{children:h.length>0&&h.map((v,S)=>W(eo,{variant:"filled",sx:{mt:2},severity:"error",children:v},S))})},ro=lt;import{useState as Ne,useEffect as oo,useRef as dt}from"react";import{Typography as ar,TextField as ut,Button as gt,Box as De,CircularProgress as mt,Alert as pt,Link as ft}from"@mui/material";import{Fragment as ht,jsx as se,jsxs as Ke}from"react/jsx-runtime";var yt=({onScreenChange:e,onError:r,searchParams:o})=>{let{crudify:t}=ne(),[i,n]=Ne(""),[s,l]=Ne(!1),[c,w]=Ne([]),[d,h]=Ne(null),[g,a]=Ne(""),u=dt(null),{t:b}=Q(),p=x=>o?o instanceof URLSearchParams?o.get(x):o[x]||null:null,y=x=>{let f=[`errors.auth.${x.code}`,`errors.data.${x.code}`,`errors.system.${x.code}`,`errors.${x.code}`,`checkCode.${x.code.toLowerCase()}`];for(let P of f){let L=b(P);if(L!==P)return L}return x.message||b("error.unknown")};oo(()=>{let x=p("email");x?a(x):e?.("forgotPassword")},[o,e]),oo(()=>{u.current&&u.current.focus()},[]);let m=async()=>{if(!(s||!t)){if(w([]),h(null),!i){h(b("checkCode.codeRequired"));return}if(i.length!==6){h(b("checkCode.codeRequired"));return}l(!0);try{let x=[{operation:"validatePasswordResetCode",data:{email:g,codePassword:i}}],f=await t.transaction(x);if(f.success)e?.("resetPassword",{email:g,code:i,fromCodeVerification:"true"});else{let L=K(f).map(y);w(L),l(!1)}}catch(x){let P=K(x).map(y);w(P),l(!1),r&&r(P.join(", "))}}},C=()=>{e?.("forgotPassword")},R=x=>{let f=x.target.value.replace(/\D/g,"").slice(0,6);n(f)};return Ke(ht,{children:[Ke(De,{component:"form",noValidate:!0,onSubmit:x=>{x.preventDefault(),m()},sx:{width:"100%",display:"flex",flexDirection:"column",gap:2},children:[Ke(De,{sx:{mb:2},children:[se(ar,{variant:"h5",component:"h1",sx:{mb:1,fontWeight:600},children:b("checkCode.title")}),se(ar,{variant:"body2",sx:{color:"grey.600"},children:b("checkCode.instructions")})]}),Ke(De,{sx:{mb:1},children:[se(ar,{variant:"body2",component:"label",htmlFor:"code",sx:{display:"block",fontWeight:500,color:"grey.700",mb:.5},children:b("checkCode.codeLabel")}),se(ut,{fullWidth:!0,id:"code",name:"code",type:"text",value:i,disabled:s,onChange:R,error:!!d,helperText:d,placeholder:b("checkCode.codePlaceholder"),inputProps:{maxLength:6,style:{textAlign:"center",fontSize:"1.5rem",letterSpacing:"0.4rem"}},required:!0,autoFocus:!0,inputRef:u})]}),se(gt,{disabled:s||i.length!==6,type:"submit",fullWidth:!0,variant:"contained",color:"primary",sx:{mt:2,mb:2},children:s?se(mt,{size:20}):b("checkCode.verifyButton")}),se(De,{sx:{display:"flex",justifyContent:"center",alignItems:"center"},children:se(ft,{sx:{cursor:"pointer"},onClick:C,variant:"body2",color:"secondary",children:b("common.back")})})]}),se(De,{children:c.length>0&&c.map((x,f)=>se(pt,{sx:{mt:2},severity:"error",children:x},f))})]})},to=yt;import{Box as bt,CircularProgress as wt,Alert as no,Typography as lr}from"@mui/material";import{Fragment as xt,jsx as Le,jsxs as so}from"react/jsx-runtime";var io=({children:e,fallback:r})=>{let{isLoading:o,error:t,isInitialized:i}=ne(),{t:n}=Q();return o?r||so(bt,{sx:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",minHeight:"200px",gap:2},children:[Le(wt,{}),Le(lr,{variant:"body2",color:"text.secondary",children:n("login.initializing")!=="login.initializing"?n("login.initializing"):"Initializing..."})]}):t?Le(no,{severity:"error",sx:{mt:2},children:so(lr,{variant:"body2",children:[n("login.initializationError")!=="login.initializationError"?n("login.initializationError"):"Initialization error",":"," ",t]})}):i?Le(xt,{children:e}):Le(no,{severity:"warning",sx:{mt:2},children:Le(lr,{variant:"body2",children:n("login.notInitialized")!=="login.notInitialized"?n("login.notInitialized"):"System not initialized"})})};import{jsx as re,jsxs as Et}from"react/jsx-runtime";var vt=({onScreenChange:e,onExternalNavigate:r,onLoginSuccess:o,onError:t,redirectUrl:i="/"})=>{let{t:n}=Q(),{state:s,setScreen:l}=je(),{config:c}=ge(),{showNotification:w}=Rr(),d=(g,a)=>{let u=a;g==="login"?u={}:g==="forgotPassword"&&!a&&(u={}),l(g,u),e?.(g,u)},h=()=>{let g={onScreenChange:d,onExternalNavigate:r,onError:t,redirectUrl:i};switch(s.currentScreen){case"forgotPassword":return re(Xr,{...g});case"checkCode":return re(to,{...g,searchParams:s.searchParams});case"resetPassword":return re(ro,{...g,searchParams:s.searchParams,onResetSuccess:()=>{let a=n("resetPassword.successMessage");w(a,"success"),d("login")}});default:return re(Kr,{...g,onLoginSuccess:o})}};return Et(io,{children:[re(Ct,{sx:{display:"flex",justifyContent:"center",mb:3},children:re("img",{src:c.logo||"https://logos.crudia.com/nocios-default.png",alt:n("login.logoAlt"),style:{width:"100%",maxWidth:"150px",height:"auto"},onError:g=>{let a=g.target;a.src="https://logos.crudia.com/nocios-default.png"}})}),!c.logo&&c.appName&&re(Pt,{variant:"h6",component:"h1",sx:{textAlign:"center",mb:2},children:c.appName}),h()]})},Tt=({translations:e,translationsUrl:r,language:o="en",initialScreen:t="login",autoReadFromCookies:i=!0,...n})=>{let{config:s}=ge();return re(Mr,{translations:e,translationsUrl:r,language:o,children:re(Tr,{config:s,children:re(qr,{config:s,initialScreen:t,autoReadFromCookies:i,children:re(vt,{...n})})})})},Bi=Tt;import{Box as J,Card as ao,CardContent as lo,Typography as oe,Chip as Ge,Avatar as Rt,Divider as It,CircularProgress as St,Alert as co,List as kt,ListItem as cr,ListItemText as dr,ListItemIcon as Lt,Collapse as At,IconButton as ur}from"@mui/material";import{Person as Ft,Email as _t,Badge as Ot,Security as Bt,Schedule as Nt,AccountCircle as Dt,ExpandMore as zt,ExpandLess as Ut,Info as Mt}from"@mui/icons-material";import{useState as Vt}from"react";import{Fragment as qt,jsx as T,jsxs as B}from"react/jsx-runtime";var Wt=({showExtendedData:e=!0,showProfileCard:r=!0,autoRefresh:o=!0})=>{let{userProfile:t,loading:i,error:n,extendedData:s,refreshProfile:l}=Ir({autoFetch:o,retryOnError:!0,maxRetries:3}),[c,w]=Vt(!1);if(i)return B(J,{display:"flex",justifyContent:"center",alignItems:"center",p:3,children:[T(St,{}),T(oe,{variant:"body2",sx:{ml:2},children:"Cargando perfil de usuario..."})]});if(n)return B(co,{severity:"error",action:T(ur,{color:"inherit",size:"small",onClick:l,children:T(oe,{variant:"caption",children:"Reintentar"})}),children:["Error al cargar el perfil: ",n]});if(!t)return T(co,{severity:"warning",children:"No se encontr\xF3 informaci\xF3n del usuario"});let d=s?.displayData||{},h=s?.totalFields||0,g=m=>{if(!m)return"No disponible";try{return new Date(m).toLocaleString("es-ES",{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}catch{return m}},a=(m,C)=>C==null?"No disponible":typeof C=="boolean"?C?"S\xED":"No":Array.isArray(C)?C.length>0?C.join(", "):"Ninguno":typeof C=="object"?JSON.stringify(C,null,2):String(C),u=[{key:"id",label:"ID",icon:T(Ot,{})},{key:"email",label:"Email",icon:T(_t,{})},{key:"username",label:"Usuario",icon:T(Ft,{})},{key:"fullName",label:"Nombre completo",icon:T(Dt,{})},{key:"role",label:"Rol",icon:T(Bt,{})}],b=[{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"}],p=[...u.map(m=>m.key),...b.map(m=>m.key),"permissions"],y=Object.keys(d).filter(m=>!p.includes(m)).map(m=>({key:m,label:m}));return B(J,{children:[r&&T(ao,{sx:{mb:2},children:B(lo,{children:[B(J,{display:"flex",alignItems:"center",mb:2,children:[T(Rt,{src:d.avatar,sx:{width:56,height:56,mr:2},children:d.fullName?.[0]||d.username?.[0]||d.email?.[0]}),B(J,{children:[T(oe,{variant:"h6",children:d.fullName||d.username||d.email}),T(oe,{variant:"body2",color:"text.secondary",children:d.role||"Usuario"}),d.isActive!==void 0&&T(Ge,{label:d.isActive?"Activo":"Inactivo",color:d.isActive?"success":"error",size:"small",sx:{mt:.5}})]})]}),T(J,{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(250px, 1fr))",gap:2,children:u.map(({key:m,label:C,icon:R})=>d[m]?B(J,{display:"flex",alignItems:"center",children:[T(J,{sx:{mr:1,color:"text.secondary"},children:R}),B(J,{children:[T(oe,{variant:"caption",color:"text.secondary",children:C}),T(oe,{variant:"body2",children:a(m,d[m])})]})]},m):null)}),d.permissions&&Array.isArray(d.permissions)&&d.permissions.length>0&&B(J,{mt:2,children:[T(oe,{variant:"caption",color:"text.secondary",display:"block",children:"Permisos"}),B(J,{display:"flex",flexWrap:"wrap",gap:.5,mt:.5,children:[d.permissions.slice(0,5).map((m,C)=>T(Ge,{label:m,size:"small",variant:"outlined"},C)),d.permissions.length>5&&T(Ge,{label:`+${d.permissions.length-5} m\xE1s`,size:"small"})]})]})]})}),e&&T(ao,{children:B(lo,{children:[B(J,{display:"flex",justifyContent:"space-between",alignItems:"center",mb:2,children:[B(oe,{variant:"h6",display:"flex",alignItems:"center",children:[T(Mt,{sx:{mr:1}}),"Informaci\xF3n Detallada"]}),T(Ge,{label:`${h} campos totales`,size:"small"})]}),B(kt,{dense:!0,children:[b.map(({key:m,label:C})=>d[m]!==void 0&&B(cr,{divider:!0,children:[T(Lt,{children:T(Nt,{fontSize:"small"})}),T(dr,{primary:C,secondary:m.includes("At")||m.includes("Login")?g(d[m]):a(m,d[m])})]},m)),y.length>0&&B(qt,{children:[T(It,{sx:{my:1}}),T(cr,{children:T(dr,{primary:B(J,{display:"flex",justifyContent:"space-between",alignItems:"center",children:[B(oe,{variant:"subtitle2",children:["Campos Personalizados (",y.length,")"]}),T(ur,{size:"small",onClick:()=>w(!c),children:c?T(Ut,{}):T(zt,{})})]})})}),T(At,{in:c,children:y.map(({key:m,label:C})=>T(cr,{sx:{pl:4},children:T(dr,{primary:C,secondary:a(m,d[m])})},m))})]})]}),B(J,{mt:2,display:"flex",justifyContent:"space-between",alignItems:"center",children:[B(oe,{variant:"caption",color:"text.secondary",children:["\xDAltima actualizaci\xF3n: ",g(d.updatedAt)]}),T(ur,{size:"small",onClick:l,disabled:i,children:T(oe,{variant:"caption",children:"Actualizar"})})]})]})})]})},Ht=Wt;var uo=["create","read","update","delete"],go=["create","read","update","delete"];import{useRef as pn}from"react";import{useTranslation as fn}from"react-i18next";import{Box as Je,Typography as wo,Button as yn,Stack as hn,Alert as xo,Divider as bn}from"@mui/material";import{Add as wn}from"@mui/icons-material";import{forwardRef as en}from"react";import{useTranslation as rn}from"react-i18next";import{Box as Pe,FormControl as on,InputLabel as tn,Select as nn,MenuItem as sn,IconButton as an,Typography as Ae,FormHelperText as ln,Stack as Xe,Paper as bo,Divider as cn,Button as fr}from"@mui/material";import{Delete as dn,SelectAll as un,ClearAll as gn}from"@mui/icons-material";import{useState as mo,useEffect as po,useRef as fo}from"react";import{useTranslation as jt}from"react-i18next";import{Box as Ye,Typography as ze,Button as yo,Stack as gr,FormControlLabel as $t,FormHelperText as ho,Switch as Kt,ToggleButton as mr,ToggleButtonGroup as Gt}from"@mui/material";import{CheckCircle as Yt,Cancel as Xt,SelectAll as Jt,ClearAll as Qt}from"@mui/icons-material";import{jsx as D,jsxs as fe}from"react/jsx-runtime";var Zt=({value:e,onChange:r,availableFields:o,error:t,disabled:i=!1})=>{let{t:n}=jt(),[s,l]=mo("custom"),[c,w]=mo(!1),d=fo(null);po(()=>{c&&d.current?.scrollIntoView({behavior:"smooth",block:"start"})},[c]);let h=fo(!1);po(()=>{let p=e||{allow:[],owner_allow:[],deny:[]},y=new Set(o),m=(p.allow||[]).filter(x=>y.has(x)),C=(p.owner_allow||[]).filter(x=>y.has(x)),R=(p.deny||[]).filter(x=>y.has(x));o.forEach(x=>{!m.includes(x)&&!C.includes(x)&&!R.includes(x)&&R.push(x)});let M={allow:m,owner_allow:C,deny:R};JSON.stringify(M)!==JSON.stringify(p)&&r(M),m.length===o.length?l("all"):R.length===o.length?l("none"):l("custom")},[o,e]);let g=()=>{h.current=!0,r({allow:[...o],owner_allow:[],deny:[]}),l("all"),setTimeout(()=>{h.current=!1},0)},a=()=>{h.current=!0,r({allow:[],owner_allow:[],deny:[...o]}),l("none"),setTimeout(()=>{h.current=!1},0)},u=p=>e?.allow?.includes(p)?"allow":e?.owner_allow?.includes(p)?"owner_allow":"deny",b=(p,y)=>{h.current=!0;let m=new Set(e?.allow||[]),C=new Set(e?.owner_allow||[]),R=new Set(e?.deny||[]);m.delete(p),C.delete(p),R.delete(p),y==="allow"&&m.add(p),y==="owner_allow"&&C.add(p),y==="deny"&&R.add(p),r({allow:Array.from(m),owner_allow:Array.from(C),deny:Array.from(R)}),l("custom"),setTimeout(()=>{h.current=!1},0)};return o.length===0?fe(Ye,{children:[D(ze,{variant:"body2",color:"text.secondary",sx:{mb:1},children:n("modules.form.publicPolicies.fields.conditions.label")}),D(ze,{variant:"body2",color:"text.secondary",sx:{fontStyle:"italic"},children:n("modules.form.publicPolicies.fields.conditions.noFieldsAvailable")}),t&&D(ho,{error:!0,sx:{mt:1},children:t})]}):fe(Ye,{children:[D(ze,{variant:"body2",color:"text.secondary",sx:{mb:2},children:n("modules.form.publicPolicies.fields.conditions.label")}),fe(gr,{direction:"row",spacing:1,alignItems:"center",sx:{mb:c?3:1},children:[D(yo,{variant:s==="all"?"contained":"outlined",startIcon:D(Jt,{}),onClick:g,disabled:i,size:"small",sx:{minWidth:120,...s==="all"&&{backgroundColor:"#16a34a","&:hover":{backgroundColor:"#15803d"}}},children:n("modules.form.publicPolicies.fields.conditions.allFields")}),D(yo,{variant:s==="none"?"contained":"outlined",startIcon:D(Qt,{}),onClick:a,disabled:i,size:"small",sx:{minWidth:120,...s==="none"&&{backgroundColor:"#cf222e","&:hover":{backgroundColor:"#bc1f2c"}}},children:n("modules.form.publicPolicies.fields.conditions.noFields")}),D(Ye,{sx:{display:"flex",alignItems:"center",px:1.5,py:.35,borderRadius:"999px",backgroundColor:"#f3f4f6",border:"1px solid #d1d9e0"},children:D($t,{control:D(Kt,{size:"small",checked:c,onChange:()=>w(p=>!p),disabled:i,color:"primary",sx:{transform:"scale(1.15)",transformOrigin:"center",m:0}}),label:n("modules.form.publicPolicies.fields.conditions.customEdit"),labelPlacement:"end",sx:{ml:0,".MuiFormControlLabel-label":{fontSize:"0.75rem"}}})})]}),c&&fe(Ye,{ref:d,sx:{p:2,border:"1px solid #d1d9e0",borderRadius:1,backgroundColor:"#f6f8fa"},children:[D(ze,{variant:"body2",color:"text.secondary",sx:{mb:2},children:n("modules.form.publicPolicies.fields.conditions.help")}),D(gr,{spacing:1,children:o.map(p=>{let y=u(p);return fe(gr,{direction:"row",spacing:1,alignItems:"center",children:[D(ze,{variant:"body2",sx:{minWidth:100,fontFamily:"monospace"},children:p}),fe(Gt,{value:y,exclusive:!0,size:"small",children:[fe(mr,{value:"allow",onClick:()=>b(p,"allow"),disabled:i,sx:{px:2,color:y==="allow"?"#ffffff":"#6b7280",backgroundColor:y==="allow"?"#16a34a":"#f3f4f6",borderColor:y==="allow"?"#16a34a":"#d1d5db","&:hover":{backgroundColor:y==="allow"?"#15803d":"#e5e7eb",borderColor:y==="allow"?"#15803d":"#9ca3af"},"&.Mui-selected":{backgroundColor:"#16a34a",color:"#ffffff","&:hover":{backgroundColor:"#15803d"}}},children:[D(Yt,{sx:{fontSize:16,mr:.5}}),n("modules.form.publicPolicies.fields.conditions.states.allow")]}),D(mr,{value:"owner_allow",onClick:()=>b(p,"owner_allow"),disabled:i,sx:{px:2,color:y==="owner_allow"?"#ffffff":"#6b7280",backgroundColor:y==="owner_allow"?"#0ea5e9":"#f3f4f6",borderColor:y==="owner_allow"?"#0ea5e9":"#d1d5db","&:hover":{backgroundColor:y==="owner_allow"?"#0284c7":"#e5e7eb",borderColor:y==="owner_allow"?"#0284c7":"#9ca3af"},"&.Mui-selected":{backgroundColor:"#0ea5e9",color:"#ffffff","&:hover":{backgroundColor:"#0284c7"}}},children:n("modules.form.publicPolicies.fields.conditions.states.ownerAllow")}),fe(mr,{value:"deny",onClick:()=>b(p,"deny"),disabled:i,sx:{px:2,color:y==="deny"?"#ffffff":"#6b7280",backgroundColor:y==="deny"?"#dc2626":"#f3f4f6",borderColor:y==="deny"?"#dc2626":"#d1d5db","&:hover":{backgroundColor:y==="deny"?"#b91c1c":"#e5e7eb",borderColor:y==="deny"?"#b91c1c":"#9ca3af"},"&.Mui-selected":{backgroundColor:"#dc2626",color:"#ffffff","&:hover":{backgroundColor:"#b91c1c"}}},children:[D(Xt,{sx:{fontSize:16,mr:.5}}),n("modules.form.publicPolicies.fields.conditions.states.deny")]})]})]},p)})})]}),t&&D(ho,{error:!0,sx:{mt:1},children:t})]})},pr=Zt;import{jsx as z,jsxs as j}from"react/jsx-runtime";var mn=en(({policy:e,onChange:r,onRemove:o,availableFields:t,isSubmitting:i=!1,usedActions:n,error:s},l)=>{let{t:c}=rn(),w=new Set(Array.from(n||[]));w.delete(e.action);let d=uo.map(h=>({value:h,label:c(`modules.form.publicPolicies.fields.action.options.${h}`)}));return j(bo,{ref:l,sx:{p:3,border:"1px solid #d1d9e0",borderRadius:2,position:"relative",backgroundColor:"#ffffff"},children:[j(Pe,{sx:{display:"flex",justifyContent:"space-between",alignItems:"flex-start",mb:3},children:[z(Ae,{variant:"subtitle1",sx:{fontWeight:600,color:"#111418",fontSize:"1rem"},children:c("modules.form.publicPolicies.policyTitle")}),z(an,{onClick:o,size:"small",disabled:i,"aria-label":c("modules.form.publicPolicies.removePolicy"),sx:{color:"#656d76","&:hover":{color:"#cf222e",backgroundColor:"rgba(207, 34, 46, 0.1)"}},children:z(dn,{})})]}),j(Xe,{spacing:1,children:[z(Xe,{direction:{xs:"column",md:"row"},spacing:2,children:z(Pe,{sx:{flex:1,minWidth:200},children:j(on,{fullWidth:!0,children:[z(tn,{children:c("modules.form.publicPolicies.fields.action.label")}),z(nn,{value:e.action,label:c("modules.form.publicPolicies.fields.action.label"),disabled:i,onChange:h=>{let g=h.target.value,a={...e,action:g};g==="delete"?(a.permission="deny",delete a.fields):(a.fields={allow:[],owner_allow:[],deny:t},delete a.permission),r(a)},sx:{backgroundColor:"#ffffff","&:hover .MuiOutlinedInput-notchedOutline":{borderColor:"#8c959f"},"&.Mui-focused .MuiOutlinedInput-notchedOutline":{borderColor:"#0969da",borderWidth:2}},children:d.map(h=>{let g=w.has(h.value);return z(sn,{value:h.value,disabled:g,children:h.label},h.value)})}),s&&z(ln,{error:!0,children:s})]})})}),e.action==="delete"?j(Pe,{children:[z(Ae,{variant:"body2",color:"text.secondary",sx:{mb:2},children:c("modules.form.publicPolicies.fields.conditions.label")}),j(Xe,{direction:"row",spacing:1,sx:{mb:1},children:[z(fr,{variant:e.permission==="*"?"contained":"outlined",startIcon:z(un,{}),onClick:()=>r({...e,permission:"*"}),disabled:i,size:"small",sx:{minWidth:140,whiteSpace:"nowrap",...e.permission==="*"&&{backgroundColor:"#16a34a","&:hover":{backgroundColor:"#15803d"}}},children:c("modules.form.publicPolicies.fields.conditions.allFields")}),z(fr,{variant:e.permission==="owner"?"contained":"outlined",onClick:()=>r({...e,permission:"owner"}),disabled:i,size:"small",sx:{minWidth:140,whiteSpace:"nowrap",...e.permission==="owner"&&{backgroundColor:"#0ea5e9","&:hover":{backgroundColor:"#0284c7"}}},children:c("modules.form.publicPolicies.fields.conditions.states.ownerAllow")}),z(fr,{variant:e.permission==="deny"?"contained":"outlined",startIcon:z(gn,{}),onClick:()=>r({...e,permission:"deny"}),disabled:i,size:"small",sx:{minWidth:140,whiteSpace:"nowrap",...e.permission==="deny"&&{backgroundColor:"#cf222e","&:hover":{backgroundColor:"#bc1f2c"}}},children:c("modules.form.publicPolicies.fields.conditions.noFields")})]})]}):z(pr,{value:e.fields||{allow:[],owner_allow:[],deny:[]},onChange:h=>r({...e,fields:h}),availableFields:t,disabled:i}),z(bo,{variant:"outlined",sx:{p:2,backgroundColor:"#f9fafb"},children:e.action==="delete"?j(Ae,{variant:"body2",sx:{fontFamily:"monospace",color:"text.secondary"},children:[j(Pe,{component:"span",sx:{color:e.permission==="*"?"#16a34a":e.permission==="owner"?"#0ea5e9":"#dc2626"},children:[c("modules.form.publicPolicies.fields.conditions.states.allow"),":"]})," ",e.permission||"-"]}):j(Xe,{spacing:.5,divider:z(cn,{sx:{borderColor:"#e5e7eb"}}),children:[j(Ae,{variant:"body2",sx:{fontFamily:"monospace",color:"text.secondary"},children:[j(Pe,{component:"span",sx:{color:"#16a34a"},children:[c("modules.form.publicPolicies.fields.conditions.states.allow"),":"]})," ",(e?.fields?.allow||[]).join(", ")||"-"]}),j(Ae,{variant:"body2",sx:{fontFamily:"monospace",color:"text.secondary"},children:[j(Pe,{component:"span",sx:{color:"#0ea5e9"},children:[c("modules.form.publicPolicies.fields.conditions.states.ownerAllow"),":"]})," ",(e?.fields?.owner_allow||[]).join(", ")||"-"]}),j(Ae,{variant:"body2",sx:{fontFamily:"monospace",color:"text.secondary"},children:[j(Pe,{component:"span",sx:{color:"#dc2626"},children:[c("modules.form.publicPolicies.fields.conditions.states.deny"),":"]})," ",(e?.fields?.deny||[]).join(", ")||"-"]})]})})]})]})}),yr=mn;import{Fragment as Pn,jsx as ie,jsxs as Qe}from"react/jsx-runtime";var xn=()=>{let e=globalThis?.crypto;return e&&typeof e.randomUUID=="function"?e.randomUUID():`${Date.now()}-${Math.random().toString(16).slice(2)}`},Cn=({policies:e,onChange:r,availableFields:o,errors:t,isSubmitting:i=!1})=>{let{t:n}=fn(),s=pn({}),l=new Set((e||[]).map(u=>u.action).filter(Boolean)),c=go.filter(u=>!l.has(u)),w=c.length>0,d=()=>{let u=c[0]||"create",b={id:xn(),action:u};u==="delete"?b.permission="deny":b.fields={allow:[],owner_allow:[],deny:o};let p=[...e||[],b];r(p),setTimeout(()=>{let y=p.length-1,m=s.current[y];m&&m.scrollIntoView({behavior:"smooth",block:"center"})},100)},h=u=>{let b=[...e];b.splice(u,1),r(b)},g=(()=>{if(!t)return null;if(typeof t=="string")return t;let u=t._error;return typeof u=="string"?u:null})(),a=new Set((e||[]).map(u=>u.action));return Qe(Pn,{children:[ie(bn,{sx:{borderColor:"#e0e4e7"}}),Qe(Je,{children:[ie(Je,{display:"flex",justifyContent:"space-between",alignItems:"center",mb:3,children:Qe(Je,{children:[ie(wo,{variant:"h6",sx:{fontWeight:600,color:"#111418",mb:1},children:n("modules.form.publicPolicies.title")}),ie(wo,{variant:"body2",color:"text.secondary",sx:{fontSize:"0.875rem"},children:n("modules.form.publicPolicies.description")})]})}),g&&ie(xo,{severity:"error",sx:{mb:3},children:g}),Qe(hn,{spacing:3,children:[(e||[]).length===0?ie(xo,{severity:"info",children:n("modules.form.publicPolicies.noPolicies")}):e.map((u,b)=>ie(yr,{ref:p=>{s.current[b]=p},policy:u,onChange:p=>{let y=[...e];y[b]=p,r(y)},onRemove:()=>h(b),availableFields:o,isSubmitting:i,usedActions:a,error:typeof t=="object"&&t&&u.id in t?t[u.id]:void 0},u.id)),w&&ie(Je,{children:ie(yn,{type:"button",variant:"outlined",startIcon:ie(wn,{}),onClick:d,disabled:i,sx:{borderColor:"#d0d7de",color:"#656d76","&:hover":{borderColor:"#8c959f",backgroundColor:"transparent"}},children:n("modules.form.publicPolicies.addPolicy")})})]})]})]})},wa=Cn;import{useState as hr}from"react";import{Button as Ze,TextField as Co,Box as Fe,Alert as Ue,Typography as ye,CircularProgress as br}from"@mui/material";import{jsx as N,jsxs as de}from"react/jsx-runtime";function Ra(){let[e,r]=hr(""),[o,t]=hr(""),[i,n]=hr(!1),{isAuthenticated:s,isLoading:l,error:c,login:w,logout:d,refreshTokens:h,clearError:g,isExpiringSoon:a,expiresIn:u}=ge(),b=async m=>{if(m.preventDefault(),!e||!o)return;(await w(e,o)).success&&(r(""),t(""),n(!1))},p=async()=>{await d()},y=async()=>{await h()};return s?de(Fe,{sx:{maxWidth:600,mx:"auto",p:3},children:[N(ye,{variant:"h4",gutterBottom:!0,children:"Welcome! \u{1F389}"}),N(Ue,{severity:"success",sx:{mb:3},children:"You are successfully logged in with Refresh Token Pattern enabled"}),de(Fe,{sx:{mb:3,p:2,bgcolor:"background.paper",border:1,borderColor:"divider",borderRadius:1},children:[N(ye,{variant:"h6",gutterBottom:!0,children:"Token Status"}),de(ye,{variant:"body2",color:"text.secondary",children:["Access Token expires in: ",Math.round(u/1e3/60)," minutes"]}),a&&N(Ue,{severity:"warning",sx:{mt:1},children:"Token expires soon - automatic refresh will happen"})]}),de(Fe,{sx:{display:"flex",gap:2,flexWrap:"wrap"},children:[N(Ze,{variant:"contained",onClick:y,disabled:l,startIcon:l?N(br,{size:16}):null,children:"Refresh Tokens"}),N(Ze,{variant:"outlined",color:"error",onClick:p,disabled:l,children:"Logout"})]}),c&&N(Ue,{severity:"error",sx:{mt:2},onClose:g,children:c})]}):de(Fe,{sx:{maxWidth:400,mx:"auto",p:3},children:[N(ye,{variant:"h4",gutterBottom:!0,align:"center",children:"Login with Refresh Tokens"}),N(Ue,{severity:"info",sx:{mb:3},children:"This demo shows the new Refresh Token Pattern with automatic session management"}),i?de("form",{onSubmit:b,children:[N(Co,{fullWidth:!0,label:"Email",type:"email",value:e,onChange:m=>r(m.target.value),margin:"normal",required:!0,autoComplete:"email"}),N(Co,{fullWidth:!0,label:"Password",type:"password",value:o,onChange:m=>t(m.target.value),margin:"normal",required:!0,autoComplete:"current-password"}),N(Ze,{type:"submit",fullWidth:!0,variant:"contained",size:"large",disabled:l,startIcon:l?N(br,{size:16}):null,sx:{mt:3,mb:2},children:l?"Logging in...":"Login"})]}):N(Ze,{fullWidth:!0,variant:"contained",size:"large",onClick:()=>n(!0),sx:{mt:2},children:"Show Login Form"}),c&&N(Ue,{severity:"error",sx:{mt:2},onClose:g,children:c})]})}function Ia(){let{isAuthenticated:e,isLoading:r,isExpiringSoon:o,expiresIn:t}=ge();return r?de(Fe,{sx:{display:"flex",alignItems:"center",gap:1},children:[N(br,{size:16}),N(ye,{variant:"caption",children:"Loading session..."})]}):e?de(Fe,{children:[N(ye,{variant:"caption",color:"success.main",children:"\u2713 Authenticated"}),o&&de(ye,{variant:"caption",color:"warning.main",display:"block",children:["\u26A0 Token expires in ",Math.round(t/1e3/60)," min"]})]}):N(ye,{variant:"caption",color:"text.secondary",children:"Not logged in"})}import vn from"@mui/material/TextField";import Tn from"@mui/material/CircularProgress";import Po from"@mui/material/InputAdornment";import En from"@mui/material/IconButton";import Rn from"@mui/icons-material/Refresh";import{jsx as he}from"react/jsx-runtime";var In=e=>e.replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,"").replace(/javascript:/gi,"").replace(/on\w+\s*=/gi,"").replace(/<iframe\b[^<]*(?:(?!<\/iframe>)<[^<]*)*<\/iframe>/gi,""),Sn=({html:e})=>he("span",{dangerouslySetInnerHTML:{__html:In(e)}}),Na=({config:e,value:r,onChange:o,label:t,error:i=!1,helperText:n,readOnly:s=!1,disabled:l=!1})=>{let{value:c,loading:w,error:d,regenerate:h}=Sr(e,{autoFetch:!r,onSuccess:y=>{o?.(y)}}),g=r||c,a=i||!!d,u=d||n,b=a&&u&&(u.toLowerCase().includes("duplicate")||u.toLowerCase().includes("duplicado")||u.toLowerCase().includes("duplicada")||u.toLowerCase().includes("unique")||u.toLowerCase().includes("\xFAnico")||u.toLowerCase().includes("unico")||u.toLowerCase().includes("\xFAnica")||u.toLowerCase().includes("unica")||u.toLowerCase().includes("already exists")||u.toLowerCase().includes("ya existe")||u.toLowerCase().includes("e11000"));return he(vn,{label:t,fullWidth:!0,value:g,error:a,helperText:u?he(Sn,{html:u}):" ",disabled:l,InputProps:{readOnly:!0,startAdornment:w?he(Po,{position:"start",children:he(Tn,{size:20})}):void 0,endAdornment:b&&!w?he(Po,{position:"end",children:he(En,{edge:"end",onClick:async()=>{!l&&!w&&await h()},disabled:l,size:"small",color:"error","aria-label":"regenerar c\xF3digo",title:"Regenerar c\xF3digo",children:he(Rn,{})})}):void 0}})};import vo,{useCallback as Me,useRef as To,useState as Ro}from"react";import ve from"@mui/material/Box";import Te from"@mui/material/Typography";import Eo from"@mui/material/IconButton";import kn from"@mui/material/LinearProgress";import wr from"@mui/material/CircularProgress";import Ln from"@mui/material/Chip";import An from"@mui/material/Paper";import Fn from"@mui/material/List";import _n from"@mui/material/ListItem";import On from"@mui/material/ListItemText";import Bn from"@mui/material/ListItemSecondaryAction";import Nn from"@mui/material/FormHelperText";import Dn from"@mui/icons-material/CloudUpload";import zn from"@mui/icons-material/InsertDriveFile";import Un from"@mui/icons-material/Image";import Mn from"@mui/icons-material/PictureAsPdf";import Vn from"@mui/icons-material/Delete";import Wn from"@mui/icons-material/Refresh";import Hn from"@mui/icons-material/CheckCircle";import qn from"@mui/icons-material/Error";import al from"@mui/icons-material/BrokenImage";import{jsx as E,jsxs as be}from"react/jsx-runtime";var Io=e=>{if(e===0)return"0 B";let r=1024,o=["B","KB","MB","GB"],t=Math.floor(Math.log(e)/Math.log(r));return`${parseFloat((e/Math.pow(r,t)).toFixed(1))} ${o[t]}`},jn=e=>e.startsWith("image/")?E(Un,{color:"primary"}):e==="application/pdf"?E(Mn,{color:"error"}):E(zn,{color:"action"}),$n=e=>{switch(e){case"completed":return E(Hn,{color:"success",fontSize:"small"});case"error":return E(qn,{color:"error",fontSize:"small"});case"uploading":case"pending":return E(wr,{size:16});case"removing":return E(wr,{size:16,color:"error"});default:return null}},Kn=({file:e,baseUrl:r,disabled:o,onRemove:t,onRetry:i})=>{let[n,s]=Ro(!1),l=!o&&e.status!=="uploading"&&e.status!=="removing",c=!o&&e.status==="error"&&e.file,w=e.contentType.startsWith("image/"),d=e.visibility==="public"||e.filePath?.startsWith("public/")||e.filePath?.startsWith(r),g=!e.filePath||!d?null:e.filePath.startsWith("http://")||e.filePath.startsWith("https://")||e.filePath.startsWith(r)?e.filePath:`${r}${e.filePath}`,a=e.status==="completed"&&g,u=()=>w&&a&&!n?E(ve,{component:a?"a":"div",href:g||void 0,target:"_blank",rel:"noopener noreferrer",sx:{width:48,height:48,borderRadius:1,overflow:"hidden",display:"flex",alignItems:"center",justifyContent:"center",bgcolor:"grey.100",border:"1px solid",borderColor:"divider",cursor:a?"pointer":"default",transition:"all 0.2s ease",flexShrink:0,"&:hover":a?{borderColor:"primary.main",transform:"scale(1.05)"}:{}},children:E("img",{src:g,alt:e.name,style:{width:"100%",height:"100%",objectFit:"cover"},onError:()=>s(!0)})}):E(ve,{component:a?"a":"div",href:g||void 0,target:"_blank",rel:"noopener noreferrer",sx:{width:48,height:48,borderRadius:1,display:"flex",alignItems:"center",justifyContent:"center",bgcolor:"grey.50",border:"1px solid",borderColor:"divider",cursor:a?"pointer":"default",transition:"all 0.2s ease",flexShrink:0,textDecoration:"none","&:hover":a?{borderColor:"primary.main",bgcolor:"action.hover"}:{}},children:jn(e.contentType)});return be(_n,{sx:{borderRadius:1,mb:.5,bgcolor:e.status==="error"?"error.lighter":"background.paper",border:"1px solid",borderColor:e.status==="error"?"error.light":"divider",gap:1.5},children:[u(),E(On,{primary:be(ve,{sx:{display:"flex",alignItems:"center",gap:1},children:[E(Te,{variant:"body2",noWrap:!0,sx:{maxWidth:200,overflow:"hidden",textOverflow:"ellipsis"},children:e.name}),$n(e.status)]}),secondary:be(ve,{children:[e.size>0&&E(Te,{variant:"caption",color:"text.secondary",children:Io(e.size)}),e.status==="uploading"&&E(kn,{variant:"determinate",value:e.progress,sx:{mt:.5,height:4,borderRadius:2}}),e.status==="error"&&e.errorMessage&&E(Te,{variant:"caption",color:"error",display:"block",children:e.errorMessage}),a&&E(Te,{variant:"caption",color:"primary",display:"block",children:w?"Click thumbnail to view":"Click to download"})]})}),be(Bn,{children:[c&&E(Eo,{edge:"end",size:"small",onClick:()=>i(e.id),color:"primary",title:"Retry",children:E(Wn,{fontSize:"small"})}),l&&E(Eo,{edge:"end",size:"small",onClick:()=>t(e.id),color:"error",title:"Delete",children:E(Vn,{fontSize:"small"})})]})]})};var cl=({label:e,accept:r,maxFileSize:o=10*1024*1024,multiple:t=!1,maxFiles:i,minFiles:n=0,required:s=!1,disabled:l=!1,error:c=!1,helperText:w,onChange:d,onValidation:h,initialFiles:g,placeholder:a,showFileList:u=!0,visibility:b="private",showPreview:p=!0,baseUrl:y})=>{let m=To(null),[C,R]=Ro(!1),M=t?i:1,x=s?Math.max(n,1):n,f={acceptedTypes:r,maxFileSize:o,maxFiles:M,minFiles:x,visibility:b,onFilesChange:k=>{let ee=k.filter(xe=>xe.status==="completed"&&xe.filePath).map(xe=>{let Re=xe.filePath;return Re.startsWith(y)||Re.startsWith("http://")||Re.startsWith("https://")?Re:y?`${y}${Re}`:Re});d?.(ee)}},{files:P,isUploading:L,addFiles:_,removeFile:ae,retryUpload:we,isValid:te,validationError:ue,initializeFiles:A,isTouched:V,markAsTouched:F,getPreviewUrl:Ee}=kr(f),I=To(!1);vo.useEffect(()=>{g&&g.length>0&&!I.current&&(I.current=!0,A(g))},[g,A]),vo.useEffect(()=>{h?.(te,ue)},[te,ue,h]);let H=Me(k=>{F();let ee=k.target.files;ee&&ee.length>0&&_(ee),m.current&&(m.current.value="")},[_,F]),v=Me(()=>{l||(F(),m.current?.click())},[l,F]),S=Me(k=>{k.preventDefault(),k.stopPropagation(),l||R(!0)},[l]),O=Me(k=>{k.preventDefault(),k.stopPropagation(),R(!1)},[]),q=Me(k=>{if(k.preventDefault(),k.stopPropagation(),R(!1),l)return;F();let ee=k.dataTransfer.files;ee&&ee.length>0&&_(ee)},[l,_,F]),G=r?.join(",")||"",Y=!l&&(t||P.length===0),le=c||V&&!te,Cr=w||(V?ue:null);return be(ve,{sx:{width:"100%"},children:[e&&be(Te,{variant:"body2",sx:{mb:1,fontWeight:500,color:le?"error.main":"text.primary"},children:[e,s&&E("span",{style:{color:"red"},children:" *"})]}),E("input",{ref:m,type:"file",accept:G,multiple:t,onChange:H,disabled:l,style:{display:"none"}}),Y&&be(An,{variant:"outlined",onClick:v,onDragOver:S,onDragLeave:O,onDrop:q,sx:{p:3,textAlign:"center",cursor:l?"not-allowed":"pointer",borderStyle:"dashed",borderWidth:2,borderColor:C?"primary.main":le?"error.main":"divider",bgcolor:C?"primary.lighter":l?"action.disabledBackground":"background.paper",transition:"all 0.2s ease","&:hover":l?{}:{borderColor:"primary.main",bgcolor:"action.hover"}},children:[E(Dn,{sx:{fontSize:48,color:C?"primary.main":l?"action.disabled":"action.active",mb:1}}),E(Te,{variant:"body2",color:l?"text.disabled":"text.secondary",children:(()=>{if(a)return a;let k=[];if(C)return"Drop file here";if(k.push("Drag files here or click to select"),r&&r.length>0){let ee=r.map(xe=>xe.split("/")[1]?.toUpperCase()||xe).join(", ");k.push(`Allowed types: ${ee}`)}return o&&k.push(`Max ${Io(o)} per file`),M!==void 0&&t&&k.push(`Max ${M} files`),k[0]})()}),r&&r.length>0&&!C&&E(ve,{sx:{mt:1,display:"flex",gap:.5,justifyContent:"center",flexWrap:"wrap"},children:r.map(k=>E(Ln,{label:k.split("/")[1]?.toUpperCase()||k,size:"small",variant:"outlined",sx:{fontSize:"0.7rem"}},k))})]}),u&&P.length>0&&E(Fn,{dense:!0,sx:{mt:1,p:0},children:P.map(k=>E(Kn,{file:k,baseUrl:y,disabled:l,onRemove:ae,onRetry:we},k.id))}),L&&be(ve,{sx:{display:"flex",alignItems:"center",gap:1,mt:1},children:[E(wr,{size:16}),E(Te,{variant:"caption",color:"text.secondary",children:"Uploading files..."})]}),Cr&&E(Nn,{error:le,sx:{mt:.5},children:Cr})]})};import{useCallback as Gn,useRef as Yn,useEffect as Xn}from"react";import So from"@mui/material/Box";import ko from"@mui/material/Typography";import Lo from"@mui/material/FormHelperText";import{MDXEditor as Jn,headingsPlugin as Qn,listsPlugin as Zn,quotePlugin as es,thematicBreakPlugin as rs,markdownShortcutPlugin as os,linkPlugin as ts,linkDialogPlugin as ns,tablePlugin as ss,toolbarPlugin as is,UndoRedo as as,BoldItalicUnderlineToggles as ls,BlockTypeSelect as cs,CreateLink as ds,InsertTable as us,ListsToggle as gs,Separator as er}from"@mdxeditor/editor";import"@mdxeditor/editor/style.css";import{Fragment as ms,jsx as $,jsxs as xr}from"react/jsx-runtime";var wl=({label:e,value:r="",onChange:o,required:t=!1,disabled:i=!1,error:n=!1,helperText:s,placeholder:l="Escribe aqu\xED...",minHeight:c=200,maxHeight:w=500})=>{let d=Yn(null);Xn(()=>{d.current&&d.current.getMarkdown()!==r&&d.current.setMarkdown(r||"")},[r]);let h=Gn(g=>{o?.(g)},[o]);return xr(So,{sx:{width:"100%"},children:[e&&xr(ko,{component:"label",sx:{display:"block",mb:.5,fontSize:"0.875rem",fontWeight:500,color:n?"error.main":"text.primary"},children:[e,t&&$(ko,{component:"span",color:"error.main",sx:{ml:.5},children:"*"})]}),$(So,{sx:{border:1,borderColor:n?"error.main":"divider",borderRadius:1,overflow:"hidden",opacity:i?.6:1,pointerEvents:i?"none":"auto","& .mdxeditor":{minHeight:c,maxHeight:w,overflow:"auto"},"& .mdxeditor-toolbar":{borderBottom:1,borderColor:"divider",backgroundColor:"background.default"},"& .mdxeditor-root-contenteditable":{padding:2,minHeight:c-50}},children:$(Jn,{ref:d,markdown:r||"",onChange:h,placeholder:l,readOnly:i,plugins:[Qn(),Zn(),es(),rs(),os(),ts(),ns(),ss(),is({toolbarContents:()=>xr(ms,{children:[$(as,{}),$(er,{}),$(ls,{}),$(er,{}),$(cs,{}),$(er,{}),$(gs,{}),$(er,{}),$(ds,{}),$(us,{})]})})]})}),s&&$(Lo,{error:n,sx:{mx:0,mt:.5},children:s}),!s&&$(Lo,{sx:{mx:0,mt:.5},children:"\xA0"})]})};export{ce as a,fs as b,ys as c,rr as d,We as e,Rs as f,Nr as g,Bi as h,Ht as i,uo as j,go as k,wa as l,Ra as m,Ia as n,Na as o,cl as p,wl as q};
|
|
1
|
+
import{b as Tr,c as ne,h as Rr,j as ge,l as Ir,m as Sr,p as kr}from"./chunk-5PKTOZAY.mjs";import{g as K}from"./chunk-BJ6PIVZR.mjs";import{a as Pr,b as vr,g as Er}from"./chunk-6GPSBDW6.mjs";var ce={es:{"checkCode.codeLabel":"C\xF3digo de Verificaci\xF3n","checkCode.codePlaceholder":"Ingresa el c\xF3digo de 6 d\xEDgitos","checkCode.codeRequired":"El c\xF3digo es obligatorio","checkCode.emailLabel":"Correo Electr\xF3nico","checkCode.emailPlaceholder":"Ingresa tu correo electr\xF3nico","checkCode.emailRequired":"El correo electr\xF3nico es obligatorio","checkCode.instructions":"Ingresa el c\xF3digo de 6 d\xEDgitos que enviamos a tu correo electr\xF3nico.","checkCode.invalidEmail":"Ingresa un correo electr\xF3nico v\xE1lido","checkCode.resendCodeLink":"Reenviar c\xF3digo","checkCode.title":"Verificar C\xF3digo","checkCode.verifyButton":"Verificar C\xF3digo","common.back":"Volver","common.backToLogin":"Volver","error.app.config":"Error de Configuraci\xF3n: {{message}}","error.app.initialization":"Error durante la inicializaci\xF3n final de la aplicaci\xF3n.","error.transaction":"Error en la operaci\xF3n","error.unknown":"Ocurri\xF3 un error desconocido.","errors.DUPLICATE":"El campo <b>{{field}}</b> debe ser \xFAnico.","errors.FOREIGN_KEY_NOT_FOUND":"El campo <b>{{field}}</b> debe referenciar un \xEDtem existente.","errors.INVALID_EMAIL":"El campo <b>{{field}}</b> debe ser un correo electr\xF3nico v\xE1lido.","errors.INVALID_OBJECT_ID":"El campo <b>{{field}}</b> debe ser un valor v\xE1lido.","errors.IN_USE":"El \xEDtem est\xE1 en uso y no puede ser eliminado.","errors.MAX_LENGTH":"El campo <b>{{field}}</b> no debe exceder los <b>{{length}}</b> caracteres.","errors.MIN_LENGTH":"El campo <b>{{field}}</b> debe tener al menos <b>{{length}}</b> caracteres.","errors.MUST_NOT_BE_EMAIL":"El campo <b>{{field}}</b> no debe ser un correo electr\xF3nico.","errors.NO_PERMISSION":"No tienes permiso para realizar esta acci\xF3n.","errors.NO_SPACES":"El campo <b>{{field}}</b> no debe contener espacios.","errors.ONE_OR_MORE_OPERATIONS_FAILED":"Error en la operaci\xF3n","errors.REQUIRED":"El campo <b>{{field}}</b> es obligatorio.","errors.TOKEN_HAS_EXPIRED":"La sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente.","errors.TOO_MANY_REQUESTS":"L\xEDmite de solicitudes alcanzado. Por favor intenta m\xE1s tarde.","errors.UNAUTHORIZED":"No est\xE1s autorizado para realizar esta acci\xF3n.","errors.all_password_fields_required":"Todos los campos de contrase\xF1a son obligatorios","errors.auth.INVALID_API_KEY":"Clave de API inv\xE1lida","errors.auth.INVALID_CREDENTIALS":"Usuario y/o contrase\xF1a incorrectos","errors.auth.NO_PERMISSION":"No tienes permisos suficientes","errors.auth.SESSION_EXPIRED":"Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente.","errors.auth.TOO_MANY_REQUESTS":"Demasiados intentos. Por favor espera 15 minutos e intenta nuevamente","errors.auth.UNAUTHORIZED":"No tienes permisos para realizar esta acci\xF3n","errors.auth.USER_NOT_ACTIVE":"Usuario no activo","errors.auth.USER_NOT_FOUND":"Usuario no encontrado","errors.data.BAD_REQUEST":"Solicitud inv\xE1lida","errors.data.FIELD_ERROR":"Error en los datos ingresados","errors.data.IN_USE":"El elemento est\xE1 en uso y no puede ser eliminado","errors.data.ITEM_NOT_FOUND":"El elemento solicitado no fue encontrado","errors.data.NOT_FOUND":"No se encontr\xF3 lo solicitado","errors.internal_error_changing_password":"Error interno al cambiar la contrase\xF1a. Intenta nuevamente","errors.password_min_length":"La contrase\xF1a debe tener al menos 8 caracteres","errors.password_mismatch":"Las contrase\xF1as no coinciden","errors.password_must_be_different":"La nueva contrase\xF1a debe ser diferente a la actual","errors.system.DATABASE_CONNECTION_ERROR":"Error de conexi\xF3n. Verifica tu conexi\xF3n a internet.","errors.system.INTERNAL_SERVER_ERROR":"Error interno del servidor. Intenta nuevamente.","errors.system.INVALID_CONFIGURATION":"Error de configuraci\xF3n del sistema","errors.system.TOO_MANY_REQUESTS":"Demasiadas solicitudes. Por favor espera un momento e intenta nuevamente","errors.system.UNKNOWN_OPERATION":"Operaci\xF3n no reconocida","errors.users_module_not_configured":"M\xF3dulo de usuarios no configurado","footer.copyright":"Nocios S.R.L. Todos los derechos reservados.","footer.version":"Versi\xF3n","forgotPassword.checkEmailInstructions":"Revisa tu bandeja de entrada para el c\xF3digo de verificaci\xF3n","forgotPassword.codeAlreadyExistsMessage":"Ya se envi\xF3 un c\xF3digo y a\xFAn es v\xE1lido","forgotPassword.emailLabel":"Correo Electr\xF3nico","forgotPassword.emailPlaceholder":"Ingresa tu correo electr\xF3nico","forgotPassword.emailRequired":"El correo electr\xF3nico es obligatorio","forgotPassword.emailSentMessage":"C\xF3digo enviado exitosamente","forgotPassword.enterCodeLink":"Ingresar C\xF3digo","forgotPassword.instructions":"Ingresa tu correo electr\xF3nico y te enviaremos un c\xF3digo para restablecer tu contrase\xF1a.","forgotPassword.invalidEmail":"Ingresa un correo electr\xF3nico v\xE1lido","forgotPassword.sendCodeButton":"Enviar C\xF3digo","forgotPassword.title":"Recuperar Contrase\xF1a","loading.app.configInitial":"Cargando configuraci\xF3n inicial...","loading.app.generic":"Cargando...","loading.app.starting":"Iniciando aplicaci\xF3n...","loading.app.themeSetup":"Generando tema...","loading.app.validatingSession":"Validando sesi\xF3n...","login.alreadyHaveCodeLink":"\xBFYa tienes un c\xF3digo?","login.forgotPasswordLink":"\xBFOlvidaste tu contrase\xF1a?","login.initializationError":"Error de inicializaci\xF3n","login.initializing":"Inicializando...","login.loginButton":"Iniciar Sesi\xF3n","login.logoAlt":"Logotipo","login.noAccountPrompt":"\xBFNo tienes una cuenta?","login.notInitialized":"Sistema no inicializado","login.passwordLabel":"Contrase\xF1a","login.passwordPlaceholder":"Ingresa tu contrase\xF1a","login.passwordRequired":"Contrase\xF1a es obligatoria","login.signUpLink":"Reg\xEDstrate","login.usernameOrEmailLabel":"Correo Electr\xF3nico","login.usernameOrEmailPlaceholder":"Ingresa tu correo electr\xF3nico","login.usernameRequired":"Correo electr\xF3nico es obligatorio","resetPassword.codeExpiredOrInvalid":"El c\xF3digo ha expirado o es inv\xE1lido","resetPassword.confirmPasswordLabel":"Confirmar Contrase\xF1a","resetPassword.confirmPasswordPlaceholder":"Confirma tu nueva contrase\xF1a","resetPassword.confirmPasswordRequired":"Confirma tu contrase\xF1a","resetPassword.goToLoginButton":"Ir al Login","resetPassword.instructions":"Ingresa tu nueva contrase\xF1a.","resetPassword.invalidCode":"El c\xF3digo de verificaci\xF3n es inv\xE1lido. Por favor, verifica el enlace o solicita uno nuevo.","resetPassword.missingParameters":"Faltan par\xE1metros obligatorios","resetPassword.newPasswordLabel":"Nueva Contrase\xF1a","resetPassword.newPasswordPlaceholder":"Ingresa tu nueva contrase\xF1a","resetPassword.newPasswordRequired":"La nueva contrase\xF1a es obligatoria","resetPassword.passwordTooShort":"La contrase\xF1a debe tener al menos 8 caracteres","resetPassword.passwordsDoNotMatch":"Las contrase\xF1as no coinciden","resetPassword.requestNewCodeButton":"Solicitar Nuevo C\xF3digo","resetPassword.resetPasswordButton":"Restablecer Contrase\xF1a","resetPassword.successInstructions":"Ahora puedes iniciar sesi\xF3n con tu nueva contrase\xF1a","resetPassword.successMessage":"Contrase\xF1a restablecida exitosamente","resetPassword.title":"Nueva Contrase\xF1a","resetPassword.validatingCode":"Validando c\xF3digo...","modules.form.publicPolicies.fields.conditions.customEdit":"Edici\xF3n personalizada"},en:{"checkCode.codeLabel":"Verification Code","checkCode.codePlaceholder":"Enter 6-digit code","checkCode.codeRequired":"Code is required","checkCode.emailLabel":"Email Address","checkCode.emailPlaceholder":"Enter your email address","checkCode.emailRequired":"Email address is required","checkCode.instructions":"Enter the 6-digit code we sent to your email address.","checkCode.invalidEmail":"Enter a valid email address","checkCode.resendCodeLink":"Resend code","checkCode.title":"Verify Code","checkCode.verifyButton":"Verify Code","common.back":"Back","common.backToLogin":"Back to Login","error.app.config":"Configuration Error: {{message}}","error.app.initialization":"Error during final application initialization.","error.transaction":"Operation error","error.unknown":"An unknown error occurred.","errors.DUPLICATE":"The field <b>{{field}}</b> must be unique.","errors.FOREIGN_KEY_NOT_FOUND":"The field <b>{{field}}</b> must reference an existing item.","errors.INVALID_EMAIL":"The field <b>{{field}}</b> must be a valid email address.","errors.INVALID_OBJECT_ID":"The field <b>{{field}}</b> must be a valid value.","errors.IN_USE":"The item is currently in use and cannot be deleted.","errors.MAX_LENGTH":"The field <b>{{field}}</b> must not exceed <b>{{maxLength}}</b> characters.","errors.MIN_LENGTH":"The field <b>{{field}}</b> must have at least <b>{{minLength}}</b> characters.","errors.MUST_NOT_BE_EMAIL":"The field <b>{{field}}</b> must not be an email address.","errors.NO_PERMISSION":"You do not have permission to perform this action.","errors.NO_SPACES":"The field <b>{{field}}</b> must not contain spaces.","errors.ONE_OR_MORE_OPERATIONS_FAILED":"Operation error","errors.REQUIRED":"The field <b>{{field}}</b> is required.","errors.TOKEN_HAS_EXPIRED":"Your session has expired, please log in again.","errors.TOO_MANY_REQUESTS":"Request limit reached. Please try again later.","errors.UNAUTHORIZED":"You are not authorized to perform this action.","errors.all_password_fields_required":"All password fields are required","errors.auth.INVALID_API_KEY":"Invalid API key","errors.auth.INVALID_CREDENTIALS":"Incorrect username and/or password","errors.auth.NO_PERMISSION":"Insufficient permissions","errors.auth.SESSION_EXPIRED":"Your session has expired. Please log in again.","errors.auth.TOO_MANY_REQUESTS":"Too many attempts. Please wait 15 minutes and try again","errors.auth.UNAUTHORIZED":"You don't have permission to perform this action","errors.auth.USER_NOT_ACTIVE":"User account is not active","errors.auth.USER_NOT_FOUND":"User not found","errors.data.BAD_REQUEST":"Invalid request","errors.data.FIELD_ERROR":"Error in the provided data","errors.data.IN_USE":"The item is in use and cannot be deleted","errors.data.ITEM_NOT_FOUND":"The requested item was not found","errors.data.NOT_FOUND":"The requested resource was not found","errors.internal_error_changing_password":"Internal error changing password. Please try again","errors.password_min_length":"Password must be at least 8 characters","errors.password_mismatch":"Passwords do not match","errors.password_must_be_different":"New password must be different from current password","errors.system.DATABASE_CONNECTION_ERROR":"Connection error. Please check your internet connection.","errors.system.INTERNAL_SERVER_ERROR":"Internal server error. Please try again.","errors.system.INVALID_CONFIGURATION":"System configuration error","errors.system.TOO_MANY_REQUESTS":"Too many requests. Please wait a moment and try again","errors.system.UNKNOWN_OPERATION":"Unrecognized operation","errors.users_module_not_configured":"Users module not configured","footer.copyright":"Nocios S.R.L. All Rights Reserved.","footer.version":"Version","forgotPassword.checkEmailInstructions":"Check your inbox for the verification code","forgotPassword.codeAlreadyExistsMessage":"A code was already sent and is still valid","forgotPassword.emailLabel":"Email Address","forgotPassword.emailPlaceholder":"Enter your email address","forgotPassword.emailRequired":"Email address is required","forgotPassword.emailSentMessage":"Code sent successfully","forgotPassword.enterCodeLink":"Enter Code","forgotPassword.instructions":"Enter your email address and we'll send you a code to reset your password.","forgotPassword.invalidEmail":"Enter a valid email address","forgotPassword.sendCodeButton":"Send Code","forgotPassword.title":"Reset Password","loading.app.configInitial":"Loading initial configuration...","loading.app.generic":"Loading...","loading.app.starting":"Starting application...","loading.app.themeSetup":"Generating theme...","loading.app.validatingSession":"Validating session...","login.alreadyHaveCodeLink":"Already have a code?","login.forgotPasswordLink":"Forgot Password?","login.initializationError":"Initialization error","login.initializing":"Initializing...","login.loginButton":"Log In","login.logoAlt":"Logo","login.noAccountPrompt":"Don't have an account?","login.notInitialized":"System not initialized","login.passwordLabel":"Password","login.passwordPlaceholder":"Enter your password","login.passwordRequired":"Password is required","login.signUpLink":"Sign up","login.usernameOrEmailLabel":"Username or Email","login.usernameOrEmailPlaceholder":"Enter your username or email","login.usernameRequired":"Username or email is required","resetPassword.codeExpiredOrInvalid":"Code expired or invalid","resetPassword.confirmPasswordLabel":"Confirm Password","resetPassword.confirmPasswordPlaceholder":"Confirm your new password","resetPassword.confirmPasswordRequired":"Confirm your password","resetPassword.goToLoginButton":"Go to Login","resetPassword.instructions":"Enter your new password.","resetPassword.invalidCode":"The verification code is invalid. Please check the link or request a new one.","resetPassword.missingParameters":"Missing required parameters","resetPassword.newPasswordLabel":"New Password","resetPassword.newPasswordPlaceholder":"Enter your new password","resetPassword.newPasswordRequired":"New password is required","resetPassword.passwordTooShort":"Password must be at least 8 characters","resetPassword.passwordsDoNotMatch":"Passwords do not match","resetPassword.requestNewCodeButton":"Request New Code","resetPassword.resetPasswordButton":"Reset Password","resetPassword.successInstructions":"You can now log in with your new password","resetPassword.successMessage":"Password reset successfully","resetPassword.title":"New Password","resetPassword.validatingCode":"Validating code...","modules.form.publicPolicies.fields.conditions.customEdit":"Custom Edit"}},fs=()=>Object.keys(ce),ys=e=>ce[e]||ce.es;import Ve from"@nocios/crudify-browser";var Lr="crudify_translations_",Ao=3600*1e3;function Ar(e){let r=0;for(let o=0;o<e.length;o++){let t=e.charCodeAt(o);r=(r<<5)-r+t,r=r&r}return Math.abs(r).toString(36)}var rr=class e{constructor(){this.enableDebug=!1;this.initializationPromise=null;this.isInitialized=!1}static getInstance(){return e.instance||(e.instance=new e),e.instance}setDebug(r){this.enableDebug=r}async ensureCrudifyInitialized(r,o){if(!this.isInitialized)return this.initializationPromise?(this.enableDebug&&console.log("[TranslationService] Waiting for crudify initialization..."),this.initializationPromise):(this.enableDebug&&console.log("[TranslationService] Initializing crudify SDK..."),this.initializationPromise=(async()=>{try{let t=Ve.getTokenData();if(t&&t.endpoint){this.enableDebug&&console.log("[TranslationService] Crudify already initialized"),this.isInitialized=!0;return}Ve.config(o);let i=await Ve.init(r,this.enableDebug?"debug":"none");if(i.success===!1)throw new Error(`Failed to initialize crudify: ${JSON.stringify(i.errors||"Unknown error")}`);this.isInitialized=!0,this.enableDebug&&console.log("[TranslationService] Crudify SDK initialized successfully")}catch(t){throw console.error("[TranslationService] Failed to initialize crudify:",t),this.initializationPromise=null,t}})(),this.initializationPromise)}async fetchTranslations(r){let{apiKey:o,featureKeys:t,crudifyEnv:i="stg",urlTranslations:n}=r;this.enableDebug&&console.log("[TranslationService] fetchTranslations called with:",{apiKeyHash:Ar(o),crudifyEnv:i,featureKeys:t,hasUrlTranslations:!!n});let s=this.getFromCache(o),l=s?this.isCacheExpired(s):!0;if(s&&!l)return this.enableDebug&&console.log("[TranslationService] Using cached translations"),this.mergeWithUrlTranslations(s.data.translations,n);try{await this.ensureCrudifyInitialized(o,i)}catch(c){return console.error("[TranslationService] \u274C Failed to initialize crudify:",c),s?(console.warn("[TranslationService] \u26A0\uFE0F Using expired cache (init failed)"),this.mergeWithUrlTranslations(s.data.translations,n)):(console.warn("[TranslationService] \u26A0\uFE0F Using critical bundle (init failed)"),this.getCriticalTranslationsOnly())}try{this.enableDebug&&console.log("[TranslationService] Fetching from API via crudify SDK");let c=await this.fetchFromAPI(t);this.hasDataChanged(s,c)||!s?this.saveToCache(o,c):this.refreshCacheTimestamp(o);let d=this.mergeWithUrlTranslations(c.translations,n);return this.enableDebug&&console.log("[TranslationService] Translations loaded:",{languages:Object.keys(d),keysCount:d[Object.keys(d)[0]]?Object.keys(d[Object.keys(d)[0]]).length:0}),d}catch(c){return console.error("[TranslationService] \u274C API fetch failed:",c),s?(console.warn("[TranslationService] \u26A0\uFE0F Using expired cache as fallback"),this.mergeWithUrlTranslations(s.data.translations,n)):(console.warn("[TranslationService] \u26A0\uFE0F Using critical bundle translations"),this.getCriticalTranslationsOnly())}}async fetchFromAPI(r){let o=await Ve.getTranslation(r);if(!o.success)throw new Error(`Crudify API error: ${o.errors?JSON.stringify(o.errors):"Unknown error"}`);if(!o.data)throw new Error("No translation data in response");return o.data}mergeWithUrlTranslations(r,o){if(!o||Object.keys(o).length===0)return r;let t={};return Object.keys(r).forEach(i=>{t[i]={...r[i],...o}}),t}hasDataChanged(r,o){if(!r||r.data.timestamp!==o.timestamp)return!0;let t=this.hashData(o.translations);return r.dataHash!==t}hashData(r){let o=JSON.stringify(r),t=0;for(let i=0;i<o.length;i++){let n=o.charCodeAt(i);t=(t<<5)-t+n,t=t&t}return t.toString(36)}saveToCache(r,o){try{let t=this.getCacheKey(r),i={data:o,cachedAt:Date.now(),dataHash:this.hashData(o.translations)};localStorage.setItem(t,JSON.stringify(i)),this.enableDebug&&console.log("[TranslationService] Saved to cache:",t)}catch(t){console.error("[TranslationService] Failed to save cache:",t)}}getFromCache(r){try{let o=this.getCacheKey(r),t=localStorage.getItem(o);return t?JSON.parse(t):null}catch(o){return console.error("[TranslationService] Failed to read cache:",o),null}}refreshCacheTimestamp(r){try{let o=this.getFromCache(r);if(o){o.cachedAt=Date.now();let t=this.getCacheKey(r);localStorage.setItem(t,JSON.stringify(o))}}catch(o){console.error("[TranslationService] Failed to refresh cache timestamp:",o)}}isCacheExpired(r){return Date.now()-r.cachedAt>Ao}hasValidCache(r){let o=this.getFromCache(r);return o?!this.isCacheExpired(o):!1}getCacheKey(r){return`${Lr}${Ar(r)}`}getCriticalTranslationsOnly(){return ce}invalidateCache(r){let o=this.getCacheKey(r);localStorage.removeItem(o),this.enableDebug&&console.log("[TranslationService] Cache invalidated:",o)}async prefetchTranslations(r){try{await this.fetchTranslations(r),this.enableDebug&&console.log("[TranslationService] Prefetch completed")}catch(o){console.error("[TranslationService] Prefetch failed:",o)}}clearAllCaches(){try{let o=Object.keys(localStorage).filter(t=>t.startsWith(Lr));o.forEach(t=>localStorage.removeItem(t)),this.enableDebug&&console.log(`[TranslationService] Cleared ${o.length} cache entries`)}catch(r){console.error("[TranslationService] Failed to clear caches:",r)}}},We=rr.getInstance();import{createContext as Fo,useContext as _o,useEffect as Or,useState as Ie,useMemo as Fr,useCallback as Oo}from"react";import{Fragment as No,jsx as qe}from"react/jsx-runtime";var He=null,or=!1,Br=Fo(null);function _r(e,r,o){return{...e,...r,...o||{}}}function Bo(e,r,o,t,i){Or(()=>{if(!t||!e||!r)return;let n=o||typeof window<"u"&&window.i18next||typeof window<"u"&&window.i18n;if(!n||!n.addResourceBundle){i&&console.log("[TranslationsProvider] i18next not found, skipping auto-sync");return}i&&console.log("[TranslationsProvider] Auto-syncing translations with i18next",{languages:Object.keys(e),currentLanguage:r}),Object.keys(e).forEach(s=>{e[s]&&Object.keys(e[s]).length>0&&(n.addResourceBundle(s,"translation",e[s],!0,!0),i&&console.log(`[TranslationsProvider] Synced ${Object.keys(e[s]).length} keys for language: ${s}`))}),n.language!==r&&(n.changeLanguage(r),i&&console.log(`[TranslationsProvider] Changed i18next language to: ${r}`))},[e,r,o,t,i])}var Rs=({children:e,apiKey:r,crudifyEnv:o="prod",featureKeys:t,language:i="es",devTranslations:n,translationUrl:s,enableDebug:l=!1,skipAutoInit:c=!0,autoSyncI18n:w=!0,i18nInstance:d,loadingFallback:h,waitForInitialLoad:g=!0})=>{let a=Fr(()=>vr({publicApiKey:r,env:o,featureKeys:t,enableDebug:l}),[r,o,t,l]),u=a.publicApiKey||"",b=a.env||o||"prod",p=a.featureKeys||t,[y,m]=Ie({}),[C,R]=Ie(!0),[M,x]=Ie(!0),[f,P]=Ie(null),[L,_]=Ie(void 0),[ae,we]=Ie(!1),te=Oo(async()=>{if(!u){l&&console.log("[TranslationsProvider] No apiKey - skipping translation fetch"),R(!1),x(!1);return}if(ae){l&&console.log("[TranslationsProvider] Skipping reload - using fallback translations");return}if(We.hasValidCache(u)&&M&&(l&&console.log("[TranslationsProvider] Valid cache found - not blocking initial render"),x(!1)),or&&He){l&&console.log("[TranslationsProvider] Fetch already in progress, waiting for existing promise");try{let I=await He;m(I),R(!1);return}catch{l&&console.warn("[TranslationsProvider] Global fetch failed, retrying")}}or=!0,R(!0),P(null);let F;if(s)try{l&&console.log(`[TranslationsProvider] Fetching translations from URL: ${s}`);let I=await fetch(s);if(!I.ok)throw new Error(`Failed to fetch translations: ${I.statusText}`);F=await I.json(),_(F),l&&console.log("[TranslationsProvider] URL translations loaded:",{keysCount:F?Object.keys(F).length:0})}catch(I){console.error("[TranslationsProvider] Failed to load URL translations:",I),F=void 0,_(void 0)}let Ee=(async()=>{try{We.setDebug(l);let I=await We.fetchTranslations({apiKey:u,crudifyEnv:b,featureKeys:p,urlTranslations:F}),H={};return Object.keys(I).forEach(v=>{let S=ce[v]||{},O=I[v]||{};H[v]=_r(S,O,n)}),l&&console.log("[TranslationsProvider] Loaded translations:",{languages:Object.keys(H),keysCount:Object.keys(H[i]||{}).length}),H}catch(I){console.error("[TranslationsProvider] Failed to load:",I),P(I.message),we(!0);let H={};return Object.keys(ce).forEach(v=>{let S=ce[v],O=F||L||{};H[v]=_r(S,O,n)}),l&&console.log("[TranslationsProvider] Using fallback translations (critical + URL)"),H}})();He=Ee;try{let I=await Ee;m(I)}finally{R(!1),x(!1),or=!1,setTimeout(()=>{He=null},1e3)}},[u,b,p,s,n,l,i,ae]);Or(()=>{te();let V=setInterval(te,3600*1e3);return()=>clearInterval(V)},[te]);let ue=Fr(()=>(V,F)=>{let I=(y[i]||{})[V];if(!I){let H=Object.keys(y);for(let v of H)if(y[v][V]){I=y[v][V];break}}return I||(l&&console.warn(`[TranslationsProvider] Missing translation: "${V}"`),I=V),F&&typeof I=="string"&&Object.entries(F).forEach(([H,v])=>{let S=new RegExp(`{{${H}}}`,"g");I=I.replace(S,String(v))}),I},[y,i,l]);Bo(y,i,d,w,l);let A={t:ue,language:i,availableLanguages:Object.keys(y),translations:y,isLoading:C,error:f,refreshTranslations:te};return u?g&&M&&C?h||qe("div",{style:{display:"flex",justifyContent:"center",alignItems:"center",height:"100vh"},children:qe("div",{children:"Loading translations..."})}):qe(Br.Provider,{value:A,children:e}):(l&&console.warn("[TranslationsProvider] No API key available. Skipping translations. Provide apiKey via props or ensure cookies are set by Lambda."),qe(No,{children:e}))},Nr=()=>{let e=_o(Br);if(!e)throw new Error("useTranslations must be used within TranslationsProvider");return e};import{Box as Ct,Typography as Pt}from"@mui/material";import{createContext as zo,useContext as Uo,useMemo as nr}from"react";import{useState as tr,useEffect as Do}from"react";var Dr=(e,r)=>{let[o,t]=tr({}),[i,n]=tr(!1),[s,l]=tr(null);return Do(()=>{if(console.log("\u{1F527} [I18nProvider] Hybrid translation loading:",{hasProvidedTranslations:!!r&&Object.keys(r).length>0,hasUrl:!!e,providedKeys:r?Object.keys(r).length:0}),r&&Object.keys(r).length>0){console.log("\u2705 [I18nProvider] Using provided translations (highest priority)"),t(r),n(!1),l(null);return}if(!e){console.log("\u26A0\uFE0F [I18nProvider] No translations provided, using empty object (keys will show as-is)"),t({}),n(!1),l(null);return}console.log("\u{1F310} [I18nProvider] Loading translations from URL:",e);let c=!1;return n(!0),l(null),fetch(e).then(w=>{if(!w.ok)throw new Error(`Failed to load translations: ${w.status}`);return w.json()}).then(w=>{c||(console.log("\u2705 [I18nProvider] Translations loaded successfully from URL:",{url:e,keysLoaded:Object.keys(w).length}),t(w),n(!1))}).catch(w=>{c||(console.error("\u274C [I18nProvider] Failed to load translations from URL:",e,w),l(w.message),console.log("\u{1F504} [I18nProvider] Falling back to empty translations (keys will show as-is)"),t({}),n(!1))}),()=>{c=!0}},[e,r]),{translations:o,loading:i,error:s}};import{jsx as zr}from"react/jsx-runtime";var Ur=zo(null),Mo=()=>{try{return Nr()}catch{return null}},Vo=(e,r)=>{if(r.includes(".")){let o=r.split(".").reduce((t,i)=>t&&typeof t=="object"?t[i]:void 0,e);if(o!==void 0)return o}if(e&&e[r])return e[r]},Mr=({children:e,translations:r,translationsUrl:o,language:t="en"})=>{let n=Mo()?.translations?.[t]||{},{translations:s,loading:l}=Dr(o,r),c=nr(()=>({...n,...s,...r||{}}),[n,s,r]),w=nr(()=>(h,g)=>{let a=Vo(c,h);return a==null&&(console.log(`\u{1F50D} [I18nProvider] Translation not found for key: "${h}" - showing key as-is`),a=h),g&&typeof a=="string"&&Object.entries(g).forEach(([u,b])=>{a=a.replace(new RegExp(`{{${u}}}`,"g"),b)}),typeof a=="string"?a:h},[c]),d=nr(()=>({t:w,language:t}),[w,t]);return l?zr("div",{children:"Loading translations..."}):zr(Ur.Provider,{value:d,children:e})},Q=()=>{let e=Uo(Ur);if(!e)throw new Error("useTranslation must be used within I18nProvider");return e};import{createContext as Wo,useContext as Ho,useReducer as qo,useEffect as Vr}from"react";import{jsx as $o}from"react/jsx-runtime";var Wr={currentScreen:"login",searchParams:{},formData:{username:"",password:"",email:"",code:"",newPassword:"",confirmPassword:""},loading:!1,errors:{global:[]},emailSent:!1,codeAlreadyExists:!1,codeValidated:!1,fromCodeVerification:!1,config:{}};function jo(e,r){switch(r.type){case"SET_SCREEN":let o={...e,currentScreen:r.payload.screen,searchParams:r.payload.params||e.searchParams,errors:{global:[]}},t=new URLSearchParams(o.searchParams),i=t.toString()?`?${t.toString()}`:window.location.pathname;try{window.history.replaceState({},"",i)}catch{}return o;case"SET_SEARCH_PARAMS":return{...e,searchParams:r.payload};case"UPDATE_FORM_DATA":return{...e,formData:{...e.formData,...r.payload},errors:{...e.errors,...Object.keys(r.payload).reduce((n,s)=>({...n,[s]:void 0}),{})}};case"SET_LOADING":return{...e,loading:r.payload};case"SET_ERRORS":return{...e,errors:{...e.errors,...r.payload}};case"CLEAR_ERRORS":return{...e,errors:{global:[]}};case"SET_EMAIL_SENT":return{...e,emailSent:r.payload};case"SET_CODE_ALREADY_EXISTS":return{...e,codeAlreadyExists:r.payload};case"SET_CODE_VALIDATED":return{...e,codeValidated:r.payload};case"SET_FROM_CODE_VERIFICATION":return{...e,fromCodeVerification:r.payload};case"RESET_FORM":return{...e,formData:Wr.formData,errors:{global:[]},loading:!1,emailSent:!1,codeAlreadyExists:!1,codeValidated:!1,fromCodeVerification:!1};case"INIT_CONFIG":return{...e,config:r.payload};default:return e}}var Hr=Wo(void 0),qr=({children:e,initialScreen:r="login",config:o,autoReadFromCookies:t=!0})=>{let[i,n]=qo(jo,{...Wr,currentScreen:r});Vr(()=>{n({type:"INIT_CONFIG",payload:(()=>{let a={};if(t)try{let u=Pr("logo");if(u){let b=decodeURIComponent(u);b.startsWith("http")&&(a.logo=b)}}catch(u){console.error("Error reading configuration from cookies:",u)}return{publicApiKey:o?.publicApiKey,env:o?.env,appName:o?.appName,logo:o?.logo||a.logo,loginActions:o?.loginActions}})()})},[o,t]),Vr(()=>{let g=new URLSearchParams(window.location.search),a={};g.forEach((u,b)=>{a[b]=u}),Object.keys(a).length>0&&n({type:"SET_SEARCH_PARAMS",payload:a}),r==="checkCode"&&a.email&&n({type:"UPDATE_FORM_DATA",payload:{email:a.email,code:a.code||""}}),r==="resetPassword"&&a.link&&n({type:"SET_SEARCH_PARAMS",payload:a})},[r]);let h={state:i,dispatch:n,setScreen:(g,a)=>{n({type:"SET_SCREEN",payload:{screen:g,params:a}})},updateFormData:g=>{n({type:"UPDATE_FORM_DATA",payload:g})},setFieldError:(g,a)=>{n({type:"SET_ERRORS",payload:{[g]:a}})},clearErrors:()=>{n({type:"CLEAR_ERRORS"})},setLoading:g=>{n({type:"SET_LOADING",payload:g})}};return $o(Hr.Provider,{value:h,children:e})},je=()=>{let e=Ho(Hr);if(e===void 0)throw new Error("useLoginState must be used within a LoginStateProvider");return e};import{useEffect as Ko,useRef as Go}from"react";import{Typography as sr,TextField as jr,Button as Yo,Box as _e,CircularProgress as Xo,Alert as Jo,Link as $r}from"@mui/material";import{Fragment as Zo,jsx as Z,jsxs as Oe}from"react/jsx-runtime";var Qo=({onScreenChange:e,onExternalNavigate:r,onLoginSuccess:o,onError:t,redirectUrl:i="/"})=>{let{crudify:n}=ne(),{state:s,updateFormData:l,setFieldError:c,clearErrors:w,setLoading:d}=je(),{login:h}=ge(),g=Q(),{t:a}=g,u=g.i18n,b=Go(null),p=Er(a,{currentLanguage:u?.language,enableDebug:!1}),y=()=>{if(s.searchParams.redirect)try{let f=decodeURIComponent(s.searchParams.redirect);if(f.startsWith("/")&&!f.startsWith("//"))return f}catch{}return i||"/"};Ko(()=>{let f=setTimeout(()=>{b.current&&b.current.focus()},100);return()=>clearTimeout(f)},[]);let m=f=>{console.log("\u{1F50D} [LoginForm] Translating parsed error:",f);let P=p.translateError({code:f.code,message:f.message,field:f.field});return console.log("\u{1F50D} [LoginForm] Translation result:",P),P},C=async()=>{if(!s.loading){if(!s.formData.username.trim()){c("username",a("login.usernameRequired"));return}if(!s.formData.password.trim()){c("password",a("login.passwordRequired"));return}w(),d(!0);try{let f=await h(s.formData.username,s.formData.password);if(d(!1),f.success){console.log("\u{1F510} LoginForm - Login successful via SessionProvider, calling onLoginSuccess");let P=y();o&&o(f.data,P)}else{let P=f.rawResponse||f;R(P)}}catch(f){d(!1);let L=K(f).map(m);c("global",L),t&&t(L.join(", "))}}},R=f=>{let P=K(f),L=[];P.forEach(_=>{_.field?c(_.field,m(_)):L.push(m(_))}),L.length>0&&c("global",L)};return Oe(Zo,{children:[Oe(_e,{component:"form",noValidate:!0,onSubmit:f=>{f.preventDefault(),C()},onKeyDown:f=>{f.key==="Enter"&&!s.loading&&(f.preventDefault(),C())},sx:{width:"100%",display:"flex",flexDirection:"column",gap:2},children:[Oe(_e,{sx:{mb:1},children:[Z(sr,{variant:"body2",component:"label",htmlFor:"email",sx:{display:"block",fontWeight:500,color:"grey.700",mb:.5},children:a("login.usernameOrEmailLabel")}),Z(jr,{fullWidth:!0,id:"email",name:"email",type:"email",value:s.formData.username,disabled:s.loading,onChange:f=>l({username:f.target.value}),error:!!s.errors.username,helperText:s.errors.username,autoComplete:"email",placeholder:a("login.usernameOrEmailPlaceholder"),inputRef:b,required:!0})]}),Oe(_e,{sx:{mb:1},children:[Z(sr,{variant:"body2",component:"label",htmlFor:"password",sx:{display:"block",fontWeight:500,color:"grey.700",mb:.5},children:a("login.passwordLabel")}),Z(jr,{fullWidth:!0,id:"password",name:"password",type:"password",value:s.formData.password,disabled:s.loading,onChange:f=>l({password:f.target.value}),error:!!s.errors.password,helperText:s.errors.password,autoComplete:"current-password",placeholder:a("login.passwordPlaceholder"),required:!0})]}),s.config.loginActions?.includes("forgotPassword")&&Z(_e,{sx:{display:"flex",justifyContent:"flex-end",alignItems:"center"},children:Z($r,{sx:{cursor:"pointer"},onClick:()=>{e?.("forgotPassword",s.searchParams)},variant:"body2",color:"secondary",children:a("login.forgotPasswordLink")})}),Z(Yo,{disabled:s.loading,type:"submit",fullWidth:!0,variant:"contained",color:"primary",sx:{mt:1,mb:2},children:s.loading?Z(Xo,{size:20}):a("login.loginButton")})]}),Z(_e,{children:s.errors.global&&s.errors.global.length>0&&s.errors.global.map((f,P)=>Z(Jo,{variant:"filled",sx:{mt:2},severity:"error",children:Z("div",{children:f})},P))}),s.config.loginActions?.includes("createUser")&&Oe(sr,{variant:"body2",align:"center",sx:{color:"text.secondary",mt:3},children:[a("login.noAccountPrompt")," ",Z($r,{sx:{cursor:"pointer"},onClick:()=>{let P=`/public/users/create${Object.keys(s.searchParams).length>0?`?${new URLSearchParams(s.searchParams).toString()}`:""}`;r?.(P)},fontWeight:"medium",color:"secondary",children:a("login.signUpLink")})]})]})},Kr=Qo;import{useState as Se,useEffect as et,useRef as rt}from"react";import{Typography as ke,TextField as ot,Button as Gr,Box as me,CircularProgress as tt,Alert as nt,Link as ir}from"@mui/material";import{Fragment as Yr,jsx as U,jsxs as Ce}from"react/jsx-runtime";var st=({onScreenChange:e,onError:r})=>{let{crudify:o}=ne(),[t,i]=Se(""),[n,s]=Se(!1),[l,c]=Se([]),[w,d]=Se(null),[h,g]=Se(!1),[a,u]=Se(!1),b=rt(null),{t:p}=Q();et(()=>{b.current&&!h&&!a&&b.current.focus()},[h,a]);let y=f=>{let P=[`errors.auth.${f.code}`,`errors.data.${f.code}`,`errors.system.${f.code}`,`errors.${f.code}`,`forgotPassword.${f.code.toLowerCase()}`];for(let L of P){let _=p(L);if(_!==L)return _}return f.message||p("error.unknown")},m=f=>/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(f),C=async()=>{if(!(n||!o)){if(c([]),d(null),!t){d(p("forgotPassword.emailRequired"));return}if(!m(t)){d(p("forgotPassword.invalidEmail"));return}s(!0);try{let f=[{operation:"requestPasswordReset",data:{email:t}}],P=await o.transaction(f);if(P.success)P.data&&P.data.existingCodeValid?u(!0):g(!0);else{let _=K(P).map(y);c(_)}}catch(f){let L=K(f).map(y);c(L),r&&r(L.join(", "))}finally{s(!1)}}},R=()=>{e?.("login")},M=()=>{if(h||a){e?.("checkCode",{email:t});return}if(!t){d(p("forgotPassword.emailRequired"));return}if(!m(t)){d(p("forgotPassword.invalidEmail"));return}e?.("checkCode",{email:t})};return h||a?U(Yr,{children:Ce(me,{sx:{width:"100%",display:"flex",flexDirection:"column",gap:2,textAlign:"center"},children:[Ce(me,{sx:{mb:2},children:[U(ke,{variant:"h5",component:"h1",sx:{mb:1,fontWeight:600},children:p(a?"forgotPassword.codeAlreadyExistsMessage":"forgotPassword.emailSentMessage")}),U(ke,{variant:"body2",sx:{color:a?"success.main":"grey.600"},children:p("forgotPassword.checkEmailInstructions")})]}),U(Gr,{type:"button",onClick:M,fullWidth:!0,variant:"contained",color:"primary",sx:{mt:2,mb:2},children:p("forgotPassword.enterCodeLink")}),U(me,{sx:{display:"flex",justifyContent:"center",alignItems:"center"},children:U(ir,{sx:{cursor:"pointer"},onClick:R,variant:"body2",color:"secondary",children:p("common.back")})})]})}):Ce(Yr,{children:[Ce(me,{component:"form",noValidate:!0,onSubmit:f=>{f.preventDefault(),C()},sx:{width:"100%",display:"flex",flexDirection:"column",gap:2},children:[Ce(me,{sx:{mb:2},children:[U(ke,{variant:"h5",component:"h1",sx:{mb:1,fontWeight:600},children:p("forgotPassword.title")}),U(ke,{variant:"body2",sx:{color:"grey.600"},children:p("forgotPassword.instructions")})]}),Ce(me,{sx:{mb:1},children:[U(ke,{variant:"body2",component:"label",htmlFor:"email",sx:{display:"block",fontWeight:500,color:"grey.700",mb:.5},children:p("forgotPassword.emailLabel")}),U(ot,{fullWidth:!0,id:"email",name:"email",type:"email",value:t,disabled:n,onChange:f=>i(f.target.value),error:!!w,helperText:w,autoComplete:"email",placeholder:p("forgotPassword.emailPlaceholder"),required:!0,autoFocus:!0,inputRef:b})]}),U(Gr,{disabled:n,type:"submit",fullWidth:!0,variant:"contained",color:"primary",sx:{mt:2,mb:2},children:n?U(tt,{size:20}):p("forgotPassword.sendCodeButton")}),Ce(me,{sx:{display:"flex",justifyContent:"center",alignItems:"center",gap:2},children:[U(ir,{sx:{cursor:"pointer"},onClick:R,variant:"body2",color:"secondary",children:p("common.back")}),U(ke,{variant:"body2",sx:{color:"grey.400"},children:"\u2022"}),U(ir,{sx:{cursor:"pointer"},onClick:M,variant:"body2",color:"secondary",children:p("login.alreadyHaveCodeLink")})]})]}),U(me,{children:l.length>0&&l.map((f,P)=>U(nt,{variant:"filled",sx:{mt:2},severity:"error",children:f},P))})]})},Xr=st;import{useState as X,useEffect as Jr}from"react";import{Typography as $e,TextField as Qr,Button as it,Box as pe,CircularProgress as Zr,Alert as eo,Link as at}from"@mui/material";import{Fragment as ct,jsx as W,jsxs as Be}from"react/jsx-runtime";var lt=({onScreenChange:e,onError:r,searchParams:o,onResetSuccess:t})=>{let{crudify:i}=ne(),[n,s]=X(""),[l,c]=X(""),[w,d]=X(!1),[h,g]=X([]),[a,u]=X(null),[b,p]=X(null),[y,m]=X(""),[C,R]=X(""),[M,x]=X(!1),[f,P]=X(!0),[L,_]=X(!1),[ae,we]=X(null),[te,ue]=X(!1),{t:A}=Q(),V=v=>{let S=[`errors.auth.${v.code}`,`errors.data.${v.code}`,`errors.system.${v.code}`,`errors.${v.code}`,`resetPassword.${v.code.toLowerCase()}`];for(let O of S){let q=A(O);if(q!==O)return q}return v.message||A("error.unknown")},F=v=>o?o instanceof URLSearchParams?o.get(v):o[v]||null:null;Jr(()=>{if(o){if(o){let v=F("fromCodeVerification"),S=F("email"),O=F("code");if(v==="true"&&S&&O){m(S),R(O),x(!0),_(!0),P(!1);return}let q=F("link");if(q)try{let G=decodeURIComponent(q),[Y,le]=G.split("/");if(Y&&le&&Y.length===6){R(Y),m(le),x(!1),we({email:le,code:Y});return}}catch{}if(S&&O){m(S),R(O),x(!1),we({email:S,code:O});return}}g([A("resetPassword.invalidCode")]),P(!1),setTimeout(()=>e?.("forgotPassword"),3e3)}},[o,i,A,e]),Jr(()=>{i&&ae&&!te&&(ue(!0),(async(S,O)=>{try{let q=[{operation:"validatePasswordResetCode",data:{email:S,codePassword:O}}],G=await i.transaction(q);if(G.data&&Array.isArray(G.data)){let Y=G.data[0];if(Y&&Y.response&&Y.response.status==="OK"){_(!0);return}}if(G.success)_(!0);else{let le=K(G).map(V);g(le),setTimeout(()=>e?.("forgotPassword"),3e3)}}catch(q){let Y=K(q).map(V);g(Y),setTimeout(()=>e?.("forgotPassword"),3e3)}finally{P(!1),we(null),ue(!1)}})(ae.email,ae.code))},[i,ae,A,e]);let Ee=v=>v.length<8?A("resetPassword.passwordTooShort"):null,I=async()=>{if(w||!i)return;g([]),u(null),p(null);let v=!1;if(!n)u(A("resetPassword.newPasswordRequired")),v=!0;else{let S=Ee(n);S&&(u(S),v=!0)}if(l?n!==l&&(p(A("resetPassword.passwordsDoNotMatch")),v=!0):(p(A("resetPassword.confirmPasswordRequired")),v=!0),!v){d(!0);try{let S=[{operation:"validateAndResetPassword",data:{email:y,codePassword:C,newPassword:n}}],O=await i.transaction(S);if(O.success)g([]),setTimeout(()=>{t?.()},1e3);else{let G=K(O).map(V);g(G)}}catch(S){let q=K(S).map(V);g(q),r&&r(q.join(", "))}d(!1)}},H=()=>{M?e?.("checkCode",{email:y}):e?.("forgotPassword")};return f?W(pe,{sx:{display:"flex",justifyContent:"center",alignItems:"center",minHeight:"300px"},children:W(Zr,{})}):L?Be(ct,{children:[Be(pe,{component:"form",noValidate:!0,sx:{width:"100%",display:"flex",flexDirection:"column",gap:2},children:[Be(pe,{sx:{mb:2},children:[W($e,{variant:"h5",component:"h1",sx:{mb:1,fontWeight:600},children:A("resetPassword.title")}),W($e,{variant:"body2",sx:{color:"grey.600"},children:A("resetPassword.instructions")})]}),Be(pe,{sx:{mb:1},children:[W($e,{variant:"body2",component:"label",htmlFor:"newPassword",sx:{display:"block",fontWeight:500,color:"grey.700",mb:.5},children:A("resetPassword.newPasswordLabel")}),W(Qr,{fullWidth:!0,id:"newPassword",name:"newPassword",type:"password",value:n,disabled:w,onChange:v=>s(v.target.value),error:!!a,helperText:a,autoComplete:"new-password",placeholder:A("resetPassword.newPasswordPlaceholder"),required:!0})]}),Be(pe,{sx:{mb:1},children:[W($e,{variant:"body2",component:"label",htmlFor:"confirmPassword",sx:{display:"block",fontWeight:500,color:"grey.700",mb:.5},children:A("resetPassword.confirmPasswordLabel")}),W(Qr,{fullWidth:!0,id:"confirmPassword",name:"confirmPassword",type:"password",value:l,disabled:w,onChange:v=>c(v.target.value),error:!!b,helperText:b,autoComplete:"new-password",placeholder:A("resetPassword.confirmPasswordPlaceholder"),required:!0})]}),W(it,{disabled:w,type:"button",onClick:I,fullWidth:!0,variant:"contained",color:"primary",sx:{mt:2,mb:2},children:w?W(Zr,{size:20}):A("resetPassword.resetPasswordButton")}),W(pe,{sx:{display:"flex",justifyContent:"center",alignItems:"center"},children:W(at,{sx:{cursor:"pointer"},onClick:H,variant:"body2",color:"secondary",children:A("common.back")})})]}),W(pe,{children:h.length>0&&h.map((v,S)=>W(eo,{variant:"filled",sx:{mt:2},severity:"error",children:v},S))})]}):W(pe,{children:h.length>0&&h.map((v,S)=>W(eo,{variant:"filled",sx:{mt:2},severity:"error",children:v},S))})},ro=lt;import{useState as Ne,useEffect as oo,useRef as dt}from"react";import{Typography as ar,TextField as ut,Button as gt,Box as De,CircularProgress as mt,Alert as pt,Link as ft}from"@mui/material";import{Fragment as ht,jsx as se,jsxs as Ke}from"react/jsx-runtime";var yt=({onScreenChange:e,onError:r,searchParams:o})=>{let{crudify:t}=ne(),[i,n]=Ne(""),[s,l]=Ne(!1),[c,w]=Ne([]),[d,h]=Ne(null),[g,a]=Ne(""),u=dt(null),{t:b}=Q(),p=x=>o?o instanceof URLSearchParams?o.get(x):o[x]||null:null,y=x=>{let f=[`errors.auth.${x.code}`,`errors.data.${x.code}`,`errors.system.${x.code}`,`errors.${x.code}`,`checkCode.${x.code.toLowerCase()}`];for(let P of f){let L=b(P);if(L!==P)return L}return x.message||b("error.unknown")};oo(()=>{let x=p("email");x?a(x):e?.("forgotPassword")},[o,e]),oo(()=>{u.current&&u.current.focus()},[]);let m=async()=>{if(!(s||!t)){if(w([]),h(null),!i){h(b("checkCode.codeRequired"));return}if(i.length!==6){h(b("checkCode.codeRequired"));return}l(!0);try{let x=[{operation:"validatePasswordResetCode",data:{email:g,codePassword:i}}],f=await t.transaction(x);if(f.success)e?.("resetPassword",{email:g,code:i,fromCodeVerification:"true"});else{let L=K(f).map(y);w(L),l(!1)}}catch(x){let P=K(x).map(y);w(P),l(!1),r&&r(P.join(", "))}}},C=()=>{e?.("forgotPassword")},R=x=>{let f=x.target.value.replace(/\D/g,"").slice(0,6);n(f)};return Ke(ht,{children:[Ke(De,{component:"form",noValidate:!0,onSubmit:x=>{x.preventDefault(),m()},sx:{width:"100%",display:"flex",flexDirection:"column",gap:2},children:[Ke(De,{sx:{mb:2},children:[se(ar,{variant:"h5",component:"h1",sx:{mb:1,fontWeight:600},children:b("checkCode.title")}),se(ar,{variant:"body2",sx:{color:"grey.600"},children:b("checkCode.instructions")})]}),Ke(De,{sx:{mb:1},children:[se(ar,{variant:"body2",component:"label",htmlFor:"code",sx:{display:"block",fontWeight:500,color:"grey.700",mb:.5},children:b("checkCode.codeLabel")}),se(ut,{fullWidth:!0,id:"code",name:"code",type:"text",value:i,disabled:s,onChange:R,error:!!d,helperText:d,placeholder:b("checkCode.codePlaceholder"),inputProps:{maxLength:6,style:{textAlign:"center",fontSize:"1.5rem",letterSpacing:"0.4rem"}},required:!0,autoFocus:!0,inputRef:u})]}),se(gt,{disabled:s||i.length!==6,type:"submit",fullWidth:!0,variant:"contained",color:"primary",sx:{mt:2,mb:2},children:s?se(mt,{size:20}):b("checkCode.verifyButton")}),se(De,{sx:{display:"flex",justifyContent:"center",alignItems:"center"},children:se(ft,{sx:{cursor:"pointer"},onClick:C,variant:"body2",color:"secondary",children:b("common.back")})})]}),se(De,{children:c.length>0&&c.map((x,f)=>se(pt,{sx:{mt:2},severity:"error",children:x},f))})]})},to=yt;import{Box as bt,CircularProgress as wt,Alert as no,Typography as lr}from"@mui/material";import{Fragment as xt,jsx as Le,jsxs as so}from"react/jsx-runtime";var io=({children:e,fallback:r})=>{let{isLoading:o,error:t,isInitialized:i}=ne(),{t:n}=Q();return o?r||so(bt,{sx:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",minHeight:"200px",gap:2},children:[Le(wt,{}),Le(lr,{variant:"body2",color:"text.secondary",children:n("login.initializing")!=="login.initializing"?n("login.initializing"):"Initializing..."})]}):t?Le(no,{severity:"error",sx:{mt:2},children:so(lr,{variant:"body2",children:[n("login.initializationError")!=="login.initializationError"?n("login.initializationError"):"Initialization error",":"," ",t]})}):i?Le(xt,{children:e}):Le(no,{severity:"warning",sx:{mt:2},children:Le(lr,{variant:"body2",children:n("login.notInitialized")!=="login.notInitialized"?n("login.notInitialized"):"System not initialized"})})};import{jsx as re,jsxs as Et}from"react/jsx-runtime";var vt=({onScreenChange:e,onExternalNavigate:r,onLoginSuccess:o,onError:t,redirectUrl:i="/"})=>{let{t:n}=Q(),{state:s,setScreen:l}=je(),{config:c}=ge(),{showNotification:w}=Rr(),d=(g,a)=>{let u=a;g==="login"?u={}:g==="forgotPassword"&&!a&&(u={}),l(g,u),e?.(g,u)},h=()=>{let g={onScreenChange:d,onExternalNavigate:r,onError:t,redirectUrl:i};switch(s.currentScreen){case"forgotPassword":return re(Xr,{...g});case"checkCode":return re(to,{...g,searchParams:s.searchParams});case"resetPassword":return re(ro,{...g,searchParams:s.searchParams,onResetSuccess:()=>{let a=n("resetPassword.successMessage");w(a,"success"),d("login")}});default:return re(Kr,{...g,onLoginSuccess:o})}};return Et(io,{children:[re(Ct,{sx:{display:"flex",justifyContent:"center",mb:3},children:re("img",{src:c.logo||"https://logos.crudia.com/nocios-default.png",alt:n("login.logoAlt"),style:{width:"100%",maxWidth:"150px",height:"auto"},onError:g=>{let a=g.target;a.src="https://logos.crudia.com/nocios-default.png"}})}),!c.logo&&c.appName&&re(Pt,{variant:"h6",component:"h1",sx:{textAlign:"center",mb:2},children:c.appName}),h()]})},Tt=({translations:e,translationsUrl:r,language:o="en",initialScreen:t="login",autoReadFromCookies:i=!0,...n})=>{let{config:s}=ge();return re(Mr,{translations:e,translationsUrl:r,language:o,children:re(Tr,{config:s,children:re(qr,{config:s,initialScreen:t,autoReadFromCookies:i,children:re(vt,{...n})})})})},Bi=Tt;import{Box as J,Card as ao,CardContent as lo,Typography as oe,Chip as Ge,Avatar as Rt,Divider as It,CircularProgress as St,Alert as co,List as kt,ListItem as cr,ListItemText as dr,ListItemIcon as Lt,Collapse as At,IconButton as ur}from"@mui/material";import{Person as Ft,Email as _t,Badge as Ot,Security as Bt,Schedule as Nt,AccountCircle as Dt,ExpandMore as zt,ExpandLess as Ut,Info as Mt}from"@mui/icons-material";import{useState as Vt}from"react";import{Fragment as qt,jsx as T,jsxs as B}from"react/jsx-runtime";var Wt=({showExtendedData:e=!0,showProfileCard:r=!0,autoRefresh:o=!0})=>{let{userProfile:t,loading:i,error:n,extendedData:s,refreshProfile:l}=Ir({autoFetch:o,retryOnError:!0,maxRetries:3}),[c,w]=Vt(!1);if(i)return B(J,{display:"flex",justifyContent:"center",alignItems:"center",p:3,children:[T(St,{}),T(oe,{variant:"body2",sx:{ml:2},children:"Cargando perfil de usuario..."})]});if(n)return B(co,{severity:"error",action:T(ur,{color:"inherit",size:"small",onClick:l,children:T(oe,{variant:"caption",children:"Reintentar"})}),children:["Error al cargar el perfil: ",n]});if(!t)return T(co,{severity:"warning",children:"No se encontr\xF3 informaci\xF3n del usuario"});let d=s?.displayData||{},h=s?.totalFields||0,g=m=>{if(!m)return"No disponible";try{return new Date(m).toLocaleString("es-ES",{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}catch{return m}},a=(m,C)=>C==null?"No disponible":typeof C=="boolean"?C?"S\xED":"No":Array.isArray(C)?C.length>0?C.join(", "):"Ninguno":typeof C=="object"?JSON.stringify(C,null,2):String(C),u=[{key:"id",label:"ID",icon:T(Ot,{})},{key:"email",label:"Email",icon:T(_t,{})},{key:"username",label:"Usuario",icon:T(Ft,{})},{key:"fullName",label:"Nombre completo",icon:T(Dt,{})},{key:"role",label:"Rol",icon:T(Bt,{})}],b=[{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"}],p=[...u.map(m=>m.key),...b.map(m=>m.key),"permissions"],y=Object.keys(d).filter(m=>!p.includes(m)).map(m=>({key:m,label:m}));return B(J,{children:[r&&T(ao,{sx:{mb:2},children:B(lo,{children:[B(J,{display:"flex",alignItems:"center",mb:2,children:[T(Rt,{src:d.avatar,sx:{width:56,height:56,mr:2},children:d.fullName?.[0]||d.username?.[0]||d.email?.[0]}),B(J,{children:[T(oe,{variant:"h6",children:d.fullName||d.username||d.email}),T(oe,{variant:"body2",color:"text.secondary",children:d.role||"Usuario"}),d.isActive!==void 0&&T(Ge,{label:d.isActive?"Activo":"Inactivo",color:d.isActive?"success":"error",size:"small",sx:{mt:.5}})]})]}),T(J,{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(250px, 1fr))",gap:2,children:u.map(({key:m,label:C,icon:R})=>d[m]?B(J,{display:"flex",alignItems:"center",children:[T(J,{sx:{mr:1,color:"text.secondary"},children:R}),B(J,{children:[T(oe,{variant:"caption",color:"text.secondary",children:C}),T(oe,{variant:"body2",children:a(m,d[m])})]})]},m):null)}),d.permissions&&Array.isArray(d.permissions)&&d.permissions.length>0&&B(J,{mt:2,children:[T(oe,{variant:"caption",color:"text.secondary",display:"block",children:"Permisos"}),B(J,{display:"flex",flexWrap:"wrap",gap:.5,mt:.5,children:[d.permissions.slice(0,5).map((m,C)=>T(Ge,{label:m,size:"small",variant:"outlined"},C)),d.permissions.length>5&&T(Ge,{label:`+${d.permissions.length-5} m\xE1s`,size:"small"})]})]})]})}),e&&T(ao,{children:B(lo,{children:[B(J,{display:"flex",justifyContent:"space-between",alignItems:"center",mb:2,children:[B(oe,{variant:"h6",display:"flex",alignItems:"center",children:[T(Mt,{sx:{mr:1}}),"Informaci\xF3n Detallada"]}),T(Ge,{label:`${h} campos totales`,size:"small"})]}),B(kt,{dense:!0,children:[b.map(({key:m,label:C})=>d[m]!==void 0&&B(cr,{divider:!0,children:[T(Lt,{children:T(Nt,{fontSize:"small"})}),T(dr,{primary:C,secondary:m.includes("At")||m.includes("Login")?g(d[m]):a(m,d[m])})]},m)),y.length>0&&B(qt,{children:[T(It,{sx:{my:1}}),T(cr,{children:T(dr,{primary:B(J,{display:"flex",justifyContent:"space-between",alignItems:"center",children:[B(oe,{variant:"subtitle2",children:["Campos Personalizados (",y.length,")"]}),T(ur,{size:"small",onClick:()=>w(!c),children:c?T(Ut,{}):T(zt,{})})]})})}),T(At,{in:c,children:y.map(({key:m,label:C})=>T(cr,{sx:{pl:4},children:T(dr,{primary:C,secondary:a(m,d[m])})},m))})]})]}),B(J,{mt:2,display:"flex",justifyContent:"space-between",alignItems:"center",children:[B(oe,{variant:"caption",color:"text.secondary",children:["\xDAltima actualizaci\xF3n: ",g(d.updatedAt)]}),T(ur,{size:"small",onClick:l,disabled:i,children:T(oe,{variant:"caption",children:"Actualizar"})})]})]})})]})},Ht=Wt;var uo=["create","read","update","delete"],go=["create","read","update","delete"];import{useRef as pn}from"react";import{useTranslation as fn}from"react-i18next";import{Box as Je,Typography as wo,Button as yn,Stack as hn,Alert as xo,Divider as bn}from"@mui/material";import{Add as wn}from"@mui/icons-material";import{forwardRef as en}from"react";import{useTranslation as rn}from"react-i18next";import{Box as Pe,FormControl as on,InputLabel as tn,Select as nn,MenuItem as sn,IconButton as an,Typography as Ae,FormHelperText as ln,Stack as Xe,Paper as bo,Divider as cn,Button as fr}from"@mui/material";import{Delete as dn,SelectAll as un,ClearAll as gn}from"@mui/icons-material";import{useState as mo,useEffect as po,useRef as fo}from"react";import{useTranslation as jt}from"react-i18next";import{Box as Ye,Typography as ze,Button as yo,Stack as gr,FormControlLabel as $t,FormHelperText as ho,Switch as Kt,ToggleButton as mr,ToggleButtonGroup as Gt}from"@mui/material";import{CheckCircle as Yt,Cancel as Xt,SelectAll as Jt,ClearAll as Qt}from"@mui/icons-material";import{jsx as D,jsxs as fe}from"react/jsx-runtime";var Zt=({value:e,onChange:r,availableFields:o,error:t,disabled:i=!1})=>{let{t:n}=jt(),[s,l]=mo("custom"),[c,w]=mo(!1),d=fo(null);po(()=>{c&&d.current?.scrollIntoView({behavior:"smooth",block:"start"})},[c]);let h=fo(!1);po(()=>{let p=e||{allow:[],owner_allow:[],deny:[]},y=new Set(o),m=(p.allow||[]).filter(x=>y.has(x)),C=(p.owner_allow||[]).filter(x=>y.has(x)),R=(p.deny||[]).filter(x=>y.has(x));o.forEach(x=>{!m.includes(x)&&!C.includes(x)&&!R.includes(x)&&R.push(x)});let M={allow:m,owner_allow:C,deny:R};JSON.stringify(M)!==JSON.stringify(p)&&r(M),m.length===o.length?l("all"):R.length===o.length?l("none"):l("custom")},[o,e]);let g=()=>{h.current=!0,r({allow:[...o],owner_allow:[],deny:[]}),l("all"),setTimeout(()=>{h.current=!1},0)},a=()=>{h.current=!0,r({allow:[],owner_allow:[],deny:[...o]}),l("none"),setTimeout(()=>{h.current=!1},0)},u=p=>e?.allow?.includes(p)?"allow":e?.owner_allow?.includes(p)?"owner_allow":"deny",b=(p,y)=>{h.current=!0;let m=new Set(e?.allow||[]),C=new Set(e?.owner_allow||[]),R=new Set(e?.deny||[]);m.delete(p),C.delete(p),R.delete(p),y==="allow"&&m.add(p),y==="owner_allow"&&C.add(p),y==="deny"&&R.add(p),r({allow:Array.from(m),owner_allow:Array.from(C),deny:Array.from(R)}),l("custom"),setTimeout(()=>{h.current=!1},0)};return o.length===0?fe(Ye,{children:[D(ze,{variant:"body2",color:"text.secondary",sx:{mb:1},children:n("modules.form.publicPolicies.fields.conditions.label")}),D(ze,{variant:"body2",color:"text.secondary",sx:{fontStyle:"italic"},children:n("modules.form.publicPolicies.fields.conditions.noFieldsAvailable")}),t&&D(ho,{error:!0,sx:{mt:1},children:t})]}):fe(Ye,{children:[D(ze,{variant:"body2",color:"text.secondary",sx:{mb:2},children:n("modules.form.publicPolicies.fields.conditions.label")}),fe(gr,{direction:"row",spacing:1,alignItems:"center",sx:{mb:c?3:1},children:[D(yo,{variant:s==="all"?"contained":"outlined",startIcon:D(Jt,{}),onClick:g,disabled:i,size:"small",sx:{minWidth:120,...s==="all"&&{backgroundColor:"#16a34a","&:hover":{backgroundColor:"#15803d"}}},children:n("modules.form.publicPolicies.fields.conditions.allFields")}),D(yo,{variant:s==="none"?"contained":"outlined",startIcon:D(Qt,{}),onClick:a,disabled:i,size:"small",sx:{minWidth:120,...s==="none"&&{backgroundColor:"#cf222e","&:hover":{backgroundColor:"#bc1f2c"}}},children:n("modules.form.publicPolicies.fields.conditions.noFields")}),D(Ye,{sx:{display:"flex",alignItems:"center",px:1.5,py:.35,borderRadius:"999px",backgroundColor:"#f3f4f6",border:"1px solid #d1d9e0"},children:D($t,{control:D(Kt,{size:"small",checked:c,onChange:()=>w(p=>!p),disabled:i,color:"primary",sx:{transform:"scale(1.15)",transformOrigin:"center",m:0}}),label:n("modules.form.publicPolicies.fields.conditions.customEdit"),labelPlacement:"end",sx:{ml:0,".MuiFormControlLabel-label":{fontSize:"0.75rem"}}})})]}),c&&fe(Ye,{ref:d,sx:{p:2,border:"1px solid #d1d9e0",borderRadius:1,backgroundColor:"#f6f8fa"},children:[D(ze,{variant:"body2",color:"text.secondary",sx:{mb:2},children:n("modules.form.publicPolicies.fields.conditions.help")}),D(gr,{spacing:1,children:o.map(p=>{let y=u(p);return fe(gr,{direction:"row",spacing:1,alignItems:"center",children:[D(ze,{variant:"body2",sx:{minWidth:100,fontFamily:"monospace"},children:p}),fe(Gt,{value:y,exclusive:!0,size:"small",children:[fe(mr,{value:"allow",onClick:()=>b(p,"allow"),disabled:i,sx:{px:2,color:y==="allow"?"#ffffff":"#6b7280",backgroundColor:y==="allow"?"#16a34a":"#f3f4f6",borderColor:y==="allow"?"#16a34a":"#d1d5db","&:hover":{backgroundColor:y==="allow"?"#15803d":"#e5e7eb",borderColor:y==="allow"?"#15803d":"#9ca3af"},"&.Mui-selected":{backgroundColor:"#16a34a",color:"#ffffff","&:hover":{backgroundColor:"#15803d"}}},children:[D(Yt,{sx:{fontSize:16,mr:.5}}),n("modules.form.publicPolicies.fields.conditions.states.allow")]}),D(mr,{value:"owner_allow",onClick:()=>b(p,"owner_allow"),disabled:i,sx:{px:2,color:y==="owner_allow"?"#ffffff":"#6b7280",backgroundColor:y==="owner_allow"?"#0ea5e9":"#f3f4f6",borderColor:y==="owner_allow"?"#0ea5e9":"#d1d5db","&:hover":{backgroundColor:y==="owner_allow"?"#0284c7":"#e5e7eb",borderColor:y==="owner_allow"?"#0284c7":"#9ca3af"},"&.Mui-selected":{backgroundColor:"#0ea5e9",color:"#ffffff","&:hover":{backgroundColor:"#0284c7"}}},children:n("modules.form.publicPolicies.fields.conditions.states.ownerAllow")}),fe(mr,{value:"deny",onClick:()=>b(p,"deny"),disabled:i,sx:{px:2,color:y==="deny"?"#ffffff":"#6b7280",backgroundColor:y==="deny"?"#dc2626":"#f3f4f6",borderColor:y==="deny"?"#dc2626":"#d1d5db","&:hover":{backgroundColor:y==="deny"?"#b91c1c":"#e5e7eb",borderColor:y==="deny"?"#b91c1c":"#9ca3af"},"&.Mui-selected":{backgroundColor:"#dc2626",color:"#ffffff","&:hover":{backgroundColor:"#b91c1c"}}},children:[D(Xt,{sx:{fontSize:16,mr:.5}}),n("modules.form.publicPolicies.fields.conditions.states.deny")]})]})]},p)})})]}),t&&D(ho,{error:!0,sx:{mt:1},children:t})]})},pr=Zt;import{jsx as z,jsxs as j}from"react/jsx-runtime";var mn=en(({policy:e,onChange:r,onRemove:o,availableFields:t,isSubmitting:i=!1,usedActions:n,error:s},l)=>{let{t:c}=rn(),w=new Set(Array.from(n||[]));w.delete(e.action);let d=uo.map(h=>({value:h,label:c(`modules.form.publicPolicies.fields.action.options.${h}`)}));return j(bo,{ref:l,sx:{p:3,border:"1px solid #d1d9e0",borderRadius:2,position:"relative",backgroundColor:"#ffffff"},children:[j(Pe,{sx:{display:"flex",justifyContent:"space-between",alignItems:"flex-start",mb:3},children:[z(Ae,{variant:"subtitle1",sx:{fontWeight:600,color:"#111418",fontSize:"1rem"},children:c("modules.form.publicPolicies.policyTitle")}),z(an,{onClick:o,size:"small",disabled:i,"aria-label":c("modules.form.publicPolicies.removePolicy"),sx:{color:"#656d76","&:hover":{color:"#cf222e",backgroundColor:"rgba(207, 34, 46, 0.1)"}},children:z(dn,{})})]}),j(Xe,{spacing:1,children:[z(Xe,{direction:{xs:"column",md:"row"},spacing:2,children:z(Pe,{sx:{flex:1,minWidth:200},children:j(on,{fullWidth:!0,children:[z(tn,{children:c("modules.form.publicPolicies.fields.action.label")}),z(nn,{value:e.action,label:c("modules.form.publicPolicies.fields.action.label"),disabled:i,onChange:h=>{let g=h.target.value,a={...e,action:g};g==="delete"?(a.permission="deny",delete a.fields):(a.fields={allow:[],owner_allow:[],deny:t},delete a.permission),r(a)},sx:{backgroundColor:"#ffffff","&:hover .MuiOutlinedInput-notchedOutline":{borderColor:"#8c959f"},"&.Mui-focused .MuiOutlinedInput-notchedOutline":{borderColor:"#0969da",borderWidth:2}},children:d.map(h=>{let g=w.has(h.value);return z(sn,{value:h.value,disabled:g,children:h.label},h.value)})}),s&&z(ln,{error:!0,children:s})]})})}),e.action==="delete"?j(Pe,{children:[z(Ae,{variant:"body2",color:"text.secondary",sx:{mb:2},children:c("modules.form.publicPolicies.fields.conditions.label")}),j(Xe,{direction:"row",spacing:1,sx:{mb:1},children:[z(fr,{variant:e.permission==="*"?"contained":"outlined",startIcon:z(un,{}),onClick:()=>r({...e,permission:"*"}),disabled:i,size:"small",sx:{minWidth:140,whiteSpace:"nowrap",...e.permission==="*"&&{backgroundColor:"#16a34a","&:hover":{backgroundColor:"#15803d"}}},children:c("modules.form.publicPolicies.fields.conditions.allFields")}),z(fr,{variant:e.permission==="owner"?"contained":"outlined",onClick:()=>r({...e,permission:"owner"}),disabled:i,size:"small",sx:{minWidth:140,whiteSpace:"nowrap",...e.permission==="owner"&&{backgroundColor:"#0ea5e9","&:hover":{backgroundColor:"#0284c7"}}},children:c("modules.form.publicPolicies.fields.conditions.states.ownerAllow")}),z(fr,{variant:e.permission==="deny"?"contained":"outlined",startIcon:z(gn,{}),onClick:()=>r({...e,permission:"deny"}),disabled:i,size:"small",sx:{minWidth:140,whiteSpace:"nowrap",...e.permission==="deny"&&{backgroundColor:"#cf222e","&:hover":{backgroundColor:"#bc1f2c"}}},children:c("modules.form.publicPolicies.fields.conditions.noFields")})]})]}):z(pr,{value:e.fields||{allow:[],owner_allow:[],deny:[]},onChange:h=>r({...e,fields:h}),availableFields:t,disabled:i}),z(bo,{variant:"outlined",sx:{p:2,backgroundColor:"#f9fafb"},children:e.action==="delete"?j(Ae,{variant:"body2",sx:{fontFamily:"monospace",color:"text.secondary"},children:[j(Pe,{component:"span",sx:{color:e.permission==="*"?"#16a34a":e.permission==="owner"?"#0ea5e9":"#dc2626"},children:[c("modules.form.publicPolicies.fields.conditions.states.allow"),":"]})," ",e.permission||"-"]}):j(Xe,{spacing:.5,divider:z(cn,{sx:{borderColor:"#e5e7eb"}}),children:[j(Ae,{variant:"body2",sx:{fontFamily:"monospace",color:"text.secondary"},children:[j(Pe,{component:"span",sx:{color:"#16a34a"},children:[c("modules.form.publicPolicies.fields.conditions.states.allow"),":"]})," ",(e?.fields?.allow||[]).join(", ")||"-"]}),j(Ae,{variant:"body2",sx:{fontFamily:"monospace",color:"text.secondary"},children:[j(Pe,{component:"span",sx:{color:"#0ea5e9"},children:[c("modules.form.publicPolicies.fields.conditions.states.ownerAllow"),":"]})," ",(e?.fields?.owner_allow||[]).join(", ")||"-"]}),j(Ae,{variant:"body2",sx:{fontFamily:"monospace",color:"text.secondary"},children:[j(Pe,{component:"span",sx:{color:"#dc2626"},children:[c("modules.form.publicPolicies.fields.conditions.states.deny"),":"]})," ",(e?.fields?.deny||[]).join(", ")||"-"]})]})})]})]})}),yr=mn;import{Fragment as Pn,jsx as ie,jsxs as Qe}from"react/jsx-runtime";var xn=()=>{let e=globalThis?.crypto;return e&&typeof e.randomUUID=="function"?e.randomUUID():`${Date.now()}-${Math.random().toString(16).slice(2)}`},Cn=({policies:e,onChange:r,availableFields:o,errors:t,isSubmitting:i=!1})=>{let{t:n}=fn(),s=pn({}),l=new Set((e||[]).map(u=>u.action).filter(Boolean)),c=go.filter(u=>!l.has(u)),w=c.length>0,d=()=>{let u=c[0]||"create",b={id:xn(),action:u};u==="delete"?b.permission="deny":b.fields={allow:[],owner_allow:[],deny:o};let p=[...e||[],b];r(p),setTimeout(()=>{let y=p.length-1,m=s.current[y];m&&m.scrollIntoView({behavior:"smooth",block:"center"})},100)},h=u=>{let b=[...e];b.splice(u,1),r(b)},g=(()=>{if(!t)return null;if(typeof t=="string")return t;let u=t._error;return typeof u=="string"?u:null})(),a=new Set((e||[]).map(u=>u.action));return Qe(Pn,{children:[ie(bn,{sx:{borderColor:"#e0e4e7"}}),Qe(Je,{children:[ie(Je,{display:"flex",justifyContent:"space-between",alignItems:"center",mb:3,children:Qe(Je,{children:[ie(wo,{variant:"h6",sx:{fontWeight:600,color:"#111418",mb:1},children:n("modules.form.publicPolicies.title")}),ie(wo,{variant:"body2",color:"text.secondary",sx:{fontSize:"0.875rem"},children:n("modules.form.publicPolicies.description")})]})}),g&&ie(xo,{severity:"error",sx:{mb:3},children:g}),Qe(hn,{spacing:3,children:[(e||[]).length===0?ie(xo,{severity:"info",children:n("modules.form.publicPolicies.noPolicies")}):e.map((u,b)=>ie(yr,{ref:p=>{s.current[b]=p},policy:u,onChange:p=>{let y=[...e];y[b]=p,r(y)},onRemove:()=>h(b),availableFields:o,isSubmitting:i,usedActions:a,error:typeof t=="object"&&t&&u.id in t?t[u.id]:void 0},u.id)),w&&ie(Je,{children:ie(yn,{type:"button",variant:"outlined",startIcon:ie(wn,{}),onClick:d,disabled:i,sx:{borderColor:"#d0d7de",color:"#656d76","&:hover":{borderColor:"#8c959f",backgroundColor:"transparent"}},children:n("modules.form.publicPolicies.addPolicy")})})]})]})]})},wa=Cn;import{useState as hr}from"react";import{Button as Ze,TextField as Co,Box as Fe,Alert as Ue,Typography as ye,CircularProgress as br}from"@mui/material";import{jsx as N,jsxs as de}from"react/jsx-runtime";function Ra(){let[e,r]=hr(""),[o,t]=hr(""),[i,n]=hr(!1),{isAuthenticated:s,isLoading:l,error:c,login:w,logout:d,refreshTokens:h,clearError:g,isExpiringSoon:a,expiresIn:u}=ge(),b=async m=>{if(m.preventDefault(),!e||!o)return;(await w(e,o)).success&&(r(""),t(""),n(!1))},p=async()=>{await d()},y=async()=>{await h()};return s?de(Fe,{sx:{maxWidth:600,mx:"auto",p:3},children:[N(ye,{variant:"h4",gutterBottom:!0,children:"Welcome! \u{1F389}"}),N(Ue,{severity:"success",sx:{mb:3},children:"You are successfully logged in with Refresh Token Pattern enabled"}),de(Fe,{sx:{mb:3,p:2,bgcolor:"background.paper",border:1,borderColor:"divider",borderRadius:1},children:[N(ye,{variant:"h6",gutterBottom:!0,children:"Token Status"}),de(ye,{variant:"body2",color:"text.secondary",children:["Access Token expires in: ",Math.round(u/1e3/60)," minutes"]}),a&&N(Ue,{severity:"warning",sx:{mt:1},children:"Token expires soon - automatic refresh will happen"})]}),de(Fe,{sx:{display:"flex",gap:2,flexWrap:"wrap"},children:[N(Ze,{variant:"contained",onClick:y,disabled:l,startIcon:l?N(br,{size:16}):null,children:"Refresh Tokens"}),N(Ze,{variant:"outlined",color:"error",onClick:p,disabled:l,children:"Logout"})]}),c&&N(Ue,{severity:"error",sx:{mt:2},onClose:g,children:c})]}):de(Fe,{sx:{maxWidth:400,mx:"auto",p:3},children:[N(ye,{variant:"h4",gutterBottom:!0,align:"center",children:"Login with Refresh Tokens"}),N(Ue,{severity:"info",sx:{mb:3},children:"This demo shows the new Refresh Token Pattern with automatic session management"}),i?de("form",{onSubmit:b,children:[N(Co,{fullWidth:!0,label:"Email",type:"email",value:e,onChange:m=>r(m.target.value),margin:"normal",required:!0,autoComplete:"email"}),N(Co,{fullWidth:!0,label:"Password",type:"password",value:o,onChange:m=>t(m.target.value),margin:"normal",required:!0,autoComplete:"current-password"}),N(Ze,{type:"submit",fullWidth:!0,variant:"contained",size:"large",disabled:l,startIcon:l?N(br,{size:16}):null,sx:{mt:3,mb:2},children:l?"Logging in...":"Login"})]}):N(Ze,{fullWidth:!0,variant:"contained",size:"large",onClick:()=>n(!0),sx:{mt:2},children:"Show Login Form"}),c&&N(Ue,{severity:"error",sx:{mt:2},onClose:g,children:c})]})}function Ia(){let{isAuthenticated:e,isLoading:r,isExpiringSoon:o,expiresIn:t}=ge();return r?de(Fe,{sx:{display:"flex",alignItems:"center",gap:1},children:[N(br,{size:16}),N(ye,{variant:"caption",children:"Loading session..."})]}):e?de(Fe,{children:[N(ye,{variant:"caption",color:"success.main",children:"\u2713 Authenticated"}),o&&de(ye,{variant:"caption",color:"warning.main",display:"block",children:["\u26A0 Token expires in ",Math.round(t/1e3/60)," min"]})]}):N(ye,{variant:"caption",color:"text.secondary",children:"Not logged in"})}import vn from"@mui/material/TextField";import Tn from"@mui/material/CircularProgress";import Po from"@mui/material/InputAdornment";import En from"@mui/material/IconButton";import Rn from"@mui/icons-material/Refresh";import{jsx as he}from"react/jsx-runtime";var In=e=>e.replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,"").replace(/javascript:/gi,"").replace(/on\w+\s*=/gi,"").replace(/<iframe\b[^<]*(?:(?!<\/iframe>)<[^<]*)*<\/iframe>/gi,""),Sn=({html:e})=>he("span",{dangerouslySetInnerHTML:{__html:In(e)}}),Na=({config:e,value:r,onChange:o,label:t,error:i=!1,helperText:n,readOnly:s=!1,disabled:l=!1})=>{let{value:c,loading:w,error:d,regenerate:h}=Sr(e,{autoFetch:!r,onSuccess:y=>{o?.(y)}}),g=r||c,a=i||!!d,u=d||n,b=a&&u&&(u.toLowerCase().includes("duplicate")||u.toLowerCase().includes("duplicado")||u.toLowerCase().includes("duplicada")||u.toLowerCase().includes("unique")||u.toLowerCase().includes("\xFAnico")||u.toLowerCase().includes("unico")||u.toLowerCase().includes("\xFAnica")||u.toLowerCase().includes("unica")||u.toLowerCase().includes("already exists")||u.toLowerCase().includes("ya existe")||u.toLowerCase().includes("e11000"));return he(vn,{label:t,fullWidth:!0,value:g,error:a,helperText:u?he(Sn,{html:u}):" ",disabled:l,InputProps:{readOnly:!0,startAdornment:w?he(Po,{position:"start",children:he(Tn,{size:20})}):void 0,endAdornment:b&&!w?he(Po,{position:"end",children:he(En,{edge:"end",onClick:async()=>{!l&&!w&&await h()},disabled:l,size:"small",color:"error","aria-label":"regenerar c\xF3digo",title:"Regenerar c\xF3digo",children:he(Rn,{})})}):void 0}})};import vo,{useCallback as Me,useRef as To,useState as Ro}from"react";import ve from"@mui/material/Box";import Te from"@mui/material/Typography";import Eo from"@mui/material/IconButton";import kn from"@mui/material/LinearProgress";import wr from"@mui/material/CircularProgress";import Ln from"@mui/material/Chip";import An from"@mui/material/Paper";import Fn from"@mui/material/List";import _n from"@mui/material/ListItem";import On from"@mui/material/ListItemText";import Bn from"@mui/material/ListItemSecondaryAction";import Nn from"@mui/material/FormHelperText";import Dn from"@mui/icons-material/CloudUpload";import zn from"@mui/icons-material/InsertDriveFile";import Un from"@mui/icons-material/Image";import Mn from"@mui/icons-material/PictureAsPdf";import Vn from"@mui/icons-material/Delete";import Wn from"@mui/icons-material/Refresh";import Hn from"@mui/icons-material/CheckCircle";import qn from"@mui/icons-material/Error";import al from"@mui/icons-material/BrokenImage";import{jsx as E,jsxs as be}from"react/jsx-runtime";var Io=e=>{if(e===0)return"0 B";let r=1024,o=["B","KB","MB","GB"],t=Math.floor(Math.log(e)/Math.log(r));return`${parseFloat((e/Math.pow(r,t)).toFixed(1))} ${o[t]}`},jn=e=>e.startsWith("image/")?E(Un,{color:"primary"}):e==="application/pdf"?E(Mn,{color:"error"}):E(zn,{color:"action"}),$n=e=>{switch(e){case"completed":return E(Hn,{color:"success",fontSize:"small"});case"error":return E(qn,{color:"error",fontSize:"small"});case"uploading":case"pending":return E(wr,{size:16});case"removing":return E(wr,{size:16,color:"error"});default:return null}},Kn=({file:e,baseUrl:r,disabled:o,onRemove:t,onRetry:i})=>{let[n,s]=Ro(!1),l=!o&&e.status!=="uploading"&&e.status!=="removing",c=!o&&e.status==="error"&&e.file,w=e.contentType.startsWith("image/"),d=e.visibility==="public"||e.filePath?.startsWith("public/")||e.filePath?.startsWith(r),g=!e.filePath||!d?null:e.filePath.startsWith("http://")||e.filePath.startsWith("https://")||e.filePath.startsWith(r)?e.filePath:`${r}${e.filePath}`,a=e.status==="completed"&&g,u=()=>w&&a&&!n?E(ve,{component:a?"a":"div",href:g||void 0,target:"_blank",rel:"noopener noreferrer",sx:{width:48,height:48,borderRadius:1,overflow:"hidden",display:"flex",alignItems:"center",justifyContent:"center",bgcolor:"grey.100",border:"1px solid",borderColor:"divider",cursor:a?"pointer":"default",transition:"all 0.2s ease",flexShrink:0,"&:hover":a?{borderColor:"primary.main",transform:"scale(1.05)"}:{}},children:E("img",{src:g,alt:e.name,style:{width:"100%",height:"100%",objectFit:"cover"},onError:()=>s(!0)})}):E(ve,{component:a?"a":"div",href:g||void 0,target:"_blank",rel:"noopener noreferrer",sx:{width:48,height:48,borderRadius:1,display:"flex",alignItems:"center",justifyContent:"center",bgcolor:"grey.50",border:"1px solid",borderColor:"divider",cursor:a?"pointer":"default",transition:"all 0.2s ease",flexShrink:0,textDecoration:"none","&:hover":a?{borderColor:"primary.main",bgcolor:"action.hover"}:{}},children:jn(e.contentType)});return be(_n,{sx:{borderRadius:1,mb:.5,bgcolor:e.status==="error"?"error.lighter":"background.paper",border:"1px solid",borderColor:e.status==="error"?"error.light":"divider",gap:1.5},children:[u(),E(On,{primary:be(ve,{sx:{display:"flex",alignItems:"center",gap:1},children:[E(Te,{variant:"body2",noWrap:!0,sx:{maxWidth:200,overflow:"hidden",textOverflow:"ellipsis"},children:e.name}),$n(e.status)]}),secondary:be(ve,{children:[e.size>0&&E(Te,{variant:"caption",color:"text.secondary",children:Io(e.size)}),e.status==="uploading"&&E(kn,{variant:"determinate",value:e.progress,sx:{mt:.5,height:4,borderRadius:2}}),e.status==="error"&&e.errorMessage&&E(Te,{variant:"caption",color:"error",display:"block",children:e.errorMessage}),a&&E(Te,{variant:"caption",color:"primary",display:"block",children:w?"Click thumbnail to view":"Click to download"})]})}),be(Bn,{children:[c&&E(Eo,{edge:"end",size:"small",onClick:()=>i(e.id),color:"primary",title:"Retry",children:E(Wn,{fontSize:"small"})}),l&&E(Eo,{edge:"end",size:"small",onClick:()=>t(e.id),color:"error",title:"Delete",children:E(Vn,{fontSize:"small"})})]})]})};var cl=({label:e,accept:r,maxFileSize:o=10*1024*1024,multiple:t=!1,maxFiles:i,minFiles:n=0,required:s=!1,disabled:l=!1,error:c=!1,helperText:w,onChange:d,onValidation:h,initialFiles:g,placeholder:a,showFileList:u=!0,visibility:b="private",showPreview:p=!0,baseUrl:y})=>{let m=To(null),[C,R]=Ro(!1),M=t?i:1,x=s?Math.max(n,1):n,f={acceptedTypes:r,maxFileSize:o,maxFiles:M,minFiles:x,visibility:b,onFilesChange:k=>{let ee=k.filter(xe=>xe.status==="completed"&&xe.filePath).map(xe=>{let Re=xe.filePath;return Re.startsWith(y)||Re.startsWith("http://")||Re.startsWith("https://")?Re:y?`${y}${Re}`:Re});d?.(ee)}},{files:P,isUploading:L,addFiles:_,removeFile:ae,retryUpload:we,isValid:te,validationError:ue,initializeFiles:A,isTouched:V,markAsTouched:F,getPreviewUrl:Ee}=kr(f),I=To(!1);vo.useEffect(()=>{g&&g.length>0&&!I.current&&(I.current=!0,A(g))},[g,A]),vo.useEffect(()=>{h?.(te,ue)},[te,ue,h]);let H=Me(k=>{F();let ee=k.target.files;ee&&ee.length>0&&_(ee),m.current&&(m.current.value="")},[_,F]),v=Me(()=>{l||(F(),m.current?.click())},[l,F]),S=Me(k=>{k.preventDefault(),k.stopPropagation(),l||R(!0)},[l]),O=Me(k=>{k.preventDefault(),k.stopPropagation(),R(!1)},[]),q=Me(k=>{if(k.preventDefault(),k.stopPropagation(),R(!1),l)return;F();let ee=k.dataTransfer.files;ee&&ee.length>0&&_(ee)},[l,_,F]),G=r?.join(",")||"",Y=!l&&(t||P.length===0),le=c||V&&!te,Cr=w||(V?ue:null);return be(ve,{sx:{width:"100%"},children:[e&&be(Te,{variant:"body2",sx:{mb:1,fontWeight:500,color:le?"error.main":"text.primary"},children:[e,s&&E("span",{style:{color:"red"},children:" *"})]}),E("input",{ref:m,type:"file",accept:G,multiple:t,onChange:H,disabled:l,style:{display:"none"}}),Y&&be(An,{variant:"outlined",onClick:v,onDragOver:S,onDragLeave:O,onDrop:q,sx:{p:3,textAlign:"center",cursor:l?"not-allowed":"pointer",borderStyle:"dashed",borderWidth:2,borderColor:C?"primary.main":le?"error.main":"divider",bgcolor:C?"primary.lighter":l?"action.disabledBackground":"background.paper",transition:"all 0.2s ease","&:hover":l?{}:{borderColor:"primary.main",bgcolor:"action.hover"}},children:[E(Dn,{sx:{fontSize:48,color:C?"primary.main":l?"action.disabled":"action.active",mb:1}}),E(Te,{variant:"body2",color:l?"text.disabled":"text.secondary",children:(()=>{if(a)return a;let k=[];if(C)return"Drop file here";if(k.push("Drag files here or click to select"),r&&r.length>0){let ee=r.map(xe=>xe.split("/")[1]?.toUpperCase()||xe).join(", ");k.push(`Allowed types: ${ee}`)}return o&&k.push(`Max ${Io(o)} per file`),M!==void 0&&t&&k.push(`Max ${M} files`),k[0]})()}),r&&r.length>0&&!C&&E(ve,{sx:{mt:1,display:"flex",gap:.5,justifyContent:"center",flexWrap:"wrap"},children:r.map(k=>E(Ln,{label:k.split("/")[1]?.toUpperCase()||k,size:"small",variant:"outlined",sx:{fontSize:"0.7rem"}},k))})]}),u&&P.length>0&&E(Fn,{dense:!0,sx:{mt:1,p:0},children:P.map(k=>E(Kn,{file:k,baseUrl:y,disabled:l,onRemove:ae,onRetry:we},k.id))}),L&&be(ve,{sx:{display:"flex",alignItems:"center",gap:1,mt:1},children:[E(wr,{size:16}),E(Te,{variant:"caption",color:"text.secondary",children:"Uploading files..."})]}),Cr&&E(Nn,{error:le,sx:{mt:.5},children:Cr})]})};import{useCallback as Gn,useRef as Yn,useEffect as Xn}from"react";import So from"@mui/material/Box";import ko from"@mui/material/Typography";import Lo from"@mui/material/FormHelperText";import{MDXEditor as Jn,headingsPlugin as Qn,listsPlugin as Zn,quotePlugin as es,thematicBreakPlugin as rs,markdownShortcutPlugin as os,linkPlugin as ts,linkDialogPlugin as ns,tablePlugin as ss,toolbarPlugin as is,UndoRedo as as,BoldItalicUnderlineToggles as ls,BlockTypeSelect as cs,CreateLink as ds,InsertTable as us,ListsToggle as gs,Separator as er}from"@mdxeditor/editor";import"@mdxeditor/editor/style.css";import{Fragment as ms,jsx as $,jsxs as xr}from"react/jsx-runtime";var wl=({label:e,value:r="",onChange:o,required:t=!1,disabled:i=!1,error:n=!1,helperText:s,placeholder:l="Write here...",minHeight:c=200,maxHeight:w=500})=>{let d=Yn(null);Xn(()=>{d.current&&d.current.getMarkdown()!==r&&d.current.setMarkdown(r||"")},[r]);let h=Gn(g=>{o?.(g)},[o]);return xr(So,{sx:{width:"100%"},children:[e&&xr(ko,{component:"label",sx:{display:"block",mb:.5,fontSize:"0.875rem",fontWeight:500,color:n?"error.main":"text.primary"},children:[e,t&&$(ko,{component:"span",color:"error.main",sx:{ml:.5},children:"*"})]}),$(So,{sx:{border:1,borderColor:n?"error.main":"divider",borderRadius:1,overflow:"hidden",opacity:i?.6:1,pointerEvents:i?"none":"auto","& .mdxeditor":{minHeight:c,maxHeight:w,overflow:"auto"},"& .mdxeditor-toolbar":{borderBottom:1,borderColor:"divider",backgroundColor:"background.default"},"& .mdxeditor-root-contenteditable":{padding:2,minHeight:c-50}},children:$(Jn,{ref:d,markdown:r||"",onChange:h,placeholder:l,readOnly:i,plugins:[Qn(),Zn(),es(),rs(),os(),ts(),ns(),ss(),is({toolbarContents:()=>xr(ms,{children:[$(as,{}),$(er,{}),$(ls,{}),$(er,{}),$(cs,{}),$(er,{}),$(gs,{}),$(er,{}),$(ds,{}),$(us,{})]})})]})}),s&&$(Lo,{error:n,sx:{mx:0,mt:.5},children:s}),!s&&$(Lo,{sx:{mx:0,mt:.5},children:"\xA0"})]})};export{ce as a,fs as b,ys as c,rr as d,We as e,Rs as f,Nr as g,Bi as h,Ht as i,uo as j,go as k,wa as l,Ra as m,Ia as n,Na as o,cl as p,wl as q};
|