@nocios/crudify-ui 4.4.28 → 4.4.30
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/{CrudiaFileField-892NRdL9.d.ts → CrudiaFileField-CXyBfgOd.d.ts} +12 -2
- package/dist/{CrudiaFileField-wOx3H54i.d.mts → CrudiaFileField-D5zDp_Y1.d.mts} +12 -2
- package/dist/chunk-IZD5WNI4.mjs +1 -0
- package/dist/{chunk-KXBLNQ5Q.js → chunk-M2BIAQ3V.js} +1 -1
- package/dist/chunk-MMFYNCPI.js +1 -0
- package/dist/{chunk-66E5Q5BA.mjs → chunk-P4SZ3U4U.mjs} +1 -1
- package/dist/chunk-PSZ2DSVH.js +1 -0
- package/dist/chunk-ZSP7TBON.mjs +1 -0
- package/dist/components.d.mts +1 -1
- package/dist/components.d.ts +1 -1
- package/dist/components.js +1 -1
- package/dist/components.mjs +1 -1
- package/dist/hooks.d.mts +1 -1
- package/dist/hooks.d.ts +1 -1
- package/dist/hooks.js +1 -1
- package/dist/hooks.mjs +1 -1
- package/dist/{index-DP2vLBQU.d.ts → index-BicpdTC_.d.ts} +26 -4
- package/dist/{index-B0DVORoA.d.mts → index-wi46iw-x.d.mts} +26 -4
- package/dist/index.d.mts +4 -4
- package/dist/index.d.ts +4 -4
- package/dist/index.js +2 -2
- package/dist/index.mjs +2 -2
- package/package.json +2 -2
- package/dist/chunk-4E2PRDUC.mjs +0 -1
- package/dist/chunk-ACJBO4GO.mjs +0 -1
- package/dist/chunk-IXDCGL4K.js +0 -1
- package/dist/chunk-QXYEAMMD.js +0 -1
|
@@ -167,12 +167,12 @@ interface CrudiaFileFieldProps {
|
|
|
167
167
|
helperText?: string;
|
|
168
168
|
/**
|
|
169
169
|
* Callback cuando cambian los filePaths de archivos completados
|
|
170
|
-
* Los filePaths son rutas relativas
|
|
170
|
+
* Los filePaths son rutas relativas con visibility (public/... o private/...)
|
|
171
171
|
*/
|
|
172
172
|
onChange?: (filePaths: string[]) => void;
|
|
173
173
|
/** Callback cuando se valida el campo */
|
|
174
174
|
onValidation?: (isValid: boolean, error: string | null) => void;
|
|
175
|
-
/** Archivos existentes (para edición) - usar filePath (ruta relativa
|
|
175
|
+
/** Archivos existentes (para edición) - usar filePath (ruta relativa con visibility) */
|
|
176
176
|
initialFiles?: Array<{
|
|
177
177
|
filePath: string;
|
|
178
178
|
name: string;
|
|
@@ -183,6 +183,16 @@ interface CrudiaFileFieldProps {
|
|
|
183
183
|
placeholder?: string;
|
|
184
184
|
/** Mostrar lista de archivos */
|
|
185
185
|
showFileList?: boolean;
|
|
186
|
+
/**
|
|
187
|
+
* Visibilidad de los archivos subidos
|
|
188
|
+
* @default "private"
|
|
189
|
+
*/
|
|
190
|
+
visibility?: "public" | "private";
|
|
191
|
+
/**
|
|
192
|
+
* Mostrar preview de imágenes
|
|
193
|
+
* @default true para imágenes
|
|
194
|
+
*/
|
|
195
|
+
showPreview?: boolean;
|
|
186
196
|
}
|
|
187
197
|
/**
|
|
188
198
|
* Componente principal de campo de archivo
|
|
@@ -167,12 +167,12 @@ interface CrudiaFileFieldProps {
|
|
|
167
167
|
helperText?: string;
|
|
168
168
|
/**
|
|
169
169
|
* Callback cuando cambian los filePaths de archivos completados
|
|
170
|
-
* Los filePaths son rutas relativas
|
|
170
|
+
* Los filePaths son rutas relativas con visibility (public/... o private/...)
|
|
171
171
|
*/
|
|
172
172
|
onChange?: (filePaths: string[]) => void;
|
|
173
173
|
/** Callback cuando se valida el campo */
|
|
174
174
|
onValidation?: (isValid: boolean, error: string | null) => void;
|
|
175
|
-
/** Archivos existentes (para edición) - usar filePath (ruta relativa
|
|
175
|
+
/** Archivos existentes (para edición) - usar filePath (ruta relativa con visibility) */
|
|
176
176
|
initialFiles?: Array<{
|
|
177
177
|
filePath: string;
|
|
178
178
|
name: string;
|
|
@@ -183,6 +183,16 @@ interface CrudiaFileFieldProps {
|
|
|
183
183
|
placeholder?: string;
|
|
184
184
|
/** Mostrar lista de archivos */
|
|
185
185
|
showFileList?: boolean;
|
|
186
|
+
/**
|
|
187
|
+
* Visibilidad de los archivos subidos
|
|
188
|
+
* @default "private"
|
|
189
|
+
*/
|
|
190
|
+
visibility?: "public" | "private";
|
|
191
|
+
/**
|
|
192
|
+
* Mostrar preview de imágenes
|
|
193
|
+
* @default true para imágenes
|
|
194
|
+
*/
|
|
195
|
+
showPreview?: boolean;
|
|
186
196
|
}
|
|
187
197
|
/**
|
|
188
198
|
* Componente principal de campo de archivo
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{b as Po,c as te,h as xo,j as de,l as vo,m as To,p as Eo}from"./chunk-ZSP7TBON.mjs";import{g as G}from"./chunk-BJ6PIVZR.mjs";import{a as bo,b as wo,g as Co}from"./chunk-6GPSBDW6.mjs";var le={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"}},Vn=()=>Object.keys(le),Wn=e=>le[e]||le.es;import ze from"@nocios/crudify-browser";var Ro="crudify_translations_",Cr=3600*1e3;function Io(e){let o=0;for(let r=0;r<e.length;r++){let t=e.charCodeAt(r);o=(o<<5)-o+t,o=o&o}return Math.abs(o).toString(36)}var Xe=class e{constructor(){this.enableDebug=!1;this.initializationPromise=null;this.isInitialized=!1}static getInstance(){return e.instance||(e.instance=new e),e.instance}setDebug(o){this.enableDebug=o}async ensureCrudifyInitialized(o,r){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=ze.getTokenData();if(t&&t.endpoint){this.enableDebug&&console.log("[TranslationService] Crudify already initialized"),this.isInitialized=!0;return}ze.config(r);let a=await ze.init(o,this.enableDebug?"debug":"none");if(a.success===!1)throw new Error(`Failed to initialize crudify: ${JSON.stringify(a.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(o){let{apiKey:r,featureKeys:t,crudifyEnv:a="stg",urlTranslations:n}=o;this.enableDebug&&console.log("[TranslationService] fetchTranslations called with:",{apiKeyHash:Io(r),crudifyEnv:a,featureKeys:t,hasUrlTranslations:!!n});let s=this.getFromCache(r),i=s?this.isCacheExpired(s):!0;if(s&&!i)return this.enableDebug&&console.log("[TranslationService] Using cached translations"),this.mergeWithUrlTranslations(s.data.translations,n);try{await this.ensureCrudifyInitialized(r,a)}catch(d){return console.error("[TranslationService] \u274C Failed to initialize crudify:",d),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 d=await this.fetchFromAPI(t);this.hasDataChanged(s,d)||!s?this.saveToCache(r,d):this.refreshCacheTimestamp(r);let m=this.mergeWithUrlTranslations(d.translations,n);return this.enableDebug&&console.log("[TranslationService] Translations loaded:",{languages:Object.keys(m),keysCount:m[Object.keys(m)[0]]?Object.keys(m[Object.keys(m)[0]]).length:0}),m}catch(d){return console.error("[TranslationService] \u274C API fetch failed:",d),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(o){let r=await ze.getTranslation(o);if(!r.success)throw new Error(`Crudify API error: ${r.errors?JSON.stringify(r.errors):"Unknown error"}`);if(!r.data)throw new Error("No translation data in response");return r.data}mergeWithUrlTranslations(o,r){if(!r||Object.keys(r).length===0)return o;let t={};return Object.keys(o).forEach(a=>{t[a]={...o[a],...r}}),t}hasDataChanged(o,r){if(!o||o.data.timestamp!==r.timestamp)return!0;let t=this.hashData(r.translations);return o.dataHash!==t}hashData(o){let r=JSON.stringify(o),t=0;for(let a=0;a<r.length;a++){let n=r.charCodeAt(a);t=(t<<5)-t+n,t=t&t}return t.toString(36)}saveToCache(o,r){try{let t=this.getCacheKey(o),a={data:r,cachedAt:Date.now(),dataHash:this.hashData(r.translations)};localStorage.setItem(t,JSON.stringify(a)),this.enableDebug&&console.log("[TranslationService] Saved to cache:",t)}catch(t){console.error("[TranslationService] Failed to save cache:",t)}}getFromCache(o){try{let r=this.getCacheKey(o),t=localStorage.getItem(r);return t?JSON.parse(t):null}catch(r){return console.error("[TranslationService] Failed to read cache:",r),null}}refreshCacheTimestamp(o){try{let r=this.getFromCache(o);if(r){r.cachedAt=Date.now();let t=this.getCacheKey(o);localStorage.setItem(t,JSON.stringify(r))}}catch(r){console.error("[TranslationService] Failed to refresh cache timestamp:",r)}}isCacheExpired(o){return Date.now()-o.cachedAt>Cr}hasValidCache(o){let r=this.getFromCache(o);return r?!this.isCacheExpired(r):!1}getCacheKey(o){return`${Ro}${Io(o)}`}getCriticalTranslationsOnly(){return le}invalidateCache(o){let r=this.getCacheKey(o);localStorage.removeItem(r),this.enableDebug&&console.log("[TranslationService] Cache invalidated:",r)}async prefetchTranslations(o){try{await this.fetchTranslations(o),this.enableDebug&&console.log("[TranslationService] Prefetch completed")}catch(r){console.error("[TranslationService] Prefetch failed:",r)}}clearAllCaches(){try{let r=Object.keys(localStorage).filter(t=>t.startsWith(Ro));r.forEach(t=>localStorage.removeItem(t)),this.enableDebug&&console.log(`[TranslationService] Cleared ${r.length} cache entries`)}catch(o){console.error("[TranslationService] Failed to clear caches:",o)}}},Me=Xe.getInstance();import{createContext as xr,useContext as vr,useEffect as ko,useState as ve,useMemo as So,useCallback as Tr}from"react";import{Fragment as Rr,jsx as We}from"react/jsx-runtime";var Ve=null,Ze=!1,Ao=xr(null);function Lo(e,o,r){return{...e,...o,...r||{}}}function Er(e,o,r,t,a){ko(()=>{if(!t||!e||!o)return;let n=r||typeof window<"u"&&window.i18next||typeof window<"u"&&window.i18n;if(!n||!n.addResourceBundle){a&&console.log("[TranslationsProvider] i18next not found, skipping auto-sync");return}a&&console.log("[TranslationsProvider] Auto-syncing translations with i18next",{languages:Object.keys(e),currentLanguage:o}),Object.keys(e).forEach(s=>{e[s]&&Object.keys(e[s]).length>0&&(n.addResourceBundle(s,"translation",e[s],!0,!0),a&&console.log(`[TranslationsProvider] Synced ${Object.keys(e[s]).length} keys for language: ${s}`))}),n.language!==o&&(n.changeLanguage(o),a&&console.log(`[TranslationsProvider] Changed i18next language to: ${o}`))},[e,o,r,t,a])}var Xn=({children:e,apiKey:o,crudifyEnv:r="prod",featureKeys:t,language:a="es",devTranslations:n,translationUrl:s,enableDebug:i=!1,skipAutoInit:d=!0,autoSyncI18n:w=!0,i18nInstance:m,loadingFallback:h,waitForInitialLoad:p=!0})=>{let l=So(()=>wo({publicApiKey:o,env:r,featureKeys:t,enableDebug:i}),[o,r,t,i]),c=l.publicApiKey||"",b=l.env||r||"prod",f=l.featureKeys||t,[y,u]=ve({}),[C,E]=ve(!0),[j,P]=ve(!0),[g,v]=ve(null),[L,B]=ve(void 0),[ae,ie]=ve(!1),re=Tr(async()=>{if(!c){i&&console.log("[TranslationsProvider] No apiKey - skipping translation fetch"),E(!1),P(!1);return}if(ae){i&&console.log("[TranslationsProvider] Skipping reload - using fallback translations");return}if(Me.hasValidCache(c)&&j&&(i&&console.log("[TranslationsProvider] Valid cache found - not blocking initial render"),P(!1)),Ze&&Ve){i&&console.log("[TranslationsProvider] Fetch already in progress, waiting for existing promise");try{let R=await Ve;u(R),E(!1);return}catch{i&&console.warn("[TranslationsProvider] Global fetch failed, retrying")}}Ze=!0,E(!0),v(null);let M;if(s)try{i&&console.log(`[TranslationsProvider] Fetching translations from URL: ${s}`);let R=await fetch(s);if(!R.ok)throw new Error(`Failed to fetch translations: ${R.statusText}`);M=await R.json(),B(M),i&&console.log("[TranslationsProvider] URL translations loaded:",{keysCount:M?Object.keys(M).length:0})}catch(R){console.error("[TranslationsProvider] Failed to load URL translations:",R),M=void 0,B(void 0)}let he=(async()=>{try{Me.setDebug(i);let R=await Me.fetchTranslations({apiKey:c,crudifyEnv:b,featureKeys:f,urlTranslations:M}),W={};return Object.keys(R).forEach(x=>{let I=le[x]||{},F=R[x]||{};W[x]=Lo(I,F,n)}),i&&console.log("[TranslationsProvider] Loaded translations:",{languages:Object.keys(W),keysCount:Object.keys(W[a]||{}).length}),W}catch(R){console.error("[TranslationsProvider] Failed to load:",R),v(R.message),ie(!0);let W={};return Object.keys(le).forEach(x=>{let I=le[x],F=M||L||{};W[x]=Lo(I,F,n)}),i&&console.log("[TranslationsProvider] Using fallback translations (critical + URL)"),W}})();Ve=he;try{let R=await he;u(R)}finally{E(!1),P(!1),Ze=!1,setTimeout(()=>{Ve=null},1e3)}},[c,b,f,s,n,i,a,ae]);ko(()=>{re();let _=setInterval(re,3600*1e3);return()=>clearInterval(_)},[re]);let Ce=So(()=>(_,M)=>{let R=(y[a]||{})[_];if(!R){let W=Object.keys(y);for(let x of W)if(y[x][_]){R=y[x][_];break}}return R||(i&&console.warn(`[TranslationsProvider] Missing translation: "${_}"`),R=_),M&&typeof R=="string"&&Object.entries(M).forEach(([W,x])=>{let I=new RegExp(`{{${W}}}`,"g");R=R.replace(I,String(x))}),R},[y,a,i]);Er(y,a,m,w,i);let A={t:Ce,language:a,availableLanguages:Object.keys(y),translations:y,isLoading:C,error:g,refreshTranslations:re};return c?p&&j&&C?h||We("div",{style:{display:"flex",justifyContent:"center",alignItems:"center",height:"100vh"},children:We("div",{children:"Loading translations..."})}):We(Ao.Provider,{value:A,children:e}):(i&&console.warn("[TranslationsProvider] No API key available. Skipping translations. Provide apiKey via props or ensure cookies are set by Lambda."),We(Rr,{children:e}))},_o=()=>{let e=vr(Ao);if(!e)throw new Error("useTranslations must be used within TranslationsProvider");return e};import{Box as ut,Typography as mt}from"@mui/material";import{createContext as Sr,useContext as Lr,useMemo as oo}from"react";import{useState as eo,useEffect as Ir}from"react";var Fo=(e,o)=>{let[r,t]=eo({}),[a,n]=eo(!1),[s,i]=eo(null);return Ir(()=>{if(console.log("\u{1F527} [I18nProvider] Hybrid translation loading:",{hasProvidedTranslations:!!o&&Object.keys(o).length>0,hasUrl:!!e,providedKeys:o?Object.keys(o).length:0}),o&&Object.keys(o).length>0){console.log("\u2705 [I18nProvider] Using provided translations (highest priority)"),t(o),n(!1),i(null);return}if(!e){console.log("\u26A0\uFE0F [I18nProvider] No translations provided, using empty object (keys will show as-is)"),t({}),n(!1),i(null);return}console.log("\u{1F310} [I18nProvider] Loading translations from URL:",e);let d=!1;return n(!0),i(null),fetch(e).then(w=>{if(!w.ok)throw new Error(`Failed to load translations: ${w.status}`);return w.json()}).then(w=>{d||(console.log("\u2705 [I18nProvider] Translations loaded successfully from URL:",{url:e,keysLoaded:Object.keys(w).length}),t(w),n(!1))}).catch(w=>{d||(console.error("\u274C [I18nProvider] Failed to load translations from URL:",e,w),i(w.message),console.log("\u{1F504} [I18nProvider] Falling back to empty translations (keys will show as-is)"),t({}),n(!1))}),()=>{d=!0}},[e,o]),{translations:r,loading:a,error:s}};import{jsx as Oo}from"react/jsx-runtime";var No=Sr(null),kr=()=>{try{return _o()}catch{return null}},Ar=(e,o)=>{if(o.includes(".")){let r=o.split(".").reduce((t,a)=>t&&typeof t=="object"?t[a]:void 0,e);if(r!==void 0)return r}if(e&&e[o])return e[o]},Bo=({children:e,translations:o,translationsUrl:r,language:t="en"})=>{let n=kr()?.translations?.[t]||{},{translations:s,loading:i}=Fo(r,o),d=oo(()=>({...n,...s,...o||{}}),[n,s,o]),w=oo(()=>(h,p)=>{let l=Ar(d,h);return l==null&&(console.log(`\u{1F50D} [I18nProvider] Translation not found for key: "${h}" - showing key as-is`),l=h),p&&typeof l=="string"&&Object.entries(p).forEach(([c,b])=>{l=l.replace(new RegExp(`{{${c}}}`,"g"),b)}),typeof l=="string"?l:h},[d]),m=oo(()=>({t:w,language:t}),[w,t]);return i?Oo("div",{children:"Loading translations..."}):Oo(No.Provider,{value:m,children:e})},Q=()=>{let e=Lr(No);if(!e)throw new Error("useTranslation must be used within I18nProvider");return e};import{createContext as _r,useContext as Fr,useReducer as Or,useEffect as Do}from"react";import{jsx as Br}from"react/jsx-runtime";var Uo={currentScreen:"login",searchParams:{},formData:{username:"",password:"",email:"",code:"",newPassword:"",confirmPassword:""},loading:!1,errors:{global:[]},emailSent:!1,codeAlreadyExists:!1,codeValidated:!1,fromCodeVerification:!1,config:{}};function Nr(e,o){switch(o.type){case"SET_SCREEN":let r={...e,currentScreen:o.payload.screen,searchParams:o.payload.params||e.searchParams,errors:{global:[]}},t=new URLSearchParams(r.searchParams),a=t.toString()?`?${t.toString()}`:window.location.pathname;try{window.history.replaceState({},"",a)}catch{}return r;case"SET_SEARCH_PARAMS":return{...e,searchParams:o.payload};case"UPDATE_FORM_DATA":return{...e,formData:{...e.formData,...o.payload},errors:{...e.errors,...Object.keys(o.payload).reduce((n,s)=>({...n,[s]:void 0}),{})}};case"SET_LOADING":return{...e,loading:o.payload};case"SET_ERRORS":return{...e,errors:{...e.errors,...o.payload}};case"CLEAR_ERRORS":return{...e,errors:{global:[]}};case"SET_EMAIL_SENT":return{...e,emailSent:o.payload};case"SET_CODE_ALREADY_EXISTS":return{...e,codeAlreadyExists:o.payload};case"SET_CODE_VALIDATED":return{...e,codeValidated:o.payload};case"SET_FROM_CODE_VERIFICATION":return{...e,fromCodeVerification:o.payload};case"RESET_FORM":return{...e,formData:Uo.formData,errors:{global:[]},loading:!1,emailSent:!1,codeAlreadyExists:!1,codeValidated:!1,fromCodeVerification:!1};case"INIT_CONFIG":return{...e,config:o.payload};default:return e}}var zo=_r(void 0),Mo=({children:e,initialScreen:o="login",config:r,autoReadFromCookies:t=!0})=>{let[a,n]=Or(Nr,{...Uo,currentScreen:o});Do(()=>{n({type:"INIT_CONFIG",payload:(()=>{let l={};if(t)try{let c=bo("logo");if(c){let b=decodeURIComponent(c);b.startsWith("http")&&(l.logo=b)}}catch(c){console.error("Error reading configuration from cookies:",c)}return{publicApiKey:r?.publicApiKey,env:r?.env,appName:r?.appName,logo:r?.logo||l.logo,loginActions:r?.loginActions}})()})},[r,t]),Do(()=>{let p=new URLSearchParams(window.location.search),l={};p.forEach((c,b)=>{l[b]=c}),Object.keys(l).length>0&&n({type:"SET_SEARCH_PARAMS",payload:l}),o==="checkCode"&&l.email&&n({type:"UPDATE_FORM_DATA",payload:{email:l.email,code:l.code||""}}),o==="resetPassword"&&l.link&&n({type:"SET_SEARCH_PARAMS",payload:l})},[o]);let h={state:a,dispatch:n,setScreen:(p,l)=>{n({type:"SET_SCREEN",payload:{screen:p,params:l}})},updateFormData:p=>{n({type:"UPDATE_FORM_DATA",payload:p})},setFieldError:(p,l)=>{n({type:"SET_ERRORS",payload:{[p]:l}})},clearErrors:()=>{n({type:"CLEAR_ERRORS"})},setLoading:p=>{n({type:"SET_LOADING",payload:p})}};return Br(zo.Provider,{value:h,children:e})},He=()=>{let e=Fr(zo);if(e===void 0)throw new Error("useLoginState must be used within a LoginStateProvider");return e};import{useEffect as Dr,useRef as Ur}from"react";import{Typography as ro,TextField as Vo,Button as zr,Box as ke,CircularProgress as Mr,Alert as Vr,Link as Wo}from"@mui/material";import{Fragment as Hr,jsx as X,jsxs as Ae}from"react/jsx-runtime";var Wr=({onScreenChange:e,onExternalNavigate:o,onLoginSuccess:r,onError:t,redirectUrl:a="/"})=>{let{crudify:n}=te(),{state:s,updateFormData:i,setFieldError:d,clearErrors:w,setLoading:m}=He(),{login:h}=de(),p=Q(),{t:l}=p,c=p.i18n,b=Ur(null),f=Co(l,{currentLanguage:c?.language,enableDebug:!1}),y=()=>{if(s.searchParams.redirect)try{let g=decodeURIComponent(s.searchParams.redirect);if(g.startsWith("/")&&!g.startsWith("//"))return g}catch{}return a||"/"};Dr(()=>{let g=setTimeout(()=>{b.current&&b.current.focus()},100);return()=>clearTimeout(g)},[]);let u=g=>{console.log("\u{1F50D} [LoginForm] Translating parsed error:",g);let v=f.translateError({code:g.code,message:g.message,field:g.field});return console.log("\u{1F50D} [LoginForm] Translation result:",v),v},C=async()=>{if(!s.loading){if(!s.formData.username.trim()){d("username",l("login.usernameRequired"));return}if(!s.formData.password.trim()){d("password",l("login.passwordRequired"));return}w(),m(!0);try{let g=await h(s.formData.username,s.formData.password);if(m(!1),g.success){console.log("\u{1F510} LoginForm - Login successful via SessionProvider, calling onLoginSuccess");let v=y();r&&r(g.data,v)}else{let v=g.rawResponse||g;E(v)}}catch(g){m(!1);let L=G(g).map(u);d("global",L),t&&t(L.join(", "))}}},E=g=>{let v=G(g),L=[];v.forEach(B=>{B.field?d(B.field,u(B)):L.push(u(B))}),L.length>0&&d("global",L)};return Ae(Hr,{children:[Ae(ke,{component:"form",noValidate:!0,onSubmit:g=>{g.preventDefault(),C()},onKeyDown:g=>{g.key==="Enter"&&!s.loading&&(g.preventDefault(),C())},sx:{width:"100%",display:"flex",flexDirection:"column",gap:2},children:[Ae(ke,{sx:{mb:1},children:[X(ro,{variant:"body2",component:"label",htmlFor:"email",sx:{display:"block",fontWeight:500,color:"grey.700",mb:.5},children:l("login.usernameOrEmailLabel")}),X(Vo,{fullWidth:!0,id:"email",name:"email",type:"email",value:s.formData.username,disabled:s.loading,onChange:g=>i({username:g.target.value}),error:!!s.errors.username,helperText:s.errors.username,autoComplete:"email",placeholder:l("login.usernameOrEmailPlaceholder"),inputRef:b,required:!0})]}),Ae(ke,{sx:{mb:1},children:[X(ro,{variant:"body2",component:"label",htmlFor:"password",sx:{display:"block",fontWeight:500,color:"grey.700",mb:.5},children:l("login.passwordLabel")}),X(Vo,{fullWidth:!0,id:"password",name:"password",type:"password",value:s.formData.password,disabled:s.loading,onChange:g=>i({password:g.target.value}),error:!!s.errors.password,helperText:s.errors.password,autoComplete:"current-password",placeholder:l("login.passwordPlaceholder"),required:!0})]}),s.config.loginActions?.includes("forgotPassword")&&X(ke,{sx:{display:"flex",justifyContent:"flex-end",alignItems:"center"},children:X(Wo,{sx:{cursor:"pointer"},onClick:()=>{e?.("forgotPassword",s.searchParams)},variant:"body2",color:"secondary",children:l("login.forgotPasswordLink")})}),X(zr,{disabled:s.loading,type:"submit",fullWidth:!0,variant:"contained",color:"primary",sx:{mt:1,mb:2},children:s.loading?X(Mr,{size:20}):l("login.loginButton")})]}),X(ke,{children:s.errors.global&&s.errors.global.length>0&&s.errors.global.map((g,v)=>X(Vr,{variant:"filled",sx:{mt:2},severity:"error",children:X("div",{children:g})},v))}),s.config.loginActions?.includes("createUser")&&Ae(ro,{variant:"body2",align:"center",sx:{color:"text.secondary",mt:3},children:[l("login.noAccountPrompt")," ",X(Wo,{sx:{cursor:"pointer"},onClick:()=>{let v=`/public/users/create${Object.keys(s.searchParams).length>0?`?${new URLSearchParams(s.searchParams).toString()}`:""}`;o?.(v)},fontWeight:"medium",color:"secondary",children:l("login.signUpLink")})]})]})},Ho=Wr;import{useState as Te,useEffect as qr,useRef as Kr}from"react";import{Typography as Ee,TextField as jr,Button as qo,Box as ue,CircularProgress as $r,Alert as Gr,Link as to}from"@mui/material";import{Fragment as Ko,jsx as z,jsxs as we}from"react/jsx-runtime";var Yr=({onScreenChange:e,onError:o})=>{let{crudify:r}=te(),[t,a]=Te(""),[n,s]=Te(!1),[i,d]=Te([]),[w,m]=Te(null),[h,p]=Te(!1),[l,c]=Te(!1),b=Kr(null),{t:f}=Q();qr(()=>{b.current&&!h&&!l&&b.current.focus()},[h,l]);let y=g=>{let v=[`errors.auth.${g.code}`,`errors.data.${g.code}`,`errors.system.${g.code}`,`errors.${g.code}`,`forgotPassword.${g.code.toLowerCase()}`];for(let L of v){let B=f(L);if(B!==L)return B}return g.message||f("error.unknown")},u=g=>/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(g),C=async()=>{if(!(n||!r)){if(d([]),m(null),!t){m(f("forgotPassword.emailRequired"));return}if(!u(t)){m(f("forgotPassword.invalidEmail"));return}s(!0);try{let g=[{operation:"requestPasswordReset",data:{email:t}}],v=await r.transaction(g);if(v.success)v.data&&v.data.existingCodeValid?c(!0):p(!0);else{let B=G(v).map(y);d(B)}}catch(g){let L=G(g).map(y);d(L),o&&o(L.join(", "))}finally{s(!1)}}},E=()=>{e?.("login")},j=()=>{if(h||l){e?.("checkCode",{email:t});return}if(!t){m(f("forgotPassword.emailRequired"));return}if(!u(t)){m(f("forgotPassword.invalidEmail"));return}e?.("checkCode",{email:t})};return h||l?z(Ko,{children:we(ue,{sx:{width:"100%",display:"flex",flexDirection:"column",gap:2,textAlign:"center"},children:[we(ue,{sx:{mb:2},children:[z(Ee,{variant:"h5",component:"h1",sx:{mb:1,fontWeight:600},children:f(l?"forgotPassword.codeAlreadyExistsMessage":"forgotPassword.emailSentMessage")}),z(Ee,{variant:"body2",sx:{color:l?"success.main":"grey.600"},children:f("forgotPassword.checkEmailInstructions")})]}),z(qo,{type:"button",onClick:j,fullWidth:!0,variant:"contained",color:"primary",sx:{mt:2,mb:2},children:f("forgotPassword.enterCodeLink")}),z(ue,{sx:{display:"flex",justifyContent:"center",alignItems:"center"},children:z(to,{sx:{cursor:"pointer"},onClick:E,variant:"body2",color:"secondary",children:f("common.back")})})]})}):we(Ko,{children:[we(ue,{component:"form",noValidate:!0,onSubmit:g=>{g.preventDefault(),C()},sx:{width:"100%",display:"flex",flexDirection:"column",gap:2},children:[we(ue,{sx:{mb:2},children:[z(Ee,{variant:"h5",component:"h1",sx:{mb:1,fontWeight:600},children:f("forgotPassword.title")}),z(Ee,{variant:"body2",sx:{color:"grey.600"},children:f("forgotPassword.instructions")})]}),we(ue,{sx:{mb:1},children:[z(Ee,{variant:"body2",component:"label",htmlFor:"email",sx:{display:"block",fontWeight:500,color:"grey.700",mb:.5},children:f("forgotPassword.emailLabel")}),z(jr,{fullWidth:!0,id:"email",name:"email",type:"email",value:t,disabled:n,onChange:g=>a(g.target.value),error:!!w,helperText:w,autoComplete:"email",placeholder:f("forgotPassword.emailPlaceholder"),required:!0,autoFocus:!0,inputRef:b})]}),z(qo,{disabled:n,type:"submit",fullWidth:!0,variant:"contained",color:"primary",sx:{mt:2,mb:2},children:n?z($r,{size:20}):f("forgotPassword.sendCodeButton")}),we(ue,{sx:{display:"flex",justifyContent:"center",alignItems:"center",gap:2},children:[z(to,{sx:{cursor:"pointer"},onClick:E,variant:"body2",color:"secondary",children:f("common.back")}),z(Ee,{variant:"body2",sx:{color:"grey.400"},children:"\u2022"}),z(to,{sx:{cursor:"pointer"},onClick:j,variant:"body2",color:"secondary",children:f("login.alreadyHaveCodeLink")})]})]}),z(ue,{children:i.length>0&&i.map((g,v)=>z(Gr,{variant:"filled",sx:{mt:2},severity:"error",children:g},v))})]})},jo=Yr;import{useState as Y,useEffect as $o}from"react";import{Typography as qe,TextField as Go,Button as Jr,Box as me,CircularProgress as Yo,Alert as Jo,Link as Qr}from"@mui/material";import{Fragment as Zr,jsx as V,jsxs as _e}from"react/jsx-runtime";var Xr=({onScreenChange:e,onError:o,searchParams:r,onResetSuccess:t})=>{let{crudify:a}=te(),[n,s]=Y(""),[i,d]=Y(""),[w,m]=Y(!1),[h,p]=Y([]),[l,c]=Y(null),[b,f]=Y(null),[y,u]=Y(""),[C,E]=Y(""),[j,P]=Y(!1),[g,v]=Y(!0),[L,B]=Y(!1),[ae,ie]=Y(null),[re,Ce]=Y(!1),{t:A}=Q(),_=x=>{let I=[`errors.auth.${x.code}`,`errors.data.${x.code}`,`errors.system.${x.code}`,`errors.${x.code}`,`resetPassword.${x.code.toLowerCase()}`];for(let F of I){let H=A(F);if(H!==F)return H}return x.message||A("error.unknown")},M=x=>r?r instanceof URLSearchParams?r.get(x):r[x]||null:null;$o(()=>{if(r){if(r){let x=M("fromCodeVerification"),I=M("email"),F=M("code");if(x==="true"&&I&&F){u(I),E(F),P(!0),B(!0),v(!1);return}let H=M("link");if(H)try{let q=decodeURIComponent(H),[$,xe]=q.split("/");if($&&xe&&$.length===6){E($),u(xe),P(!1),ie({email:xe,code:$});return}}catch{}if(I&&F){u(I),E(F),P(!1),ie({email:I,code:F});return}}p([A("resetPassword.invalidCode")]),v(!1),setTimeout(()=>e?.("forgotPassword"),3e3)}},[r,a,A,e]),$o(()=>{a&&ae&&!re&&(Ce(!0),(async(I,F)=>{try{let H=[{operation:"validatePasswordResetCode",data:{email:I,codePassword:F}}],q=await a.transaction(H);if(q.data&&Array.isArray(q.data)){let $=q.data[0];if($&&$.response&&$.response.status==="OK"){B(!0);return}}if(q.success)B(!0);else{let xe=G(q).map(_);p(xe),setTimeout(()=>e?.("forgotPassword"),3e3)}}catch(H){let $=G(H).map(_);p($),setTimeout(()=>e?.("forgotPassword"),3e3)}finally{v(!1),ie(null),Ce(!1)}})(ae.email,ae.code))},[a,ae,A,e]);let he=x=>x.length<8?A("resetPassword.passwordTooShort"):null,R=async()=>{if(w||!a)return;p([]),c(null),f(null);let x=!1;if(!n)c(A("resetPassword.newPasswordRequired")),x=!0;else{let I=he(n);I&&(c(I),x=!0)}if(i?n!==i&&(f(A("resetPassword.passwordsDoNotMatch")),x=!0):(f(A("resetPassword.confirmPasswordRequired")),x=!0),!x){m(!0);try{let I=[{operation:"validateAndResetPassword",data:{email:y,codePassword:C,newPassword:n}}],F=await a.transaction(I);if(F.success)p([]),setTimeout(()=>{t?.()},1e3);else{let q=G(F).map(_);p(q)}}catch(I){let H=G(I).map(_);p(H),o&&o(H.join(", "))}m(!1)}},W=()=>{j?e?.("checkCode",{email:y}):e?.("forgotPassword")};return g?V(me,{sx:{display:"flex",justifyContent:"center",alignItems:"center",minHeight:"300px"},children:V(Yo,{})}):L?_e(Zr,{children:[_e(me,{component:"form",noValidate:!0,sx:{width:"100%",display:"flex",flexDirection:"column",gap:2},children:[_e(me,{sx:{mb:2},children:[V(qe,{variant:"h5",component:"h1",sx:{mb:1,fontWeight:600},children:A("resetPassword.title")}),V(qe,{variant:"body2",sx:{color:"grey.600"},children:A("resetPassword.instructions")})]}),_e(me,{sx:{mb:1},children:[V(qe,{variant:"body2",component:"label",htmlFor:"newPassword",sx:{display:"block",fontWeight:500,color:"grey.700",mb:.5},children:A("resetPassword.newPasswordLabel")}),V(Go,{fullWidth:!0,id:"newPassword",name:"newPassword",type:"password",value:n,disabled:w,onChange:x=>s(x.target.value),error:!!l,helperText:l,autoComplete:"new-password",placeholder:A("resetPassword.newPasswordPlaceholder"),required:!0})]}),_e(me,{sx:{mb:1},children:[V(qe,{variant:"body2",component:"label",htmlFor:"confirmPassword",sx:{display:"block",fontWeight:500,color:"grey.700",mb:.5},children:A("resetPassword.confirmPasswordLabel")}),V(Go,{fullWidth:!0,id:"confirmPassword",name:"confirmPassword",type:"password",value:i,disabled:w,onChange:x=>d(x.target.value),error:!!b,helperText:b,autoComplete:"new-password",placeholder:A("resetPassword.confirmPasswordPlaceholder"),required:!0})]}),V(Jr,{disabled:w,type:"button",onClick:R,fullWidth:!0,variant:"contained",color:"primary",sx:{mt:2,mb:2},children:w?V(Yo,{size:20}):A("resetPassword.resetPasswordButton")}),V(me,{sx:{display:"flex",justifyContent:"center",alignItems:"center"},children:V(Qr,{sx:{cursor:"pointer"},onClick:W,variant:"body2",color:"secondary",children:A("common.back")})})]}),V(me,{children:h.length>0&&h.map((x,I)=>V(Jo,{variant:"filled",sx:{mt:2},severity:"error",children:x},I))})]}):V(me,{children:h.length>0&&h.map((x,I)=>V(Jo,{variant:"filled",sx:{mt:2},severity:"error",children:x},I))})},Qo=Xr;import{useState as Fe,useEffect as Xo,useRef as et}from"react";import{Typography as no,TextField as ot,Button as rt,Box as Oe,CircularProgress as tt,Alert as nt,Link as st}from"@mui/material";import{Fragment as it,jsx as ne,jsxs as Ke}from"react/jsx-runtime";var at=({onScreenChange:e,onError:o,searchParams:r})=>{let{crudify:t}=te(),[a,n]=Fe(""),[s,i]=Fe(!1),[d,w]=Fe([]),[m,h]=Fe(null),[p,l]=Fe(""),c=et(null),{t:b}=Q(),f=P=>r?r instanceof URLSearchParams?r.get(P):r[P]||null:null,y=P=>{let g=[`errors.auth.${P.code}`,`errors.data.${P.code}`,`errors.system.${P.code}`,`errors.${P.code}`,`checkCode.${P.code.toLowerCase()}`];for(let v of g){let L=b(v);if(L!==v)return L}return P.message||b("error.unknown")};Xo(()=>{let P=f("email");P?l(P):e?.("forgotPassword")},[r,e]),Xo(()=>{c.current&&c.current.focus()},[]);let u=async()=>{if(!(s||!t)){if(w([]),h(null),!a){h(b("checkCode.codeRequired"));return}if(a.length!==6){h(b("checkCode.codeRequired"));return}i(!0);try{let P=[{operation:"validatePasswordResetCode",data:{email:p,codePassword:a}}],g=await t.transaction(P);if(g.success)e?.("resetPassword",{email:p,code:a,fromCodeVerification:"true"});else{let L=G(g).map(y);w(L),i(!1)}}catch(P){let v=G(P).map(y);w(v),i(!1),o&&o(v.join(", "))}}},C=()=>{e?.("forgotPassword")},E=P=>{let g=P.target.value.replace(/\D/g,"").slice(0,6);n(g)};return Ke(it,{children:[Ke(Oe,{component:"form",noValidate:!0,onSubmit:P=>{P.preventDefault(),u()},sx:{width:"100%",display:"flex",flexDirection:"column",gap:2},children:[Ke(Oe,{sx:{mb:2},children:[ne(no,{variant:"h5",component:"h1",sx:{mb:1,fontWeight:600},children:b("checkCode.title")}),ne(no,{variant:"body2",sx:{color:"grey.600"},children:b("checkCode.instructions")})]}),Ke(Oe,{sx:{mb:1},children:[ne(no,{variant:"body2",component:"label",htmlFor:"code",sx:{display:"block",fontWeight:500,color:"grey.700",mb:.5},children:b("checkCode.codeLabel")}),ne(ot,{fullWidth:!0,id:"code",name:"code",type:"text",value:a,disabled:s,onChange:E,error:!!m,helperText:m,placeholder:b("checkCode.codePlaceholder"),inputProps:{maxLength:6,style:{textAlign:"center",fontSize:"1.5rem",letterSpacing:"0.4rem"}},required:!0,autoFocus:!0,inputRef:c})]}),ne(rt,{disabled:s||a.length!==6,type:"submit",fullWidth:!0,variant:"contained",color:"primary",sx:{mt:2,mb:2},children:s?ne(tt,{size:20}):b("checkCode.verifyButton")}),ne(Oe,{sx:{display:"flex",justifyContent:"center",alignItems:"center"},children:ne(st,{sx:{cursor:"pointer"},onClick:C,variant:"body2",color:"secondary",children:b("common.back")})})]}),ne(Oe,{children:d.length>0&&d.map((P,g)=>ne(nt,{sx:{mt:2},severity:"error",children:P},g))})]})},Zo=at;import{Box as lt,CircularProgress as ct,Alert as er,Typography as so}from"@mui/material";import{Fragment as dt,jsx as Re,jsxs as or}from"react/jsx-runtime";var rr=({children:e,fallback:o})=>{let{isLoading:r,error:t,isInitialized:a}=te(),{t:n}=Q();return r?o||or(lt,{sx:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",minHeight:"200px",gap:2},children:[Re(ct,{}),Re(so,{variant:"body2",color:"text.secondary",children:n("login.initializing")!=="login.initializing"?n("login.initializing"):"Initializing..."})]}):t?Re(er,{severity:"error",sx:{mt:2},children:or(so,{variant:"body2",children:[n("login.initializationError")!=="login.initializationError"?n("login.initializationError"):"Initialization error",":"," ",t]})}):a?Re(dt,{children:e}):Re(er,{severity:"warning",sx:{mt:2},children:Re(so,{variant:"body2",children:n("login.notInitialized")!=="login.notInitialized"?n("login.notInitialized"):"System not initialized"})})};import{jsx as ee,jsxs as pt}from"react/jsx-runtime";var gt=({onScreenChange:e,onExternalNavigate:o,onLoginSuccess:r,onError:t,redirectUrl:a="/"})=>{let{t:n}=Q(),{state:s,setScreen:i}=He(),{config:d}=de(),{showNotification:w}=xo(),m=(p,l)=>{let c=l;p==="login"?c={}:p==="forgotPassword"&&!l&&(c={}),i(p,c),e?.(p,c)},h=()=>{let p={onScreenChange:m,onExternalNavigate:o,onError:t,redirectUrl:a};switch(s.currentScreen){case"forgotPassword":return ee(jo,{...p});case"checkCode":return ee(Zo,{...p,searchParams:s.searchParams});case"resetPassword":return ee(Qo,{...p,searchParams:s.searchParams,onResetSuccess:()=>{let l=n("resetPassword.successMessage");w(l,"success"),m("login")}});default:return ee(Ho,{...p,onLoginSuccess:r})}};return pt(rr,{children:[ee(ut,{sx:{display:"flex",justifyContent:"center",mb:3},children:ee("img",{src:d.logo||"https://logos.crudia.com/nocios-default.png",alt:n("login.logoAlt"),style:{width:"100%",maxWidth:"150px",height:"auto"},onError:p=>{let l=p.target;l.src="https://logos.crudia.com/nocios-default.png"}})}),!d.logo&&d.appName&&ee(mt,{variant:"h6",component:"h1",sx:{textAlign:"center",mb:2},children:d.appName}),h()]})},ft=({translations:e,translationsUrl:o,language:r="en",initialScreen:t="login",autoReadFromCookies:a=!0,...n})=>{let{config:s}=de();return ee(Bo,{translations:e,translationsUrl:o,language:r,children:ee(Po,{config:s,children:ee(Mo,{config:s,initialScreen:t,autoReadFromCookies:a,children:ee(gt,{...n})})})})},ia=ft;import{Box as J,Card as tr,CardContent as nr,Typography as oe,Chip as je,Avatar as yt,Divider as ht,CircularProgress as bt,Alert as sr,List as wt,ListItem as ao,ListItemText as io,ListItemIcon as Pt,Collapse as Ct,IconButton as lo}from"@mui/material";import{Person as xt,Email as vt,Badge as Tt,Security as Et,Schedule as Rt,AccountCircle as It,ExpandMore as St,ExpandLess as Lt,Info as kt}from"@mui/icons-material";import{useState as At}from"react";import{Fragment as Ot,jsx as T,jsxs as O}from"react/jsx-runtime";var _t=({showExtendedData:e=!0,showProfileCard:o=!0,autoRefresh:r=!0})=>{let{userProfile:t,loading:a,error:n,extendedData:s,refreshProfile:i}=vo({autoFetch:r,retryOnError:!0,maxRetries:3}),[d,w]=At(!1);if(a)return O(J,{display:"flex",justifyContent:"center",alignItems:"center",p:3,children:[T(bt,{}),T(oe,{variant:"body2",sx:{ml:2},children:"Cargando perfil de usuario..."})]});if(n)return O(sr,{severity:"error",action:T(lo,{color:"inherit",size:"small",onClick:i,children:T(oe,{variant:"caption",children:"Reintentar"})}),children:["Error al cargar el perfil: ",n]});if(!t)return T(sr,{severity:"warning",children:"No se encontr\xF3 informaci\xF3n del usuario"});let m=s?.displayData||{},h=s?.totalFields||0,p=u=>{if(!u)return"No disponible";try{return new Date(u).toLocaleString("es-ES",{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}catch{return u}},l=(u,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),c=[{key:"id",label:"ID",icon:T(Tt,{})},{key:"email",label:"Email",icon:T(vt,{})},{key:"username",label:"Usuario",icon:T(xt,{})},{key:"fullName",label:"Nombre completo",icon:T(It,{})},{key:"role",label:"Rol",icon:T(Et,{})}],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"}],f=[...c.map(u=>u.key),...b.map(u=>u.key),"permissions"],y=Object.keys(m).filter(u=>!f.includes(u)).map(u=>({key:u,label:u}));return O(J,{children:[o&&T(tr,{sx:{mb:2},children:O(nr,{children:[O(J,{display:"flex",alignItems:"center",mb:2,children:[T(yt,{src:m.avatar,sx:{width:56,height:56,mr:2},children:m.fullName?.[0]||m.username?.[0]||m.email?.[0]}),O(J,{children:[T(oe,{variant:"h6",children:m.fullName||m.username||m.email}),T(oe,{variant:"body2",color:"text.secondary",children:m.role||"Usuario"}),m.isActive!==void 0&&T(je,{label:m.isActive?"Activo":"Inactivo",color:m.isActive?"success":"error",size:"small",sx:{mt:.5}})]})]}),T(J,{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(250px, 1fr))",gap:2,children:c.map(({key:u,label:C,icon:E})=>m[u]?O(J,{display:"flex",alignItems:"center",children:[T(J,{sx:{mr:1,color:"text.secondary"},children:E}),O(J,{children:[T(oe,{variant:"caption",color:"text.secondary",children:C}),T(oe,{variant:"body2",children:l(u,m[u])})]})]},u):null)}),m.permissions&&Array.isArray(m.permissions)&&m.permissions.length>0&&O(J,{mt:2,children:[T(oe,{variant:"caption",color:"text.secondary",display:"block",children:"Permisos"}),O(J,{display:"flex",flexWrap:"wrap",gap:.5,mt:.5,children:[m.permissions.slice(0,5).map((u,C)=>T(je,{label:u,size:"small",variant:"outlined"},C)),m.permissions.length>5&&T(je,{label:`+${m.permissions.length-5} m\xE1s`,size:"small"})]})]})]})}),e&&T(tr,{children:O(nr,{children:[O(J,{display:"flex",justifyContent:"space-between",alignItems:"center",mb:2,children:[O(oe,{variant:"h6",display:"flex",alignItems:"center",children:[T(kt,{sx:{mr:1}}),"Informaci\xF3n Detallada"]}),T(je,{label:`${h} campos totales`,size:"small"})]}),O(wt,{dense:!0,children:[b.map(({key:u,label:C})=>m[u]!==void 0&&O(ao,{divider:!0,children:[T(Pt,{children:T(Rt,{fontSize:"small"})}),T(io,{primary:C,secondary:u.includes("At")||u.includes("Login")?p(m[u]):l(u,m[u])})]},u)),y.length>0&&O(Ot,{children:[T(ht,{sx:{my:1}}),T(ao,{children:T(io,{primary:O(J,{display:"flex",justifyContent:"space-between",alignItems:"center",children:[O(oe,{variant:"subtitle2",children:["Campos Personalizados (",y.length,")"]}),T(lo,{size:"small",onClick:()=>w(!d),children:d?T(Lt,{}):T(St,{})})]})})}),T(Ct,{in:d,children:y.map(({key:u,label:C})=>T(ao,{sx:{pl:4},children:T(io,{primary:C,secondary:l(u,m[u])})},u))})]})]}),O(J,{mt:2,display:"flex",justifyContent:"space-between",alignItems:"center",children:[O(oe,{variant:"caption",color:"text.secondary",children:["\xDAltima actualizaci\xF3n: ",p(m.updatedAt)]}),T(lo,{size:"small",onClick:i,disabled:a,children:T(oe,{variant:"caption",children:"Actualizar"})})]})]})})]})},Ft=_t;var ar=["create","read","update","delete"],ir=["create","read","update","delete"];import{useRef as tn}from"react";import{useTranslation as nn}from"react-i18next";import{Box as Ye,Typography as fr,Button as sn,Stack as an,Alert as pr,Divider as ln}from"@mui/material";import{Add as cn}from"@mui/icons-material";import{forwardRef as qt}from"react";import{useTranslation as Kt}from"react-i18next";import{Box as Pe,FormControl as jt,InputLabel as $t,Select as Gt,MenuItem as Yt,IconButton as Jt,Typography as Ie,FormHelperText as Qt,Stack as Ge,Paper as gr,Divider as Xt,Button as go}from"@mui/material";import{Delete as Zt,SelectAll as en,ClearAll as on}from"@mui/icons-material";import{useState as lr,useEffect as cr,useRef as dr}from"react";import{useTranslation as Nt}from"react-i18next";import{Box as $e,Typography as Ne,Button as ur,Stack as co,FormControlLabel as Bt,FormHelperText as mr,Switch as Dt,ToggleButton as uo,ToggleButtonGroup as Ut}from"@mui/material";import{CheckCircle as zt,Cancel as Mt,SelectAll as Vt,ClearAll as Wt}from"@mui/icons-material";import{jsx as D,jsxs as ge}from"react/jsx-runtime";var Ht=({value:e,onChange:o,availableFields:r,error:t,disabled:a=!1})=>{let{t:n}=Nt(),[s,i]=lr("custom"),[d,w]=lr(!1),m=dr(null);cr(()=>{d&&m.current?.scrollIntoView({behavior:"smooth",block:"start"})},[d]);let h=dr(!1);cr(()=>{let f=e||{allow:[],owner_allow:[],deny:[]},y=new Set(r),u=(f.allow||[]).filter(P=>y.has(P)),C=(f.owner_allow||[]).filter(P=>y.has(P)),E=(f.deny||[]).filter(P=>y.has(P));r.forEach(P=>{!u.includes(P)&&!C.includes(P)&&!E.includes(P)&&E.push(P)});let j={allow:u,owner_allow:C,deny:E};JSON.stringify(j)!==JSON.stringify(f)&&o(j),u.length===r.length?i("all"):E.length===r.length?i("none"):i("custom")},[r,e]);let p=()=>{h.current=!0,o({allow:[...r],owner_allow:[],deny:[]}),i("all"),setTimeout(()=>{h.current=!1},0)},l=()=>{h.current=!0,o({allow:[],owner_allow:[],deny:[...r]}),i("none"),setTimeout(()=>{h.current=!1},0)},c=f=>e?.allow?.includes(f)?"allow":e?.owner_allow?.includes(f)?"owner_allow":"deny",b=(f,y)=>{h.current=!0;let u=new Set(e?.allow||[]),C=new Set(e?.owner_allow||[]),E=new Set(e?.deny||[]);u.delete(f),C.delete(f),E.delete(f),y==="allow"&&u.add(f),y==="owner_allow"&&C.add(f),y==="deny"&&E.add(f),o({allow:Array.from(u),owner_allow:Array.from(C),deny:Array.from(E)}),i("custom"),setTimeout(()=>{h.current=!1},0)};return r.length===0?ge($e,{children:[D(Ne,{variant:"body2",color:"text.secondary",sx:{mb:1},children:n("modules.form.publicPolicies.fields.conditions.label")}),D(Ne,{variant:"body2",color:"text.secondary",sx:{fontStyle:"italic"},children:n("modules.form.publicPolicies.fields.conditions.noFieldsAvailable")}),t&&D(mr,{error:!0,sx:{mt:1},children:t})]}):ge($e,{children:[D(Ne,{variant:"body2",color:"text.secondary",sx:{mb:2},children:n("modules.form.publicPolicies.fields.conditions.label")}),ge(co,{direction:"row",spacing:1,alignItems:"center",sx:{mb:d?3:1},children:[D(ur,{variant:s==="all"?"contained":"outlined",startIcon:D(Vt,{}),onClick:p,disabled:a,size:"small",sx:{minWidth:120,...s==="all"&&{backgroundColor:"#16a34a","&:hover":{backgroundColor:"#15803d"}}},children:n("modules.form.publicPolicies.fields.conditions.allFields")}),D(ur,{variant:s==="none"?"contained":"outlined",startIcon:D(Wt,{}),onClick:l,disabled:a,size:"small",sx:{minWidth:120,...s==="none"&&{backgroundColor:"#cf222e","&:hover":{backgroundColor:"#bc1f2c"}}},children:n("modules.form.publicPolicies.fields.conditions.noFields")}),D($e,{sx:{display:"flex",alignItems:"center",px:1.5,py:.35,borderRadius:"999px",backgroundColor:"#f3f4f6",border:"1px solid #d1d9e0"},children:D(Bt,{control:D(Dt,{size:"small",checked:d,onChange:()=>w(f=>!f),disabled:a,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"}}})})]}),d&&ge($e,{ref:m,sx:{p:2,border:"1px solid #d1d9e0",borderRadius:1,backgroundColor:"#f6f8fa"},children:[D(Ne,{variant:"body2",color:"text.secondary",sx:{mb:2},children:n("modules.form.publicPolicies.fields.conditions.help")}),D(co,{spacing:1,children:r.map(f=>{let y=c(f);return ge(co,{direction:"row",spacing:1,alignItems:"center",children:[D(Ne,{variant:"body2",sx:{minWidth:100,fontFamily:"monospace"},children:f}),ge(Ut,{value:y,exclusive:!0,size:"small",children:[ge(uo,{value:"allow",onClick:()=>b(f,"allow"),disabled:a,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(zt,{sx:{fontSize:16,mr:.5}}),n("modules.form.publicPolicies.fields.conditions.states.allow")]}),D(uo,{value:"owner_allow",onClick:()=>b(f,"owner_allow"),disabled:a,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")}),ge(uo,{value:"deny",onClick:()=>b(f,"deny"),disabled:a,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(Mt,{sx:{fontSize:16,mr:.5}}),n("modules.form.publicPolicies.fields.conditions.states.deny")]})]})]},f)})})]}),t&&D(mr,{error:!0,sx:{mt:1},children:t})]})},mo=Ht;import{jsx as U,jsxs as K}from"react/jsx-runtime";var rn=qt(({policy:e,onChange:o,onRemove:r,availableFields:t,isSubmitting:a=!1,usedActions:n,error:s},i)=>{let{t:d}=Kt(),w=new Set(Array.from(n||[]));w.delete(e.action);let m=ar.map(h=>({value:h,label:d(`modules.form.publicPolicies.fields.action.options.${h}`)}));return K(gr,{ref:i,sx:{p:3,border:"1px solid #d1d9e0",borderRadius:2,position:"relative",backgroundColor:"#ffffff"},children:[K(Pe,{sx:{display:"flex",justifyContent:"space-between",alignItems:"flex-start",mb:3},children:[U(Ie,{variant:"subtitle1",sx:{fontWeight:600,color:"#111418",fontSize:"1rem"},children:d("modules.form.publicPolicies.policyTitle")}),U(Jt,{onClick:r,size:"small",disabled:a,"aria-label":d("modules.form.publicPolicies.removePolicy"),sx:{color:"#656d76","&:hover":{color:"#cf222e",backgroundColor:"rgba(207, 34, 46, 0.1)"}},children:U(Zt,{})})]}),K(Ge,{spacing:1,children:[U(Ge,{direction:{xs:"column",md:"row"},spacing:2,children:U(Pe,{sx:{flex:1,minWidth:200},children:K(jt,{fullWidth:!0,children:[U($t,{children:d("modules.form.publicPolicies.fields.action.label")}),U(Gt,{value:e.action,label:d("modules.form.publicPolicies.fields.action.label"),disabled:a,onChange:h=>{let p=h.target.value,l={...e,action:p};p==="delete"?(l.permission="deny",delete l.fields):(l.fields={allow:[],owner_allow:[],deny:t},delete l.permission),o(l)},sx:{backgroundColor:"#ffffff","&:hover .MuiOutlinedInput-notchedOutline":{borderColor:"#8c959f"},"&.Mui-focused .MuiOutlinedInput-notchedOutline":{borderColor:"#0969da",borderWidth:2}},children:m.map(h=>{let p=w.has(h.value);return U(Yt,{value:h.value,disabled:p,children:h.label},h.value)})}),s&&U(Qt,{error:!0,children:s})]})})}),e.action==="delete"?K(Pe,{children:[U(Ie,{variant:"body2",color:"text.secondary",sx:{mb:2},children:d("modules.form.publicPolicies.fields.conditions.label")}),K(Ge,{direction:"row",spacing:1,sx:{mb:1},children:[U(go,{variant:e.permission==="*"?"contained":"outlined",startIcon:U(en,{}),onClick:()=>o({...e,permission:"*"}),disabled:a,size:"small",sx:{minWidth:140,whiteSpace:"nowrap",...e.permission==="*"&&{backgroundColor:"#16a34a","&:hover":{backgroundColor:"#15803d"}}},children:d("modules.form.publicPolicies.fields.conditions.allFields")}),U(go,{variant:e.permission==="owner"?"contained":"outlined",onClick:()=>o({...e,permission:"owner"}),disabled:a,size:"small",sx:{minWidth:140,whiteSpace:"nowrap",...e.permission==="owner"&&{backgroundColor:"#0ea5e9","&:hover":{backgroundColor:"#0284c7"}}},children:d("modules.form.publicPolicies.fields.conditions.states.ownerAllow")}),U(go,{variant:e.permission==="deny"?"contained":"outlined",startIcon:U(on,{}),onClick:()=>o({...e,permission:"deny"}),disabled:a,size:"small",sx:{minWidth:140,whiteSpace:"nowrap",...e.permission==="deny"&&{backgroundColor:"#cf222e","&:hover":{backgroundColor:"#bc1f2c"}}},children:d("modules.form.publicPolicies.fields.conditions.noFields")})]})]}):U(mo,{value:e.fields||{allow:[],owner_allow:[],deny:[]},onChange:h=>o({...e,fields:h}),availableFields:t,disabled:a}),U(gr,{variant:"outlined",sx:{p:2,backgroundColor:"#f9fafb"},children:e.action==="delete"?K(Ie,{variant:"body2",sx:{fontFamily:"monospace",color:"text.secondary"},children:[K(Pe,{component:"span",sx:{color:e.permission==="*"?"#16a34a":e.permission==="owner"?"#0ea5e9":"#dc2626"},children:[d("modules.form.publicPolicies.fields.conditions.states.allow"),":"]})," ",e.permission||"-"]}):K(Ge,{spacing:.5,divider:U(Xt,{sx:{borderColor:"#e5e7eb"}}),children:[K(Ie,{variant:"body2",sx:{fontFamily:"monospace",color:"text.secondary"},children:[K(Pe,{component:"span",sx:{color:"#16a34a"},children:[d("modules.form.publicPolicies.fields.conditions.states.allow"),":"]})," ",(e?.fields?.allow||[]).join(", ")||"-"]}),K(Ie,{variant:"body2",sx:{fontFamily:"monospace",color:"text.secondary"},children:[K(Pe,{component:"span",sx:{color:"#0ea5e9"},children:[d("modules.form.publicPolicies.fields.conditions.states.ownerAllow"),":"]})," ",(e?.fields?.owner_allow||[]).join(", ")||"-"]}),K(Ie,{variant:"body2",sx:{fontFamily:"monospace",color:"text.secondary"},children:[K(Pe,{component:"span",sx:{color:"#dc2626"},children:[d("modules.form.publicPolicies.fields.conditions.states.deny"),":"]})," ",(e?.fields?.deny||[]).join(", ")||"-"]})]})})]})]})}),fo=rn;import{Fragment as mn,jsx as se,jsxs as Je}from"react/jsx-runtime";var dn=()=>{let e=globalThis?.crypto;return e&&typeof e.randomUUID=="function"?e.randomUUID():`${Date.now()}-${Math.random().toString(16).slice(2)}`},un=({policies:e,onChange:o,availableFields:r,errors:t,isSubmitting:a=!1})=>{let{t:n}=nn(),s=tn({}),i=new Set((e||[]).map(c=>c.action).filter(Boolean)),d=ir.filter(c=>!i.has(c)),w=d.length>0,m=()=>{let c=d[0]||"create",b={id:dn(),action:c};c==="delete"?b.permission="deny":b.fields={allow:[],owner_allow:[],deny:r};let f=[...e||[],b];o(f),setTimeout(()=>{let y=f.length-1,u=s.current[y];u&&u.scrollIntoView({behavior:"smooth",block:"center"})},100)},h=c=>{let b=[...e];b.splice(c,1),o(b)},p=(()=>{if(!t)return null;if(typeof t=="string")return t;let c=t._error;return typeof c=="string"?c:null})(),l=new Set((e||[]).map(c=>c.action));return Je(mn,{children:[se(ln,{sx:{borderColor:"#e0e4e7"}}),Je(Ye,{children:[se(Ye,{display:"flex",justifyContent:"space-between",alignItems:"center",mb:3,children:Je(Ye,{children:[se(fr,{variant:"h6",sx:{fontWeight:600,color:"#111418",mb:1},children:n("modules.form.publicPolicies.title")}),se(fr,{variant:"body2",color:"text.secondary",sx:{fontSize:"0.875rem"},children:n("modules.form.publicPolicies.description")})]})}),p&&se(pr,{severity:"error",sx:{mb:3},children:p}),Je(an,{spacing:3,children:[(e||[]).length===0?se(pr,{severity:"info",children:n("modules.form.publicPolicies.noPolicies")}):e.map((c,b)=>se(fo,{ref:f=>{s.current[b]=f},policy:c,onChange:f=>{let y=[...e];y[b]=f,o(y)},onRemove:()=>h(b),availableFields:r,isSubmitting:a,usedActions:l,error:typeof t=="object"&&t&&c.id in t?t[c.id]:void 0},c.id)),w&&se(Ye,{children:se(sn,{type:"button",variant:"outlined",startIcon:se(cn,{}),onClick:m,disabled:a,sx:{borderColor:"#d0d7de",color:"#656d76","&:hover":{borderColor:"#8c959f",backgroundColor:"transparent"}},children:n("modules.form.publicPolicies.addPolicy")})})]})]})]})},Ka=un;import{useState as po}from"react";import{Button as Qe,TextField as yr,Box as Se,Alert as Be,Typography as fe,CircularProgress as yo}from"@mui/material";import{jsx as N,jsxs as ce}from"react/jsx-runtime";function Xa(){let[e,o]=po(""),[r,t]=po(""),[a,n]=po(!1),{isAuthenticated:s,isLoading:i,error:d,login:w,logout:m,refreshTokens:h,clearError:p,isExpiringSoon:l,expiresIn:c}=de(),b=async u=>{if(u.preventDefault(),!e||!r)return;(await w(e,r)).success&&(o(""),t(""),n(!1))},f=async()=>{await m()},y=async()=>{await h()};return s?ce(Se,{sx:{maxWidth:600,mx:"auto",p:3},children:[N(fe,{variant:"h4",gutterBottom:!0,children:"Welcome! \u{1F389}"}),N(Be,{severity:"success",sx:{mb:3},children:"You are successfully logged in with Refresh Token Pattern enabled"}),ce(Se,{sx:{mb:3,p:2,bgcolor:"background.paper",border:1,borderColor:"divider",borderRadius:1},children:[N(fe,{variant:"h6",gutterBottom:!0,children:"Token Status"}),ce(fe,{variant:"body2",color:"text.secondary",children:["Access Token expires in: ",Math.round(c/1e3/60)," minutes"]}),l&&N(Be,{severity:"warning",sx:{mt:1},children:"Token expires soon - automatic refresh will happen"})]}),ce(Se,{sx:{display:"flex",gap:2,flexWrap:"wrap"},children:[N(Qe,{variant:"contained",onClick:y,disabled:i,startIcon:i?N(yo,{size:16}):null,children:"Refresh Tokens"}),N(Qe,{variant:"outlined",color:"error",onClick:f,disabled:i,children:"Logout"})]}),d&&N(Be,{severity:"error",sx:{mt:2},onClose:p,children:d})]}):ce(Se,{sx:{maxWidth:400,mx:"auto",p:3},children:[N(fe,{variant:"h4",gutterBottom:!0,align:"center",children:"Login with Refresh Tokens"}),N(Be,{severity:"info",sx:{mb:3},children:"This demo shows the new Refresh Token Pattern with automatic session management"}),a?ce("form",{onSubmit:b,children:[N(yr,{fullWidth:!0,label:"Email",type:"email",value:e,onChange:u=>o(u.target.value),margin:"normal",required:!0,autoComplete:"email"}),N(yr,{fullWidth:!0,label:"Password",type:"password",value:r,onChange:u=>t(u.target.value),margin:"normal",required:!0,autoComplete:"current-password"}),N(Qe,{type:"submit",fullWidth:!0,variant:"contained",size:"large",disabled:i,startIcon:i?N(yo,{size:16}):null,sx:{mt:3,mb:2},children:i?"Logging in...":"Login"})]}):N(Qe,{fullWidth:!0,variant:"contained",size:"large",onClick:()=>n(!0),sx:{mt:2},children:"Show Login Form"}),d&&N(Be,{severity:"error",sx:{mt:2},onClose:p,children:d})]})}function Za(){let{isAuthenticated:e,isLoading:o,isExpiringSoon:r,expiresIn:t}=de();return o?ce(Se,{sx:{display:"flex",alignItems:"center",gap:1},children:[N(yo,{size:16}),N(fe,{variant:"caption",children:"Loading session..."})]}):e?ce(Se,{children:[N(fe,{variant:"caption",color:"success.main",children:"\u2713 Authenticated"}),r&&ce(fe,{variant:"caption",color:"warning.main",display:"block",children:["\u26A0 Token expires in ",Math.round(t/1e3/60)," min"]})]}):N(fe,{variant:"caption",color:"text.secondary",children:"Not logged in"})}import gn from"@mui/material/TextField";import fn from"@mui/material/CircularProgress";import hr from"@mui/material/InputAdornment";import pn from"@mui/material/IconButton";import yn from"@mui/icons-material/Refresh";import{jsx as pe}from"react/jsx-runtime";var hn=e=>e.replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,"").replace(/javascript:/gi,"").replace(/on\w+\s*=/gi,"").replace(/<iframe\b[^<]*(?:(?!<\/iframe>)<[^<]*)*<\/iframe>/gi,""),bn=({html:e})=>pe("span",{dangerouslySetInnerHTML:{__html:hn(e)}}),li=({config:e,value:o,onChange:r,label:t,error:a=!1,helperText:n,readOnly:s=!1,disabled:i=!1})=>{let{value:d,loading:w,error:m,regenerate:h}=To(e,{autoFetch:!o,onSuccess:y=>{r?.(y)}}),p=o||d,l=a||!!m,c=m||n,b=l&&c&&(c.toLowerCase().includes("duplicate")||c.toLowerCase().includes("duplicado")||c.toLowerCase().includes("duplicada")||c.toLowerCase().includes("unique")||c.toLowerCase().includes("\xFAnico")||c.toLowerCase().includes("unico")||c.toLowerCase().includes("\xFAnica")||c.toLowerCase().includes("unica")||c.toLowerCase().includes("already exists")||c.toLowerCase().includes("ya existe")||c.toLowerCase().includes("e11000"));return pe(gn,{label:t,fullWidth:!0,value:p,error:l,helperText:c?pe(bn,{html:c}):" ",disabled:i,InputProps:{readOnly:!0,startAdornment:w?pe(hr,{position:"start",children:pe(fn,{size:20})}):void 0,endAdornment:b&&!w?pe(hr,{position:"end",children:pe(pn,{edge:"end",onClick:async()=>{!i&&!w&&await h()},disabled:i,size:"small",color:"error","aria-label":"regenerar c\xF3digo",title:"Regenerar c\xF3digo",children:pe(yn,{})})}):void 0}})};import br,{useCallback as De,useRef as wn,useState as Pn}from"react";import Ue from"@mui/material/Box";import Le from"@mui/material/Typography";import wr from"@mui/material/IconButton";import Cn from"@mui/material/LinearProgress";import ho from"@mui/material/CircularProgress";import xn from"@mui/material/Chip";import vn from"@mui/material/Paper";import Tn from"@mui/material/List";import En from"@mui/material/ListItem";import Rn from"@mui/material/ListItemIcon";import In from"@mui/material/ListItemText";import Sn from"@mui/material/ListItemSecondaryAction";import Ln from"@mui/material/FormHelperText";import kn from"@mui/icons-material/CloudUpload";import An from"@mui/icons-material/InsertDriveFile";import _n from"@mui/icons-material/Image";import Fn from"@mui/icons-material/PictureAsPdf";import On from"@mui/icons-material/Delete";import Nn from"@mui/icons-material/Refresh";import Bn from"@mui/icons-material/CheckCircle";import Dn from"@mui/icons-material/Error";import{jsx as S,jsxs as ye}from"react/jsx-runtime";var Pr=e=>{if(e===0)return"0 B";let o=1024,r=["B","KB","MB","GB"],t=Math.floor(Math.log(e)/Math.log(o));return`${parseFloat((e/Math.pow(o,t)).toFixed(1))} ${r[t]}`},Un=e=>e.startsWith("image/")?S(_n,{color:"primary"}):e==="application/pdf"?S(Fn,{color:"error"}):S(An,{color:"action"}),zn=e=>{switch(e){case"completed":return S(Bn,{color:"success",fontSize:"small"});case"error":return S(Dn,{color:"error",fontSize:"small"});case"uploading":case"pending":return S(ho,{size:16});case"removing":return S(ho,{size:16,color:"error"});default:return null}},Mn=({file:e,disabled:o,onRemove:r,onRetry:t})=>{let a=!o&&e.status!=="uploading"&&e.status!=="removing",n=!o&&e.status==="error"&&e.file;return ye(En,{sx:{borderRadius:1,mb:.5,bgcolor:e.status==="error"?"error.lighter":"background.paper",border:"1px solid",borderColor:e.status==="error"?"error.light":"divider"},children:[S(Rn,{sx:{minWidth:40},children:Un(e.contentType)}),S(In,{primary:ye(Ue,{sx:{display:"flex",alignItems:"center",gap:1},children:[S(Le,{variant:"body2",noWrap:!0,sx:{maxWidth:200,overflow:"hidden",textOverflow:"ellipsis"},children:e.name}),zn(e.status)]}),secondary:ye(Ue,{children:[S(Le,{variant:"caption",color:"text.secondary",children:Pr(e.size)}),e.status==="uploading"&&S(Cn,{variant:"determinate",value:e.progress,sx:{mt:.5,height:4,borderRadius:2}}),e.status==="error"&&e.errorMessage&&S(Le,{variant:"caption",color:"error",display:"block",children:e.errorMessage})]})}),ye(Sn,{children:[n&&S(wr,{edge:"end",size:"small",onClick:()=>t(e.id),color:"primary",title:"Reintentar",children:S(Nn,{fontSize:"small"})}),a&&S(wr,{edge:"end",size:"small",onClick:()=>r(e.id),color:"error",title:"Eliminar",children:S(On,{fontSize:"small"})})]})]})},Oi=({label:e,accept:o,maxFileSize:r=10*1024*1024,multiple:t=!1,maxFiles:a,minFiles:n=0,required:s=!1,disabled:i=!1,error:d=!1,helperText:w,onChange:m,onValidation:h,initialFiles:p,placeholder:l,showFileList:c=!0,visibility:b="private",showPreview:f=!0})=>{let y=wn(null),[u,C]=Pn(!1),E=t?a:1,j=s?Math.max(n,1):n,P={acceptedTypes:o,maxFileSize:r,maxFiles:E,minFiles:j,visibility:b,onFilesChange:k=>{let Z=k.filter(be=>be.status==="completed"&&be.filePath).map(be=>be.filePath);m?.(Z)}},{files:g,isUploading:v,addFiles:L,removeFile:B,retryUpload:ae,isValid:ie,validationError:re,initializeFiles:Ce,isTouched:A,markAsTouched:_,getPreviewUrl:M}=Eo(P);br.useEffect(()=>{p&&p.length>0&&Ce(p)},[]),br.useEffect(()=>{h?.(ie,re)},[ie,re,h]);let he=De(k=>{_();let Z=k.target.files;Z&&Z.length>0&&L(Z),y.current&&(y.current.value="")},[L,_]),R=De(()=>{i||(_(),y.current?.click())},[i,_]),W=De(k=>{k.preventDefault(),k.stopPropagation(),i||C(!0)},[i]),x=De(k=>{k.preventDefault(),k.stopPropagation(),C(!1)},[]),I=De(k=>{if(k.preventDefault(),k.stopPropagation(),C(!1),i)return;_();let Z=k.dataTransfer.files;Z&&Z.length>0&&L(Z)},[i,L,_]),F=o?.join(",")||"",H=t||g.length===0,q=d||A&&!ie,$=w||(A?re:null);return ye(Ue,{sx:{width:"100%"},children:[e&&ye(Le,{variant:"body2",sx:{mb:1,fontWeight:500,color:q?"error.main":"text.primary"},children:[e,s&&S("span",{style:{color:"red"},children:" *"})]}),S("input",{ref:y,type:"file",accept:F,multiple:t,onChange:he,disabled:i,style:{display:"none"}}),H&&ye(vn,{variant:"outlined",onClick:R,onDragOver:W,onDragLeave:x,onDrop:I,sx:{p:3,textAlign:"center",cursor:i?"not-allowed":"pointer",borderStyle:"dashed",borderWidth:2,borderColor:u?"primary.main":q?"error.main":"divider",bgcolor:u?"primary.lighter":i?"action.disabledBackground":"background.paper",transition:"all 0.2s ease","&:hover":i?{}:{borderColor:"primary.main",bgcolor:"action.hover"}},children:[S(kn,{sx:{fontSize:48,color:u?"primary.main":i?"action.disabled":"action.active",mb:1}}),S(Le,{variant:"body2",color:i?"text.disabled":"text.secondary",children:(()=>{if(l)return l;let k=[];if(u)return"Suelta el archivo aqu\xED";if(k.push("Arrastra archivos aqu\xED o haz clic para seleccionar"),o&&o.length>0){let Z=o.map(be=>be.split("/")[1]?.toUpperCase()||be).join(", ");k.push(`Tipos permitidos: ${Z}`)}return r&&k.push(`M\xE1ximo ${Pr(r)} por archivo`),E!==void 0&&t&&k.push(`M\xE1ximo ${E} archivos`),k[0]})()}),o&&o.length>0&&!u&&S(Ue,{sx:{mt:1,display:"flex",gap:.5,justifyContent:"center",flexWrap:"wrap"},children:o.map(k=>S(xn,{label:k.split("/")[1]?.toUpperCase()||k,size:"small",variant:"outlined",sx:{fontSize:"0.7rem"}},k))})]}),c&&g.length>0&&S(Tn,{dense:!0,sx:{mt:1,p:0},children:g.map(k=>S(Mn,{file:k,disabled:i,onRemove:B,onRetry:ae},k.id))}),v&&ye(Ue,{sx:{display:"flex",alignItems:"center",gap:1,mt:1},children:[S(ho,{size:16}),S(Le,{variant:"caption",color:"text.secondary",children:"Subiendo archivos..."})]}),$&&S(Ln,{error:q,sx:{mt:.5},children:$})]})};export{le as a,Vn as b,Wn as c,Xe as d,Me as e,Xn as f,_o as g,ia as h,Ft as i,ar as j,ir as k,Ka as l,Xa as m,Za as n,li as o,Oi as p};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }var _chunkIXDCGL4Kjs = require('./chunk-IXDCGL4K.js');var _react = require('react');var _crudifybrowser = require('@nocios/crudify-browser'); var _crudifybrowser2 = _interopRequireDefault(_crudifybrowser);var G=(S={})=>{let{autoFetch:a=!0,retryOnError:N=!1,maxRetries:g=3}=S,{isAuthenticated:T,isInitialized:I,sessionData:c,tokens:R}=_chunkIXDCGL4Kjs.j.call(void 0, ),[E,d]=_react.useState.call(void 0, null),[y,A]=_react.useState.call(void 0, a&&T),[_,p]=_react.useState.call(void 0, null),u=_react.useRef.call(void 0, null),o=_react.useRef.call(void 0, !0),m=_react.useRef.call(void 0, 0),l=_react.useRef.call(void 0, 0),x=_react.useCallback.call(void 0, ()=>c&&(c.email||c["cognito:username"])||null,[c]),P=_react.useCallback.call(void 0, ()=>{d(null),p(null),A(!1),l.current=0},[]),w=_react.useCallback.call(void 0, async()=>{let F=x();if(!F){o.current&&(p("No user email available from session data"),A(!1));return}if(!I){o.current&&(p("Session not initialized"),A(!1));return}u.current&&u.current.abort();let e=new AbortController;u.current=e;let i=++m.current;try{o.current&&(A(!0),p(null));let r=await _crudifybrowser2.default.readItems("users",{filter:{email:F},pagination:{limit:1}});if(i===m.current&&o.current&&!e.signal.aborted){let t=null;if(r.success){if(Array.isArray(r.data)&&r.data.length>0)t=r.data[0];else if(_optionalChain([r, 'access', _2 => _2.data, 'optionalAccess', _3 => _3.response, 'optionalAccess', _4 => _4.data]))try{let n=r.data.response.data,s=typeof n=="string"?JSON.parse(n):n;s&&s.items&&Array.isArray(s.items)&&s.items.length>0&&(t=s.items[0])}catch (e2){}else if(r.data&&typeof r.data=="object")r.data.items&&Array.isArray(r.data.items)&&r.data.items.length>0&&(t=r.data.items[0]);else if(_optionalChain([r, 'access', _5 => _5.data, 'optionalAccess', _6 => _6.data, 'optionalAccess', _7 => _7.response, 'optionalAccess', _8 => _8.data]))try{let n=r.data.data.response.data,s=typeof n=="string"?JSON.parse(n):n;s&&s.items&&Array.isArray(s.items)&&s.items.length>0&&(t=s.items[0])}catch (e3){}}t?(d(t),p(null),l.current=0):(p("User profile not found in database"),d(null))}}catch(r){if(i===m.current&&o.current){let t=r;if(t.name==="AbortError")return;N&&l.current<g&&(_optionalChain([t, 'access', _9 => _9.message, 'optionalAccess', _10 => _10.includes, 'call', _11 => _11("Network Error")])||_optionalChain([t, 'access', _12 => _12.message, 'optionalAccess', _13 => _13.includes, 'call', _14 => _14("Failed to fetch")]))?(l.current++,setTimeout(()=>{o.current&&w()},1e3*l.current)):(p("Failed to load user profile from database"),d(null))}}finally{i===m.current&&o.current&&A(!1),u.current===e&&(u.current=null)}},[I,x,N,g]);return _react.useEffect.call(void 0, ()=>{a&&T&&I?w():T||P()},[a,T,I,w,P]),_react.useEffect.call(void 0, ()=>(o.current=!0,()=>{o.current=!1,u.current&&(u.current.abort(),u.current=null)}),[]),{user:{session:c,data:E},loading:y,error:_,refreshProfile:w,clearProfile:P}};var ee=()=>{let{isAuthenticated:S,isLoading:a,isInitialized:N,tokens:g,error:T,sessionData:I,login:c,logout:R,refreshTokens:E,clearError:d,getTokenInfo:y,isExpiringSoon:A,expiresIn:_,refreshExpiresIn:p}=_chunkIXDCGL4Kjs.j.call(void 0, ),u=_react.useCallback.call(void 0, m=>{m?console.warn("useAuth.setToken() is deprecated. Use login() method instead for better security."):R()},[R]),o=_optionalChain([g, 'optionalAccess', _15 => _15.expiresAt])?new Date(g.expiresAt):null;return{isAuthenticated:S,loading:a,error:T,token:_optionalChain([g, 'optionalAccess', _16 => _16.accessToken])||null,user:I,tokenExpiration:o,setToken:u,logout:R,refreshToken:E,login:c,isExpiringSoon:A,expiresIn:_,refreshExpiresIn:p,getTokenInfo:y,clearError:d}};var oe=()=>{let{isInitialized:S,isLoading:a,error:N,isAuthenticated:g,login:T}=_chunkIXDCGL4Kjs.j.call(void 0, ),I=_react.useCallback.call(void 0, ()=>S&&!a&&!N,[S,a,N]),c=_react.useCallback.call(void 0, async()=>new Promise((o,m)=>{let l=()=>{I()?o():N?m(new Error(N)):setTimeout(l,100)};l()}),[I,N]),R=_react.useCallback.call(void 0, async()=>{if(!I())throw new Error("System not ready. Check isInitialized, isLoading, and error states.")},[I]),E=_react.useCallback.call(void 0, async(o,m,l)=>(await R(),await _crudifybrowser2.default.readItems(o,m||{},l)),[R]),d=_react.useCallback.call(void 0, async(o,m,l)=>(await R(),await _crudifybrowser2.default.readItem(o,m,l)),[R]),y=_react.useCallback.call(void 0, async(o,m,l)=>(await R(),await _crudifybrowser2.default.createItem(o,m,l)),[R]),A=_react.useCallback.call(void 0, async(o,m,l)=>(await R(),await _crudifybrowser2.default.updateItem(o,m,l)),[R]),_=_react.useCallback.call(void 0, async(o,m,l)=>(await R(),await _crudifybrowser2.default.deleteItem(o,m,l)),[R]),p=_react.useCallback.call(void 0, async(o,m)=>(await R(),await _crudifybrowser2.default.transaction(o,m)),[R]),u=_react.useCallback.call(void 0, async(o,m)=>{try{let l=await T(o,m);return l.success?{success:!0,data:l.tokens}:{success:!1,errors:l.error||"Login failed"}}catch(l){return{success:!1,errors:l instanceof Error?l.message:"Login failed"}}},[T]);return{readItems:E,readItem:d,createItem:y,updateItem:A,deleteItem:_,transaction:p,login:u,isInitialized:S,isInitializing:a,initializationError:N,isReady:I,waitForReady:c}};var Y={INVALID_CREDENTIALS:"warning",UNAUTHORIZED:"warning",INVALID_API_KEY:"error",USER_NOT_FOUND:"warning",USER_NOT_ACTIVE:"warning",NO_PERMISSION:"warning",ITEM_NOT_FOUND:"info",NOT_FOUND:"info",IN_USE:"warning",FIELD_ERROR:"warning",BAD_REQUEST:"warning",INTERNAL_SERVER_ERROR:"error",DATABASE_CONNECTION_ERROR:"error",INVALID_CONFIGURATION:"error",UNKNOWN_OPERATION:"error",TOO_MANY_REQUESTS:"warning"},M={INVALID_CREDENTIALS:"errors.auth.INVALID_CREDENTIALS",UNAUTHORIZED:"errors.auth.UNAUTHORIZED",INVALID_API_KEY:"errors.auth.INVALID_API_KEY",USER_NOT_FOUND:"errors.auth.USER_NOT_FOUND",USER_NOT_ACTIVE:"errors.auth.USER_NOT_ACTIVE",NO_PERMISSION:"errors.auth.NO_PERMISSION",ITEM_NOT_FOUND:"errors.data.ITEM_NOT_FOUND",NOT_FOUND:"errors.data.NOT_FOUND",IN_USE:"errors.data.IN_USE",FIELD_ERROR:"errors.data.FIELD_ERROR",BAD_REQUEST:"errors.data.BAD_REQUEST",INTERNAL_SERVER_ERROR:"errors.system.INTERNAL_SERVER_ERROR",DATABASE_CONNECTION_ERROR:"errors.system.DATABASE_CONNECTION_ERROR",INVALID_CONFIGURATION:"errors.system.INVALID_CONFIGURATION",UNKNOWN_OPERATION:"errors.system.UNKNOWN_OPERATION",TOO_MANY_REQUESTS:"errors.system.TOO_MANY_REQUESTS"},le= exports.d =(S={})=>{let{showNotification:a}=_chunkIXDCGL4Kjs.h.call(void 0, ),{showSuccessNotifications:N=!1,showErrorNotifications:g=!0,customErrorMessages:T={},defaultErrorMessage:I="Ha ocurrido un error inesperado",autoHideDuration:c=6e3,appStructure:R=[],translateFn:E=e=>e}=S,d=_react.useCallback.call(void 0, e=>!(!e.success&&e.errors&&(Object.keys(e.errors).some(r=>r!=="_error"&&r!=="_graphql"&&r!=="_transaction")||_optionalChain([e, 'access', _17 => _17.errors, 'access', _18 => _18._transaction, 'optionalAccess', _19 => _19.includes, 'call', _20 => _20("ONE_OR_MORE_OPERATIONS_FAILED")])||_optionalChain([e, 'access', _21 => _21.errors, 'access', _22 => _22._error, 'optionalAccess', _23 => _23.includes, 'call', _24 => _24("TOO_MANY_REQUESTS")]))||!e.success&&_optionalChain([e, 'access', _25 => _25.data, 'optionalAccess', _26 => _26.response, 'optionalAccess', _27 => _27.status])==="TOO_MANY_REQUESTS"),[]),y=_react.useCallback.call(void 0, (e,i)=>{let r=E(e);return r===e?i||E("error.unknown"):r},[E]),A=_react.useCallback.call(void 0, e=>["create","update","delete"].includes(e),[]),_=_react.useCallback.call(void 0, (e,i)=>N?A(e)&&i?!0:R.some(r=>r.key===e):!1,[N,R,A]),p=_react.useCallback.call(void 0, (e,i,r)=>{let t=_optionalChain([r, 'optionalAccess', _28 => _28.key])&&typeof r.key=="string"?r.key:e,n=`action.onSuccess.${t}`,s=y(n);if(s!==E("error.unknown")){if(A(t)&&i){let f=`action.${i}Singular`,O=y(f);if(O!==E("error.unknown"))return E(n,{item:O});{let k=`action.onSuccess.${t}WithoutItem`,L=y(k);return L!==E("error.unknown")?L:s}}return s}return E("success.transaction")},[y,E,A]),u=_react.useCallback.call(void 0, e=>{if(e.errorCode&&T[e.errorCode])return T[e.errorCode];if(e.errorCode&&M[e.errorCode])return y(M[e.errorCode]);if(e.errorCode){let i=[`errors.auth.${e.errorCode}`,`errors.data.${e.errorCode}`,`errors.system.${e.errorCode}`,`errors.${e.errorCode}`];for(let r of i){let t=y(r);if(t!==E("error.unknown"))return t}}if(typeof e.data=="string"&&e.data.startsWith("errors.")){let i=y(e.data);if(i!==E("error.unknown"))return i}if(e.errors&&Object.keys(e.errors).length>0){let i=Object.keys(e.errors);if(i.length===1&&i[0]==="_transaction"){let r=e.errors._transaction;if(_optionalChain([r, 'optionalAccess', _29 => _29.includes, 'call', _30 => _30("ONE_OR_MORE_OPERATIONS_FAILED")]))return"";if(Array.isArray(r)&&r.length>0){let t=r[0];if(typeof t=="string"&&t!=="ONE_OR_MORE_OPERATIONS_FAILED")try{let n=JSON.parse(t);if(Array.isArray(n)&&n.length>0){let s=n[0];if(_optionalChain([s, 'optionalAccess', _31 => _31.response, 'optionalAccess', _32 => _32.errorCode])){let f=s.response.errorCode;if(M[f])return y(M[f]);let O=[`errors.auth.${f}`,`errors.data.${f}`,`errors.system.${f}`,`errors.${f}`];for(let k of O){let L=y(k);if(L!==y("error.unknown"))return L}}if(_optionalChain([s, 'optionalAccess', _33 => _33.response, 'optionalAccess', _34 => _34.data]))return s.response.data}if(_optionalChain([n, 'optionalAccess', _35 => _35.response, 'optionalAccess', _36 => _36.message])){let s=n.response.message.toLowerCase();return s.includes("expired")?y("resetPassword.linkExpired","El enlace ha expirado"):s.includes("invalid")?y("resetPassword.invalidCode","C\xF3digo inv\xE1lido"):n.response.message}}catch (e4){return t.toLowerCase().includes("expired")?y("resetPassword.linkExpired","El enlace ha expirado"):t.toLowerCase().includes("invalid")?y("resetPassword.invalidCode","C\xF3digo inv\xE1lido"):t}}return y("error.transaction","Error en la operaci\xF3n")}if(i.length===1&&i[0]==="_error"){let r=e.errors._error;return Array.isArray(r)?r[0]:String(r)}return i.length===1&&i[0]==="_graphql"?y("errors.system.DATABASE_CONNECTION_ERROR"):`${y("errors.data.FIELD_ERROR")}: ${i.join(", ")}`}return I||E("error.unknown")},[T,I,E,y]),o=_react.useCallback.call(void 0, e=>e.errorCode&&Y[e.errorCode]?Y[e.errorCode]:"error",[]),m=_react.useCallback.call(void 0, async(e,i,r)=>{let t=await _crudifybrowser2.default.createItem(e,i,r);if(!t.success&&g&&d(t)){let n=u(t),s=o(t);a(n,s,{autoHideDuration:c})}else if(t.success){let n=_optionalChain([r, 'optionalAccess', _37 => _37.actionConfig]),s=_optionalChain([n, 'optionalAccess', _38 => _38.key])||"create",f=_optionalChain([n, 'optionalAccess', _39 => _39.moduleKey])||e;if(_(s,f)){let O=p(s,f,n);a(O,"success",{autoHideDuration:c})}}return t},[g,_,a,u,o,p,c,d]),l=_react.useCallback.call(void 0, async(e,i,r)=>{let t=await _crudifybrowser2.default.updateItem(e,i,r),n=_optionalChain([r, 'optionalAccess', _40 => _40.skipNotifications])===!0;if(!n&&!t.success&&g&&d(t)){let s=u(t),f=o(t);a(s,f,{autoHideDuration:c})}else if(!n&&t.success){let s=_optionalChain([r, 'optionalAccess', _41 => _41.actionConfig]),f=_optionalChain([s, 'optionalAccess', _42 => _42.key])||"update",O=_optionalChain([s, 'optionalAccess', _43 => _43.moduleKey])||e;if(_(f,O)){let k=p(f,O,s);a(k,"success",{autoHideDuration:c})}}return t},[g,_,a,u,o,p,c,d]),x=_react.useCallback.call(void 0, async(e,i,r)=>{let t=await _crudifybrowser2.default.deleteItem(e,i,r);if(!t.success&&g&&d(t)){let n=u(t),s=o(t);a(n,s,{autoHideDuration:c})}else if(t.success){let n=_optionalChain([r, 'optionalAccess', _44 => _44.actionConfig]),s=_optionalChain([n, 'optionalAccess', _45 => _45.key])||"delete",f=_optionalChain([n, 'optionalAccess', _46 => _46.moduleKey])||e;if(_(s,f)){let O=p(s,f,n);a(O,"success",{autoHideDuration:c})}}return t},[g,_,a,u,o,p,c,d]),P=_react.useCallback.call(void 0, async(e,i,r)=>{let t=await _crudifybrowser2.default.readItem(e,i,r);if(!t.success&&g&&d(t)){let n=u(t),s=o(t);a(n,s,{autoHideDuration:c})}return t},[g,a,u,o,c,d]),w=_react.useCallback.call(void 0, async(e,i,r)=>{let t=await _crudifybrowser2.default.readItems(e,i,r);if(!t.success&&g&&d(t)){let n=u(t),s=o(t);a(n,s,{autoHideDuration:c})}return t},[g,a,u,o,c,d]),V=_react.useCallback.call(void 0, async(e,i)=>{let r=await _crudifybrowser2.default.transaction(e,i),t=_optionalChain([i, 'optionalAccess', _47 => _47.skipNotifications])===!0;if(!t&&!r.success&&g&&d(r)){let n=u(r),s=o(r);a(n,s,{autoHideDuration:c})}else if(!t&&r.success){let n="transaction",s,f=null;if(_optionalChain([i, 'optionalAccess', _48 => _48.actionConfig])?(f=i.actionConfig,n=f.key,s=f.moduleKey):Array.isArray(e)&&e.length>0&&e[0].operation&&(n=e[0].operation,f=R.find(O=>O.key===n),f&&(s=f.moduleKey)),_(n,s)){let O=p(n,s,f);a(O,"success",{autoHideDuration:c})}}return r},[g,_,a,u,o,p,c,d,R]),F=_react.useCallback.call(void 0, (e,i)=>{if(!e.success&&g&&d(e)){let r=u(e),t=o(e);a(r,t,{autoHideDuration:c})}else e.success&&N&&i&&a(i,"success",{autoHideDuration:c});return e},[g,N,a,u,o,c,d,E]);return{createItem:m,updateItem:l,deleteItem:x,readItem:P,readItems:w,transaction:V,handleResponse:F,getErrorMessage:u,getErrorSeverity:o,shouldShowNotification:d}};exports.a = G; exports.b = ee; exports.c = oe; exports.d = le;
|
|
1
|
+
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }var _chunkMMFYNCPIjs = require('./chunk-MMFYNCPI.js');var _react = require('react');var _crudifybrowser = require('@nocios/crudify-browser'); var _crudifybrowser2 = _interopRequireDefault(_crudifybrowser);var G=(S={})=>{let{autoFetch:a=!0,retryOnError:N=!1,maxRetries:g=3}=S,{isAuthenticated:T,isInitialized:I,sessionData:c,tokens:R}=_chunkMMFYNCPIjs.j.call(void 0, ),[E,d]=_react.useState.call(void 0, null),[y,A]=_react.useState.call(void 0, a&&T),[_,p]=_react.useState.call(void 0, null),u=_react.useRef.call(void 0, null),o=_react.useRef.call(void 0, !0),m=_react.useRef.call(void 0, 0),l=_react.useRef.call(void 0, 0),x=_react.useCallback.call(void 0, ()=>c&&(c.email||c["cognito:username"])||null,[c]),P=_react.useCallback.call(void 0, ()=>{d(null),p(null),A(!1),l.current=0},[]),w=_react.useCallback.call(void 0, async()=>{let F=x();if(!F){o.current&&(p("No user email available from session data"),A(!1));return}if(!I){o.current&&(p("Session not initialized"),A(!1));return}u.current&&u.current.abort();let e=new AbortController;u.current=e;let i=++m.current;try{o.current&&(A(!0),p(null));let r=await _crudifybrowser2.default.readItems("users",{filter:{email:F},pagination:{limit:1}});if(i===m.current&&o.current&&!e.signal.aborted){let t=null;if(r.success){if(Array.isArray(r.data)&&r.data.length>0)t=r.data[0];else if(_optionalChain([r, 'access', _2 => _2.data, 'optionalAccess', _3 => _3.response, 'optionalAccess', _4 => _4.data]))try{let n=r.data.response.data,s=typeof n=="string"?JSON.parse(n):n;s&&s.items&&Array.isArray(s.items)&&s.items.length>0&&(t=s.items[0])}catch (e2){}else if(r.data&&typeof r.data=="object")r.data.items&&Array.isArray(r.data.items)&&r.data.items.length>0&&(t=r.data.items[0]);else if(_optionalChain([r, 'access', _5 => _5.data, 'optionalAccess', _6 => _6.data, 'optionalAccess', _7 => _7.response, 'optionalAccess', _8 => _8.data]))try{let n=r.data.data.response.data,s=typeof n=="string"?JSON.parse(n):n;s&&s.items&&Array.isArray(s.items)&&s.items.length>0&&(t=s.items[0])}catch (e3){}}t?(d(t),p(null),l.current=0):(p("User profile not found in database"),d(null))}}catch(r){if(i===m.current&&o.current){let t=r;if(t.name==="AbortError")return;N&&l.current<g&&(_optionalChain([t, 'access', _9 => _9.message, 'optionalAccess', _10 => _10.includes, 'call', _11 => _11("Network Error")])||_optionalChain([t, 'access', _12 => _12.message, 'optionalAccess', _13 => _13.includes, 'call', _14 => _14("Failed to fetch")]))?(l.current++,setTimeout(()=>{o.current&&w()},1e3*l.current)):(p("Failed to load user profile from database"),d(null))}}finally{i===m.current&&o.current&&A(!1),u.current===e&&(u.current=null)}},[I,x,N,g]);return _react.useEffect.call(void 0, ()=>{a&&T&&I?w():T||P()},[a,T,I,w,P]),_react.useEffect.call(void 0, ()=>(o.current=!0,()=>{o.current=!1,u.current&&(u.current.abort(),u.current=null)}),[]),{user:{session:c,data:E},loading:y,error:_,refreshProfile:w,clearProfile:P}};var ee=()=>{let{isAuthenticated:S,isLoading:a,isInitialized:N,tokens:g,error:T,sessionData:I,login:c,logout:R,refreshTokens:E,clearError:d,getTokenInfo:y,isExpiringSoon:A,expiresIn:_,refreshExpiresIn:p}=_chunkMMFYNCPIjs.j.call(void 0, ),u=_react.useCallback.call(void 0, m=>{m?console.warn("useAuth.setToken() is deprecated. Use login() method instead for better security."):R()},[R]),o=_optionalChain([g, 'optionalAccess', _15 => _15.expiresAt])?new Date(g.expiresAt):null;return{isAuthenticated:S,loading:a,error:T,token:_optionalChain([g, 'optionalAccess', _16 => _16.accessToken])||null,user:I,tokenExpiration:o,setToken:u,logout:R,refreshToken:E,login:c,isExpiringSoon:A,expiresIn:_,refreshExpiresIn:p,getTokenInfo:y,clearError:d}};var oe=()=>{let{isInitialized:S,isLoading:a,error:N,isAuthenticated:g,login:T}=_chunkMMFYNCPIjs.j.call(void 0, ),I=_react.useCallback.call(void 0, ()=>S&&!a&&!N,[S,a,N]),c=_react.useCallback.call(void 0, async()=>new Promise((o,m)=>{let l=()=>{I()?o():N?m(new Error(N)):setTimeout(l,100)};l()}),[I,N]),R=_react.useCallback.call(void 0, async()=>{if(!I())throw new Error("System not ready. Check isInitialized, isLoading, and error states.")},[I]),E=_react.useCallback.call(void 0, async(o,m,l)=>(await R(),await _crudifybrowser2.default.readItems(o,m||{},l)),[R]),d=_react.useCallback.call(void 0, async(o,m,l)=>(await R(),await _crudifybrowser2.default.readItem(o,m,l)),[R]),y=_react.useCallback.call(void 0, async(o,m,l)=>(await R(),await _crudifybrowser2.default.createItem(o,m,l)),[R]),A=_react.useCallback.call(void 0, async(o,m,l)=>(await R(),await _crudifybrowser2.default.updateItem(o,m,l)),[R]),_=_react.useCallback.call(void 0, async(o,m,l)=>(await R(),await _crudifybrowser2.default.deleteItem(o,m,l)),[R]),p=_react.useCallback.call(void 0, async(o,m)=>(await R(),await _crudifybrowser2.default.transaction(o,m)),[R]),u=_react.useCallback.call(void 0, async(o,m)=>{try{let l=await T(o,m);return l.success?{success:!0,data:l.tokens}:{success:!1,errors:l.error||"Login failed"}}catch(l){return{success:!1,errors:l instanceof Error?l.message:"Login failed"}}},[T]);return{readItems:E,readItem:d,createItem:y,updateItem:A,deleteItem:_,transaction:p,login:u,isInitialized:S,isInitializing:a,initializationError:N,isReady:I,waitForReady:c}};var Y={INVALID_CREDENTIALS:"warning",UNAUTHORIZED:"warning",INVALID_API_KEY:"error",USER_NOT_FOUND:"warning",USER_NOT_ACTIVE:"warning",NO_PERMISSION:"warning",ITEM_NOT_FOUND:"info",NOT_FOUND:"info",IN_USE:"warning",FIELD_ERROR:"warning",BAD_REQUEST:"warning",INTERNAL_SERVER_ERROR:"error",DATABASE_CONNECTION_ERROR:"error",INVALID_CONFIGURATION:"error",UNKNOWN_OPERATION:"error",TOO_MANY_REQUESTS:"warning"},M={INVALID_CREDENTIALS:"errors.auth.INVALID_CREDENTIALS",UNAUTHORIZED:"errors.auth.UNAUTHORIZED",INVALID_API_KEY:"errors.auth.INVALID_API_KEY",USER_NOT_FOUND:"errors.auth.USER_NOT_FOUND",USER_NOT_ACTIVE:"errors.auth.USER_NOT_ACTIVE",NO_PERMISSION:"errors.auth.NO_PERMISSION",ITEM_NOT_FOUND:"errors.data.ITEM_NOT_FOUND",NOT_FOUND:"errors.data.NOT_FOUND",IN_USE:"errors.data.IN_USE",FIELD_ERROR:"errors.data.FIELD_ERROR",BAD_REQUEST:"errors.data.BAD_REQUEST",INTERNAL_SERVER_ERROR:"errors.system.INTERNAL_SERVER_ERROR",DATABASE_CONNECTION_ERROR:"errors.system.DATABASE_CONNECTION_ERROR",INVALID_CONFIGURATION:"errors.system.INVALID_CONFIGURATION",UNKNOWN_OPERATION:"errors.system.UNKNOWN_OPERATION",TOO_MANY_REQUESTS:"errors.system.TOO_MANY_REQUESTS"},le= exports.d =(S={})=>{let{showNotification:a}=_chunkMMFYNCPIjs.h.call(void 0, ),{showSuccessNotifications:N=!1,showErrorNotifications:g=!0,customErrorMessages:T={},defaultErrorMessage:I="Ha ocurrido un error inesperado",autoHideDuration:c=6e3,appStructure:R=[],translateFn:E=e=>e}=S,d=_react.useCallback.call(void 0, e=>!(!e.success&&e.errors&&(Object.keys(e.errors).some(r=>r!=="_error"&&r!=="_graphql"&&r!=="_transaction")||_optionalChain([e, 'access', _17 => _17.errors, 'access', _18 => _18._transaction, 'optionalAccess', _19 => _19.includes, 'call', _20 => _20("ONE_OR_MORE_OPERATIONS_FAILED")])||_optionalChain([e, 'access', _21 => _21.errors, 'access', _22 => _22._error, 'optionalAccess', _23 => _23.includes, 'call', _24 => _24("TOO_MANY_REQUESTS")]))||!e.success&&_optionalChain([e, 'access', _25 => _25.data, 'optionalAccess', _26 => _26.response, 'optionalAccess', _27 => _27.status])==="TOO_MANY_REQUESTS"),[]),y=_react.useCallback.call(void 0, (e,i)=>{let r=E(e);return r===e?i||E("error.unknown"):r},[E]),A=_react.useCallback.call(void 0, e=>["create","update","delete"].includes(e),[]),_=_react.useCallback.call(void 0, (e,i)=>N?A(e)&&i?!0:R.some(r=>r.key===e):!1,[N,R,A]),p=_react.useCallback.call(void 0, (e,i,r)=>{let t=_optionalChain([r, 'optionalAccess', _28 => _28.key])&&typeof r.key=="string"?r.key:e,n=`action.onSuccess.${t}`,s=y(n);if(s!==E("error.unknown")){if(A(t)&&i){let f=`action.${i}Singular`,O=y(f);if(O!==E("error.unknown"))return E(n,{item:O});{let k=`action.onSuccess.${t}WithoutItem`,L=y(k);return L!==E("error.unknown")?L:s}}return s}return E("success.transaction")},[y,E,A]),u=_react.useCallback.call(void 0, e=>{if(e.errorCode&&T[e.errorCode])return T[e.errorCode];if(e.errorCode&&M[e.errorCode])return y(M[e.errorCode]);if(e.errorCode){let i=[`errors.auth.${e.errorCode}`,`errors.data.${e.errorCode}`,`errors.system.${e.errorCode}`,`errors.${e.errorCode}`];for(let r of i){let t=y(r);if(t!==E("error.unknown"))return t}}if(typeof e.data=="string"&&e.data.startsWith("errors.")){let i=y(e.data);if(i!==E("error.unknown"))return i}if(e.errors&&Object.keys(e.errors).length>0){let i=Object.keys(e.errors);if(i.length===1&&i[0]==="_transaction"){let r=e.errors._transaction;if(_optionalChain([r, 'optionalAccess', _29 => _29.includes, 'call', _30 => _30("ONE_OR_MORE_OPERATIONS_FAILED")]))return"";if(Array.isArray(r)&&r.length>0){let t=r[0];if(typeof t=="string"&&t!=="ONE_OR_MORE_OPERATIONS_FAILED")try{let n=JSON.parse(t);if(Array.isArray(n)&&n.length>0){let s=n[0];if(_optionalChain([s, 'optionalAccess', _31 => _31.response, 'optionalAccess', _32 => _32.errorCode])){let f=s.response.errorCode;if(M[f])return y(M[f]);let O=[`errors.auth.${f}`,`errors.data.${f}`,`errors.system.${f}`,`errors.${f}`];for(let k of O){let L=y(k);if(L!==y("error.unknown"))return L}}if(_optionalChain([s, 'optionalAccess', _33 => _33.response, 'optionalAccess', _34 => _34.data]))return s.response.data}if(_optionalChain([n, 'optionalAccess', _35 => _35.response, 'optionalAccess', _36 => _36.message])){let s=n.response.message.toLowerCase();return s.includes("expired")?y("resetPassword.linkExpired","El enlace ha expirado"):s.includes("invalid")?y("resetPassword.invalidCode","C\xF3digo inv\xE1lido"):n.response.message}}catch (e4){return t.toLowerCase().includes("expired")?y("resetPassword.linkExpired","El enlace ha expirado"):t.toLowerCase().includes("invalid")?y("resetPassword.invalidCode","C\xF3digo inv\xE1lido"):t}}return y("error.transaction","Error en la operaci\xF3n")}if(i.length===1&&i[0]==="_error"){let r=e.errors._error;return Array.isArray(r)?r[0]:String(r)}return i.length===1&&i[0]==="_graphql"?y("errors.system.DATABASE_CONNECTION_ERROR"):`${y("errors.data.FIELD_ERROR")}: ${i.join(", ")}`}return I||E("error.unknown")},[T,I,E,y]),o=_react.useCallback.call(void 0, e=>e.errorCode&&Y[e.errorCode]?Y[e.errorCode]:"error",[]),m=_react.useCallback.call(void 0, async(e,i,r)=>{let t=await _crudifybrowser2.default.createItem(e,i,r);if(!t.success&&g&&d(t)){let n=u(t),s=o(t);a(n,s,{autoHideDuration:c})}else if(t.success){let n=_optionalChain([r, 'optionalAccess', _37 => _37.actionConfig]),s=_optionalChain([n, 'optionalAccess', _38 => _38.key])||"create",f=_optionalChain([n, 'optionalAccess', _39 => _39.moduleKey])||e;if(_(s,f)){let O=p(s,f,n);a(O,"success",{autoHideDuration:c})}}return t},[g,_,a,u,o,p,c,d]),l=_react.useCallback.call(void 0, async(e,i,r)=>{let t=await _crudifybrowser2.default.updateItem(e,i,r),n=_optionalChain([r, 'optionalAccess', _40 => _40.skipNotifications])===!0;if(!n&&!t.success&&g&&d(t)){let s=u(t),f=o(t);a(s,f,{autoHideDuration:c})}else if(!n&&t.success){let s=_optionalChain([r, 'optionalAccess', _41 => _41.actionConfig]),f=_optionalChain([s, 'optionalAccess', _42 => _42.key])||"update",O=_optionalChain([s, 'optionalAccess', _43 => _43.moduleKey])||e;if(_(f,O)){let k=p(f,O,s);a(k,"success",{autoHideDuration:c})}}return t},[g,_,a,u,o,p,c,d]),x=_react.useCallback.call(void 0, async(e,i,r)=>{let t=await _crudifybrowser2.default.deleteItem(e,i,r);if(!t.success&&g&&d(t)){let n=u(t),s=o(t);a(n,s,{autoHideDuration:c})}else if(t.success){let n=_optionalChain([r, 'optionalAccess', _44 => _44.actionConfig]),s=_optionalChain([n, 'optionalAccess', _45 => _45.key])||"delete",f=_optionalChain([n, 'optionalAccess', _46 => _46.moduleKey])||e;if(_(s,f)){let O=p(s,f,n);a(O,"success",{autoHideDuration:c})}}return t},[g,_,a,u,o,p,c,d]),P=_react.useCallback.call(void 0, async(e,i,r)=>{let t=await _crudifybrowser2.default.readItem(e,i,r);if(!t.success&&g&&d(t)){let n=u(t),s=o(t);a(n,s,{autoHideDuration:c})}return t},[g,a,u,o,c,d]),w=_react.useCallback.call(void 0, async(e,i,r)=>{let t=await _crudifybrowser2.default.readItems(e,i,r);if(!t.success&&g&&d(t)){let n=u(t),s=o(t);a(n,s,{autoHideDuration:c})}return t},[g,a,u,o,c,d]),V=_react.useCallback.call(void 0, async(e,i)=>{let r=await _crudifybrowser2.default.transaction(e,i),t=_optionalChain([i, 'optionalAccess', _47 => _47.skipNotifications])===!0;if(!t&&!r.success&&g&&d(r)){let n=u(r),s=o(r);a(n,s,{autoHideDuration:c})}else if(!t&&r.success){let n="transaction",s,f=null;if(_optionalChain([i, 'optionalAccess', _48 => _48.actionConfig])?(f=i.actionConfig,n=f.key,s=f.moduleKey):Array.isArray(e)&&e.length>0&&e[0].operation&&(n=e[0].operation,f=R.find(O=>O.key===n),f&&(s=f.moduleKey)),_(n,s)){let O=p(n,s,f);a(O,"success",{autoHideDuration:c})}}return r},[g,_,a,u,o,p,c,d,R]),F=_react.useCallback.call(void 0, (e,i)=>{if(!e.success&&g&&d(e)){let r=u(e),t=o(e);a(r,t,{autoHideDuration:c})}else e.success&&N&&i&&a(i,"success",{autoHideDuration:c});return e},[g,N,a,u,o,c,d,E]);return{createItem:m,updateItem:l,deleteItem:x,readItem:P,readItems:w,transaction:V,handleResponse:F,getErrorMessage:u,getErrorSeverity:o,shouldShowNotification:d}};exports.a = G; exports.b = ee; exports.c = oe; exports.d = le;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }var _chunkFC7HOMNQjs = require('./chunk-FC7HOMNQ.js');var _react = require('react'); var _react2 = _interopRequireDefault(_react);var _crudifybrowser = require('@nocios/crudify-browser'); var _crudifybrowser2 = _interopRequireDefault(_crudifybrowser);var se=class r{constructor(){this.listeners=[];this.credentials=null;this.isReady=!1}static getInstance(){return r.instance||(r.instance=new r),r.instance}notifyCredentialsReady(i){this.credentials=i,this.isReady=!0,this.listeners.forEach(e=>{try{e(i)}catch(t){console.error("[CredentialsEventBus] Error in listener:",t)}}),this.listeners=[]}waitForCredentials(){return this.isReady&&this.credentials?Promise.resolve(this.credentials):new Promise(i=>{this.listeners.push(i)})}reset(){this.credentials=null,this.isReady=!1,this.listeners=[]}areCredentialsReady(){return this.isReady&&this.credentials!==null}},ve= exports.a =se.getInstance();var _jsxruntime = require('react/jsx-runtime');var Ee=_react.createContext.call(void 0, void 0),Ae= exports.b =({config:r,children:i})=>{let[e,t]=_react.useState.call(void 0, !0),[o,s]=_react.useState.call(void 0, null),[f,h]=_react.useState.call(void 0, !1),[S,I]=_react.useState.call(void 0, ""),[v,c]=_react.useState.call(void 0, );_react.useEffect.call(void 0, ()=>{if(!r.publicApiKey){s("No publicApiKey provided"),t(!1),h(!1);return}let l=`${r.publicApiKey}-${r.env}`;if(l===S&&f){t(!1);return}(async()=>{t(!0),s(null),h(!1);try{_crudifybrowser2.default.config(r.env||"prod");let p=await _crudifybrowser2.default.init(r.publicApiKey,"none");if(c(p),typeof _crudifybrowser2.default.transaction=="function"&&typeof _crudifybrowser2.default.login=="function")h(!0),I(l),p.apiEndpointAdmin&&p.apiKeyEndpointAdmin&&ve.notifyCredentialsReady({apiUrl:p.apiEndpointAdmin,apiKey:p.apiKeyEndpointAdmin});else throw new Error("Crudify methods not properly initialized")}catch(p){let T=p instanceof Error?p.message:"Failed to initialize Crudify";console.error("[CrudifyProvider] Initialization error:",p),s(T),h(!1)}finally{t(!1)}})()},[r.publicApiKey,r.env,S,f]);let a={crudify:f?_crudifybrowser2.default:null,isLoading:e,error:o,isInitialized:f,adminCredentials:v};return _jsxruntime.jsx.call(void 0, Ee.Provider,{value:a,children:i})},Ie= exports.c =()=>{let r=_react.useContext.call(void 0, Ee);if(r===void 0)throw new Error("useCrudify must be used within a CrudifyProvider");return r};var _cryptojs = require('crypto-js'); var _cryptojs2 = _interopRequireDefault(_cryptojs);var d=class d{static setStorageType(i){d.storageType=i}static generateEncryptionKey(){let i=[navigator.userAgent,navigator.language,navigator.platform,screen.width,screen.height,Date.now().toString(),Math.random().toString(36)].join("|");return _cryptojs2.default.SHA256(i).toString()}static getEncryptionKey(){if(d.encryptionKey)return d.encryptionKey;let i=window.localStorage;if(!i)return d.encryptionKey=d.generateEncryptionKey(),d.encryptionKey;try{let e=i.getItem(d.ENCRYPTION_KEY_STORAGE);return(!e||e.length<32)&&(e=d.generateEncryptionKey(),i.setItem(d.ENCRYPTION_KEY_STORAGE,e)),d.encryptionKey=e,e}catch (e2){return console.warn("Crudify: Cannot persist encryption key, using temporary key"),d.encryptionKey=d.generateEncryptionKey(),d.encryptionKey}}static isStorageAvailable(i){try{let e=window[i],t="__storage_test__";return e.setItem(t,"test"),e.removeItem(t),!0}catch (e3){return!1}}static getStorage(){return d.storageType==="none"?null:d.isStorageAvailable(d.storageType)?window[d.storageType]:(console.warn(`Crudify: ${d.storageType} not available, tokens won't persist`),null)}static encrypt(i){try{let e=d.getEncryptionKey();return _cryptojs2.default.AES.encrypt(i,e).toString()}catch(e){return console.error("Crudify: Encryption failed",e),i}}static decrypt(i){try{let e=d.getEncryptionKey();return _cryptojs2.default.AES.decrypt(i,e).toString(_cryptojs2.default.enc.Utf8)||i}catch(e){return console.error("Crudify: Decryption failed",e),i}}static saveTokens(i){let e=d.getStorage();if(e)try{let t={accessToken:i.accessToken,refreshToken:i.refreshToken,expiresAt:i.expiresAt,refreshExpiresAt:i.refreshExpiresAt,savedAt:Date.now()},o=d.encrypt(JSON.stringify(t));e.setItem(d.TOKEN_KEY,o),console.debug("Crudify: Tokens saved successfully")}catch(t){console.error("Crudify: Failed to save tokens",t)}}static getTokens(){let i=d.getStorage();if(!i)return null;try{let e=i.getItem(d.TOKEN_KEY);if(!e)return null;let t=d.decrypt(e),o=JSON.parse(t);return!o.accessToken||!o.refreshToken||!o.expiresAt||!o.refreshExpiresAt?(console.warn("Crudify: Incomplete token data found, clearing storage"),d.clearTokens(),null):Date.now()>=o.refreshExpiresAt?(console.info("Crudify: Refresh token expired, clearing storage"),d.clearTokens(),null):{accessToken:o.accessToken,refreshToken:o.refreshToken,expiresAt:o.expiresAt,refreshExpiresAt:o.refreshExpiresAt}}catch(e){return console.error("Crudify: Failed to retrieve tokens",e),d.clearTokens(),null}}static clearTokens(){let i=d.getStorage();if(i)try{i.removeItem(d.TOKEN_KEY),console.debug("Crudify: Tokens cleared from storage")}catch(e){console.error("Crudify: Failed to clear tokens",e)}}static rotateEncryptionKey(){try{d.clearTokens(),d.encryptionKey=null;let i=window.localStorage;i&&i.removeItem(d.ENCRYPTION_KEY_STORAGE),console.info("Crudify: Encryption key rotated successfully")}catch(i){console.error("Crudify: Failed to rotate encryption key",i)}}static hasValidTokens(){return d.getTokens()!==null}static getExpirationInfo(){let i=d.getTokens();if(!i)return null;let e=Date.now();return{accessExpired:e>=i.expiresAt,refreshExpired:e>=i.refreshExpiresAt,accessExpiresIn:Math.max(0,i.expiresAt-e),refreshExpiresIn:Math.max(0,i.refreshExpiresAt-e)}}static updateAccessToken(i,e){let t=d.getTokens();if(!t){console.warn("Crudify: Cannot update access token, no existing tokens found");return}d.saveTokens({...t,accessToken:i,expiresAt:e})}static subscribeToChanges(i){let e=t=>{if(t.key===d.TOKEN_KEY){if(t.newValue===null){console.debug("Crudify: Tokens removed in another tab"),i(null);return}if(t.newValue){console.debug("Crudify: Tokens updated in another tab");let o=d.getTokens();i(o)}}};return window.addEventListener("storage",e),()=>{window.removeEventListener("storage",e)}}};d.TOKEN_KEY="crudify_tokens",d.ENCRYPTION_KEY_STORAGE="crudify_enc_key",d.encryptionKey=null,d.storageType="localStorage";var A=d;var W=class r{constructor(){this.config={};this.initialized=!1;this.crudifyInitialized=!1;this.lastActivityTime=0;this.isRefreshingLocally=!1;this.refreshPromise=null}static getInstance(){return r.instance||(r.instance=new r),r.instance}async initialize(i={}){if(!this.initialized){if(this.config={storageType:"localStorage",autoRestore:!0,enableLogging:!1,env:"stg",...i},A.setStorageType(this.config.storageType||"localStorage"),this.config.publicApiKey&&!this.crudifyInitialized&&await this.ensureCrudifyInitialized(),_crudifybrowser2.default.setTokenInvalidationCallback(()=>{this.log("Tokens invalidated by crudify-core"),_chunkFC7HOMNQjs.h.emit("SESSION_EXPIRED",{message:"Your session has expired. Please log in again.",source:"crudify-core.clearTokensAndRefreshState"})}),this.config.apiEndpointAdmin&&this.config.apiKeyEndpointAdmin){let e=A.getTokens();e?A.saveTokens({...e,apiEndpointAdmin:this.config.apiEndpointAdmin,apiKeyEndpointAdmin:this.config.apiKeyEndpointAdmin}):A.saveTokens({accessToken:"",refreshToken:"",expiresAt:0,refreshExpiresAt:0,apiEndpointAdmin:this.config.apiEndpointAdmin,apiKeyEndpointAdmin:this.config.apiKeyEndpointAdmin})}this.config.autoRestore&&await this.restoreSession(),this.initialized=!0}}async login(i,e){try{let t=await _crudifybrowser2.default.login(i,e);if(!t.success)return{success:!1,error:this.formatError(t.errors),rawResponse:t};let o=A.getTokens(),s={accessToken:t.data.token,refreshToken:t.data.refreshToken,expiresAt:t.data.expiresAt,refreshExpiresAt:t.data.refreshExpiresAt,apiEndpointAdmin:_optionalChain([o, 'optionalAccess', _2 => _2.apiEndpointAdmin])||this.config.apiEndpointAdmin,apiKeyEndpointAdmin:_optionalChain([o, 'optionalAccess', _3 => _3.apiKeyEndpointAdmin])||this.config.apiKeyEndpointAdmin};return A.saveTokens(s),this.lastActivityTime=Date.now(),_optionalChain([this, 'access', _4 => _4.config, 'access', _5 => _5.onLoginSuccess, 'optionalCall', _6 => _6(s)]),{success:!0,tokens:s,data:t.data}}catch(t){return console.error("[SessionManager] Login error:",t),{success:!1,error:t instanceof Error?t.message:"Unknown error"}}}async logout(){try{this.log("Logging out..."),await _crudifybrowser2.default.logout(),A.clearTokens(),this.log("Logout successful"),_optionalChain([this, 'access', _7 => _7.config, 'access', _8 => _8.onLogout, 'optionalCall', _9 => _9()])}catch(i){this.log("Logout error:",i),A.clearTokens()}}async restoreSession(){try{this.log("Attempting to restore session...");let i=A.getTokens();if(!i)return this.log("No valid tokens found in storage"),!1;if(Date.now()>=i.refreshExpiresAt)return this.log("Refresh token expired, clearing storage"),A.clearTokens(),!1;if(_crudifybrowser2.default.setTokens({accessToken:i.accessToken,refreshToken:i.refreshToken,expiresAt:i.expiresAt,refreshExpiresAt:i.refreshExpiresAt}),_crudifybrowser2.default.getTokenData().isValid===!1){if(this.log("Restored access token is invalid or expired"),Date.now()<i.refreshExpiresAt&&(this.log("Access token expired but refresh is valid, attempting refresh..."),await this.refreshTokens())){this.log("Session restored successfully via token refresh");let o=A.getTokens();return o&&_optionalChain([this, 'access', _10 => _10.config, 'access', _11 => _11.onSessionRestored, 'optionalCall', _12 => _12(o)]),!0}return A.clearTokens(),await _crudifybrowser2.default.logout(),!1}return this.log("Session restored successfully"),this.lastActivityTime=Date.now(),_optionalChain([this, 'access', _13 => _13.config, 'access', _14 => _14.onSessionRestored, 'optionalCall', _15 => _15(i)]),!0}catch(i){return this.log("Session restore error:",i),A.clearTokens(),await _crudifybrowser2.default.logout(),!1}}isAuthenticated(){return _crudifybrowser2.default.isLogin()||A.hasValidTokens()}getTokenInfo(){let i=_crudifybrowser2.default.getTokenData(),e=A.getExpirationInfo(),t=A.getTokens();return{isLoggedIn:this.isAuthenticated(),crudifyTokens:i,storageInfo:e,hasValidTokens:A.hasValidTokens(),apiEndpointAdmin:_optionalChain([t, 'optionalAccess', _16 => _16.apiEndpointAdmin]),apiKeyEndpointAdmin:_optionalChain([t, 'optionalAccess', _17 => _17.apiKeyEndpointAdmin])}}async refreshTokens(){if(this.isRefreshingLocally&&this.refreshPromise)return this.log("Refresh already in progress, waiting for existing promise..."),this.refreshPromise;this.isRefreshingLocally=!0,this.refreshPromise=this._performRefresh();try{return await this.refreshPromise}finally{this.isRefreshingLocally=!1,this.refreshPromise=null}}async _performRefresh(){try{this.log("Starting token refresh...");let i=await _crudifybrowser2.default.refreshAccessToken();if(!i.success)return this.log("Token refresh failed:",i.errors),A.clearTokens(),_optionalChain([this, 'access', _18 => _18.config, 'access', _19 => _19.showNotification, 'optionalCall', _20 => _20(this.getSessionExpiredMessage(),"warning")]),_optionalChain([this, 'access', _21 => _21.config, 'access', _22 => _22.onSessionExpired, 'optionalCall', _23 => _23()]),!1;let e={accessToken:i.data.token,refreshToken:i.data.refreshToken,expiresAt:i.data.expiresAt,refreshExpiresAt:i.data.refreshExpiresAt};return A.saveTokens(e),this.log("Tokens refreshed and saved successfully"),this.lastActivityTime=Date.now(),!0}catch(i){return this.log("Token refresh error:",i),A.clearTokens(),_optionalChain([this, 'access', _24 => _24.config, 'access', _25 => _25.showNotification, 'optionalCall', _26 => _26(this.getSessionExpiredMessage(),"warning")]),_optionalChain([this, 'access', _27 => _27.config, 'access', _28 => _28.onSessionExpired, 'optionalCall', _29 => _29()]),!1}}isRefreshing(){return this.isRefreshingLocally}setupResponseInterceptor(){_crudifybrowser2.default.setResponseInterceptor(async i=>{this.updateLastActivity();let e=this.detectAuthorizationError(i);if(e.isAuthError){if(this.log("\u{1F6A8} Authorization error detected:",{errorType:e.errorType,shouldLogout:e.shouldTriggerLogout}),e.isRefreshTokenInvalid||e.isTokenRefreshFailed)return this.log("Refresh token invalid, emitting TOKEN_REFRESH_FAILED event"),_chunkFC7HOMNQjs.h.emit("TOKEN_REFRESH_FAILED",{message:e.userFriendlyMessage,error:e.errorDetails,source:"SessionManager.setupResponseInterceptor"}),i;e.shouldTriggerLogout&&(A.hasValidTokens()&&!e.isIrrecoverable?(this.log("Access token expired, emitting TOKEN_EXPIRED event"),_chunkFC7HOMNQjs.h.emit("TOKEN_EXPIRED",{message:"Access token expired, refresh needed",error:e.errorDetails,source:"SessionManager.setupResponseInterceptor"})):(this.log("No valid tokens or irrecoverable error, emitting SESSION_EXPIRED event"),_chunkFC7HOMNQjs.h.emit("SESSION_EXPIRED",{message:e.userFriendlyMessage,error:e.errorDetails,source:"SessionManager.setupResponseInterceptor"})))}return i}),this.log("Response interceptor configured (non-blocking mode)")}async ensureCrudifyInitialized(){if(!this.crudifyInitialized)try{this.log("Initializing crudify SDK...");let i=_crudifybrowser2.default.getTokenData();if(i&&i.endpoint){this.log("Crudify already initialized by another service"),this.crudifyInitialized=!0;return}let e=this.config.env||"stg";_crudifybrowser2.default.config(e);let t=this.config.publicApiKey,o=this.config.enableLogging?"debug":"none",s=await _crudifybrowser2.default.init(t,o);if(s&&s.success===!1&&s.errors)throw new Error(`Failed to initialize crudify: ${JSON.stringify(s.errors)}`);this.crudifyInitialized=!0,this.log("Crudify SDK initialized successfully")}catch(i){throw console.error("[SessionManager] Failed to initialize crudify:",i),i}}detectAuthorizationError(i){let e={isAuthError:!1,isRefreshTokenInvalid:!1,isTokenRefreshFailed:!1,isTokenExpired:!1,isUnauthorized:!1,isIrrecoverable:!1,shouldTriggerLogout:!1,errorType:"",errorDetails:null,userFriendlyMessage:""};if(i.errors&&Array.isArray(i.errors)){let t=i.errors.find(o=>o.errorType==="Unauthorized"||_optionalChain([o, 'access', _30 => _30.message, 'optionalAccess', _31 => _31.includes, 'call', _32 => _32("Unauthorized")])||_optionalChain([o, 'access', _33 => _33.message, 'optionalAccess', _34 => _34.includes, 'call', _35 => _35("Not Authorized")])||_optionalChain([o, 'access', _36 => _36.message, 'optionalAccess', _37 => _37.includes, 'call', _38 => _38("NOT_AUTHORIZED")])||_optionalChain([o, 'access', _39 => _39.message, 'optionalAccess', _40 => _40.includes, 'call', _41 => _41("Token")])||_optionalChain([o, 'access', _42 => _42.message, 'optionalAccess', _43 => _43.includes, 'call', _44 => _44("TOKEN")])||_optionalChain([o, 'access', _45 => _45.message, 'optionalAccess', _46 => _46.includes, 'call', _47 => _47("Authentication")])||_optionalChain([o, 'access', _48 => _48.message, 'optionalAccess', _49 => _49.includes, 'call', _50 => _50("UNAUTHENTICATED")])||_optionalChain([o, 'access', _51 => _51.extensions, 'optionalAccess', _52 => _52.code])==="UNAUTHENTICATED"||_optionalChain([o, 'access', _53 => _53.extensions, 'optionalAccess', _54 => _54.code])==="FORBIDDEN");t&&(e.isAuthError=!0,e.errorType="GraphQL Array",e.errorDetails=t,e.shouldTriggerLogout=!0,e.userFriendlyMessage="Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente.",(_optionalChain([t, 'access', _55 => _55.message, 'optionalAccess', _56 => _56.includes, 'call', _57 => _57("TOKEN")])||_optionalChain([t, 'access', _58 => _58.message, 'optionalAccess', _59 => _59.includes, 'call', _60 => _60("Token")]))&&(e.isTokenExpired=!0),_optionalChain([t, 'access', _61 => _61.extensions, 'optionalAccess', _62 => _62.code])==="UNAUTHENTICATED"&&(e.isUnauthorized=!0))}if(!e.isAuthError&&i.errors&&typeof i.errors=="object"&&!Array.isArray(i.errors)){let o=Object.values(i.errors).flat().find(s=>typeof s=="string"&&(s.includes("NOT_AUTHORIZED")||s.includes("TOKEN_REFRESH_FAILED")||s.includes("TOKEN_HAS_EXPIRED")||s.includes("PLEASE_LOGIN")||s.includes("Unauthorized")||s.includes("UNAUTHENTICATED")||s.includes("SESSION_EXPIRED")||s.includes("INVALID_TOKEN")));o&&typeof o=="string"&&(e.isAuthError=!0,e.errorType="GraphQL Object",e.errorDetails=i.errors,e.shouldTriggerLogout=!0,o.includes("TOKEN_REFRESH_FAILED")?(e.isTokenRefreshFailed=!0,e.isRefreshTokenInvalid=!0,e.isIrrecoverable=!0,e.userFriendlyMessage="Tu sesi\xF3n ha caducado. Por favor, inicia sesi\xF3n nuevamente."):o.includes("TOKEN_HAS_EXPIRED")||o.includes("SESSION_EXPIRED")?(e.isTokenExpired=!0,e.userFriendlyMessage="Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente."):o.includes("INVALID_TOKEN")?(e.isTokenExpired=!0,e.isIrrecoverable=!0,e.userFriendlyMessage="Token inv\xE1lido. Por favor, inicia sesi\xF3n nuevamente."):e.userFriendlyMessage="Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente.")}if(!e.isAuthError&&_optionalChain([i, 'access', _63 => _63.data, 'optionalAccess', _64 => _64.response, 'optionalAccess', _65 => _65.status])){let t=i.data.response.status.toUpperCase();(t==="UNAUTHORIZED"||t==="UNAUTHENTICATED")&&(e.isAuthError=!0,e.errorType="Status",e.errorDetails=i.data.response,e.isUnauthorized=!0,e.shouldTriggerLogout=!0,e.isIrrecoverable=!0,e.userFriendlyMessage="Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente.")}if(!e.isAuthError&&_optionalChain([i, 'access', _66 => _66.data, 'optionalAccess', _67 => _67.response, 'optionalAccess', _68 => _68.data]))try{let t=typeof i.data.response.data=="string"?JSON.parse(i.data.response.data):i.data.response.data;(t.error==="REFRESH_TOKEN_INVALID"||t.error==="TOKEN_EXPIRED"||t.error==="INVALID_TOKEN")&&(e.isAuthError=!0,e.errorType="Parsed Data",e.errorDetails=t,e.shouldTriggerLogout=!0,e.isIrrecoverable=!0,t.error==="REFRESH_TOKEN_INVALID"?(e.isRefreshTokenInvalid=!0,e.isTokenRefreshFailed=!0,e.userFriendlyMessage="Tu sesi\xF3n ha caducado. Por favor, inicia sesi\xF3n nuevamente."):(e.isTokenExpired=!0,e.userFriendlyMessage="Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente."))}catch (e4){}if(!e.isAuthError&&i.errorCode){let t=i.errorCode.toUpperCase();(t==="UNAUTHORIZED"||t==="UNAUTHENTICATED"||t==="TOKEN_EXPIRED"||t==="INVALID_TOKEN")&&(e.isAuthError=!0,e.errorType="Error Code",e.errorDetails={errorCode:t},e.shouldTriggerLogout=!0,t==="TOKEN_EXPIRED"?e.isTokenExpired=!0:e.isUnauthorized=!0,e.userFriendlyMessage="Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente.")}return e}updateLastActivity(){this.lastActivityTime=Date.now(),this.log("Last activity updated")}getTimeSinceLastActivity(){return this.lastActivityTime===0?0:Date.now()-this.lastActivityTime}checkInactivity(){let i=this.getTimeSinceLastActivity();if(this.lastActivityTime===0)return"none";let e=1800*1e3;return i>e?(this.log(`Inactivity timeout: ${Math.floor(i/6e4)} minutes since last activity`),"logout"):"none"}clearSession(){A.clearTokens(),_crudifybrowser2.default.logout(),this.lastActivityTime=0,this.log("Session cleared completely")}getSessionExpiredMessage(){return this.config.translateFn?_chunkFC7HOMNQjs.d.call(void 0, "SESSION_EXPIRED",{translateFn:this.config.translateFn,enableDebug:this.config.enableLogging}):"Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente."}log(i,...e){this.config.enableLogging&&console.log(`[SessionManager] ${i}`,...e)}formatError(i){return i?typeof i=="string"?i:typeof i=="object"?Object.values(i).flat().join(", "):"Authentication failed":"Unknown error"}};function be(r={}){let[i,e]=_react.useState.call(void 0, {isAuthenticated:!1,isLoading:!0,isInitialized:!1,tokens:null,error:null}),t=W.getInstance(),o=_react.useCallback.call(void 0, async()=>{console.log("\u{1F535} [useSession] initialize() CALLED"),console.log("\u{1F50D} [useSession] options received:",{autoRestore:r.autoRestore,enableLogging:r.enableLogging,apiEndpointAdmin:r.apiEndpointAdmin,apiKeyEndpointAdmin:r.apiKeyEndpointAdmin});try{e(n=>({...n,isLoading:!0,error:null}));let c={autoRestore:_nullishCoalesce(r.autoRestore, () => (!0)),enableLogging:_nullishCoalesce(r.enableLogging, () => (!1)),showNotification:r.showNotification,translateFn:r.translateFn,apiEndpointAdmin:r.apiEndpointAdmin,apiKeyEndpointAdmin:r.apiKeyEndpointAdmin,publicApiKey:r.publicApiKey,env:r.env||"stg",onSessionExpired:()=>{e(n=>({...n,isAuthenticated:!1,tokens:null,error:"Session expired"})),_optionalChain([r, 'access', _69 => _69.onSessionExpired, 'optionalCall', _70 => _70()])},onSessionRestored:n=>{e(p=>({...p,isAuthenticated:!0,tokens:n,error:null})),_optionalChain([r, 'access', _71 => _71.onSessionRestored, 'optionalCall', _72 => _72(n)])},onLoginSuccess:n=>{e(p=>({...p,isAuthenticated:!0,tokens:n,error:null}))},onLogout:()=>{e(n=>({...n,isAuthenticated:!1,tokens:null,error:null}))}};console.log("\u{1F50D} [useSession] Calling sessionManager.initialize() with config:",c),await t.initialize(c),console.log("\u2705 [useSession] sessionManager.initialize() completed"),t.setupResponseInterceptor();let a=t.isAuthenticated(),l=t.getTokenInfo();console.log("\u{1F50D} [useSession] After initialize, isAuth:",a),console.log("\u{1F50D} [useSession] After initialize, tokenInfo:",l),e(n=>({...n,isAuthenticated:a,isInitialized:!0,isLoading:!1,tokens:l.crudifyTokens.accessToken?{accessToken:l.crudifyTokens.accessToken,refreshToken:l.crudifyTokens.refreshToken,expiresAt:l.crudifyTokens.expiresAt,refreshExpiresAt:l.crudifyTokens.refreshExpiresAt}:null}))}catch(c){let a=c instanceof Error?c.message:"Initialization failed";e(l=>({...l,isLoading:!1,isInitialized:!0,error:a}))}},[r.autoRestore,r.enableLogging,r.onSessionExpired,r.onSessionRestored]),s=_react.useCallback.call(void 0, async(c,a)=>{e(l=>({...l,isLoading:!0,error:null}));try{let l=await t.login(c,a);return l.success&&l.tokens?e(n=>({...n,isAuthenticated:!0,tokens:l.tokens,isLoading:!1,error:null})):e(n=>({...n,isAuthenticated:!1,tokens:null,isLoading:!1,error:null})),l}catch(l){let n=l instanceof Error?l.message:"Login failed",p=n.includes("INVALID_CREDENTIALS")||n.includes("Invalid email")||n.includes("Invalid password")||n.includes("credentials");return e(T=>({...T,isAuthenticated:!1,tokens:null,isLoading:!1,error:p?null:n})),{success:!1,error:n}}},[t]),f=_react.useCallback.call(void 0, async()=>{e(c=>({...c,isLoading:!0}));try{await t.logout(),e(c=>({...c,isAuthenticated:!1,tokens:null,isLoading:!1,error:null}))}catch(c){e(a=>({...a,isAuthenticated:!1,tokens:null,isLoading:!1,error:c instanceof Error?c.message:"Logout error"}))}},[t]),h=_react.useCallback.call(void 0, async()=>{try{let c=await t.refreshTokens();if(c){let a=t.getTokenInfo();e(l=>({...l,tokens:a.crudifyTokens.accessToken?{accessToken:a.crudifyTokens.accessToken,refreshToken:a.crudifyTokens.refreshToken,expiresAt:a.crudifyTokens.expiresAt,refreshExpiresAt:a.crudifyTokens.refreshExpiresAt}:null,error:null}))}else e(a=>({...a,isAuthenticated:!1,tokens:null,error:"Token refresh failed"}));return c}catch(c){return e(a=>({...a,isAuthenticated:!1,tokens:null,error:c instanceof Error?c.message:"Token refresh failed"})),!1}},[t]),S=_react.useCallback.call(void 0, ()=>{e(c=>({...c,error:null}))},[]),I=_react.useCallback.call(void 0, ()=>t.getTokenInfo(),[t]);_react.useEffect.call(void 0, ()=>{o()},[o]),_react.useEffect.call(void 0, ()=>{if(!i.isAuthenticated||!i.tokens)return;let c=_chunkFC7HOMNQjs.i.getInstance(),a=()=>{t.updateLastActivity(),r.enableLogging&&console.log("\u{1F4CD} User navigating - activity updated")},l=c.subscribe(a);window.addEventListener("popstate",a);let n=()=>{let C=t.getTokenInfo().crudifyTokens.expiresIn||0;return C<300*1e3?30*1e3:C<1800*1e3?60*1e3:120*1e3},p,T=()=>{let k=n();p=setTimeout(async()=>{if(t.isRefreshing()){r.enableLogging&&console.log("\u23F8\uFE0F Refresh in progress, rescheduling check"),T();return}let C=t.getTokenInfo(),b=C.crudifyTokens.expiresIn||0,z=(C.crudifyTokens.expiresAt||0)-(Date.now()-b),E=z*.5;if(b>0&&b<=E){let $=Math.round(b/z*100);if(r.enableLogging&&console.log(`\u{1F504} Token at ${$}% of TTL (${Math.round(b/6e4)}min remaining), refreshing...`),e(F=>({...F,isLoading:!0})),await t.refreshTokens()){let F=t.getTokenInfo();e(re=>({...re,isLoading:!1,tokens:F.crudifyTokens.accessToken?{accessToken:F.crudifyTokens.accessToken,refreshToken:F.crudifyTokens.refreshToken,expiresAt:F.crudifyTokens.expiresAt,refreshExpiresAt:F.crudifyTokens.refreshExpiresAt}:null}))}else e(F=>({...F,isLoading:!1,isAuthenticated:!1,tokens:null}))}let _=t.getTimeSinceLastActivity(),H=1800*1e3;_>H?(r.enableLogging&&console.log("\u23F1\uFE0F Inactivity timeout (30min) - logging out"),await f()):T()},k)};return T(),()=>{clearTimeout(p),window.removeEventListener("popstate",a),l()}},[i.isAuthenticated,i.tokens,t,r.enableLogging,f]),_react.useEffect.call(void 0, ()=>{let c=_chunkFC7HOMNQjs.h.subscribe(async a=>{if(r.enableLogging&&console.log(`\u{1F4E2} useSession: Received auth event: ${a.type}`),a.type==="TOKEN_EXPIRED"){if(t.isRefreshing()){r.enableLogging&&console.log("\u23F8\uFE0F Refresh already in progress, skipping TOKEN_EXPIRED handler");return}r.enableLogging&&console.log("\u{1F504} Token expired, attempting refresh..."),e(l=>({...l,isLoading:!0}));try{if(await t.refreshTokens()){r.enableLogging&&console.log("\u2705 Token refreshed successfully");let n=t.getTokenInfo();e(p=>({...p,isLoading:!1,tokens:n.crudifyTokens.accessToken?{accessToken:n.crudifyTokens.accessToken,refreshToken:n.crudifyTokens.refreshToken,expiresAt:n.crudifyTokens.expiresAt,refreshExpiresAt:n.crudifyTokens.refreshExpiresAt}:null}))}else r.enableLogging&&console.log("\u274C Token refresh failed, session expired"),_chunkFC7HOMNQjs.h.emit("SESSION_EXPIRED",{message:"Failed to refresh token after detecting expiration",source:"useSession.TOKEN_EXPIRED handler"})}catch(l){r.enableLogging&&console.error("\u274C Error during token refresh:",l),_chunkFC7HOMNQjs.h.emit("SESSION_EXPIRED",{message:l instanceof Error?l.message:"Unknown error during refresh",source:"useSession.TOKEN_EXPIRED handler (error)"})}}(a.type==="SESSION_EXPIRED"||a.type==="TOKEN_REFRESH_FAILED")&&(r.enableLogging&&console.log(`\u{1F534} Session expired (${a.type}), logging out...`),e(l=>({...l,isAuthenticated:!1,tokens:null,isLoading:!1,error:_optionalChain([a, 'access', _73 => _73.details, 'optionalAccess', _74 => _74.message])||"Session expired"})),_optionalChain([r, 'access', _75 => _75.onSessionExpired, 'optionalCall', _76 => _76()]))});return()=>c()},[r.enableLogging,r.onSessionExpired,t]),_react.useEffect.call(void 0, ()=>{let c=A.subscribeToChanges(a=>{a?(r.enableLogging&&console.log("\u{1F504} Tokens updated in another tab"),e(l=>({...l,tokens:a,isAuthenticated:!0}))):(r.enableLogging&&console.log("\u{1F504} Logout detected in another tab"),e(l=>({...l,isAuthenticated:!1,tokens:null})),_chunkFC7HOMNQjs.h.emit("SESSION_EXPIRED",{message:"Sesi\xF3n cerrada en otra pesta\xF1a",source:"CrossTabSync"}))});return()=>c()},[r.enableLogging]);let v=_react.useCallback.call(void 0, ()=>{t.updateLastActivity()},[t]);return{...i,login:s,logout:f,refreshTokens:h,clearError:S,getTokenInfo:I,updateActivity:v,isExpiringSoon:i.tokens?i.tokens.expiresAt-Date.now()<300*1e3:!1,expiresIn:i.tokens?Math.max(0,i.tokens.expiresAt-Date.now()):0,refreshExpiresIn:i.tokens?Math.max(0,i.tokens.refreshExpiresAt-Date.now()):0}}var _material = require('@mui/material');var _uuid = require('uuid');var _dompurify = require('dompurify'); var _dompurify2 = _interopRequireDefault(_dompurify);var xe=_react.createContext.call(void 0, null),je=r=>_dompurify2.default.sanitize(r,{ALLOWED_TAGS:["b","i","em","strong","br","span"],ALLOWED_ATTR:["class"],FORBID_TAGS:["script","iframe","object","embed"],FORBID_ATTR:["onload","onerror","onclick","onmouseover","onfocus","onblur"],WHOLE_DOCUMENT:!1,RETURN_DOM:!1,RETURN_DOM_FRAGMENT:!1,RETURN_TRUSTED_TYPE:!1}),ae= exports.g =({children:r,maxNotifications:i=5,defaultAutoHideDuration:e=6e3,position:t={vertical:"top",horizontal:"right"},enabled:o=!1,allowHtml:s=!1})=>{let[f,h]=_react.useState.call(void 0, []),S=_react.useCallback.call(void 0, (a,l="info",n)=>{if(!o)return"";if(!a||typeof a!="string")return console.warn("\u26A0\uFE0F GlobalNotificationProvider: Invalid message provided"),"";a.length>1e3&&(console.warn("\u26A0\uFE0F GlobalNotificationProvider: Message too long, truncating"),a=a.substring(0,1e3)+"...");let p=_uuid.v4.call(void 0, ),T={id:p,message:a,severity:l,autoHideDuration:_nullishCoalesce(_optionalChain([n, 'optionalAccess', _77 => _77.autoHideDuration]), () => (e)),persistent:_nullishCoalesce(_optionalChain([n, 'optionalAccess', _78 => _78.persistent]), () => (!1)),allowHtml:_nullishCoalesce(_optionalChain([n, 'optionalAccess', _79 => _79.allowHtml]), () => (s))};return h(k=>[...k.length>=i?k.slice(-(i-1)):k,T]),p},[i,e,o,s]),I=_react.useCallback.call(void 0, a=>{h(l=>l.filter(n=>n.id!==a))},[]),v=_react.useCallback.call(void 0, ()=>{h([])},[]),c={showNotification:S,hideNotification:I,clearAllNotifications:v};return _jsxruntime.jsxs.call(void 0, xe.Provider,{value:c,children:[r,o&&_jsxruntime.jsx.call(void 0, _material.Portal,{children:_jsxruntime.jsx.call(void 0, _material.Box,{sx:{position:"fixed",zIndex:9999,[t.vertical]:(t.vertical==="top",24),[t.horizontal]:t.horizontal==="right"||t.horizontal==="left"?24:"50%",...t.horizontal==="center"&&{transform:"translateX(-50%)"},display:"flex",flexDirection:t.vertical==="top"?"column":"column-reverse",gap:1,maxWidth:"400px",width:"auto"},children:f.map(a=>_jsxruntime.jsx.call(void 0, Qe,{notification:a,onClose:()=>I(a.id)},a.id))})})]})},Qe=({notification:r,onClose:i})=>{let[e,t]=_react.useState.call(void 0, !0),o=_react.useCallback.call(void 0, (s,f)=>{f!=="clickaway"&&(t(!1),setTimeout(i,300))},[i]);return _react.useEffect.call(void 0, ()=>{if(!r.persistent&&r.autoHideDuration){let s=setTimeout(()=>{o()},r.autoHideDuration);return()=>clearTimeout(s)}},[r.autoHideDuration,r.persistent,o]),_jsxruntime.jsx.call(void 0, _material.Snackbar,{open:e,onClose:o,sx:{position:"relative","& .MuiSnackbarContent-root":{minWidth:"auto"}},TransitionProps:{enter:!0,exit:!0},children:_jsxruntime.jsx.call(void 0, _material.Alert,{variant:"filled",severity:r.severity,onClose:o,sx:{width:"100%",minWidth:"280px",maxWidth:"400px",wordBreak:"break-word"},children:r.allowHtml?_jsxruntime.jsx.call(void 0, "span",{dangerouslySetInnerHTML:{__html:je(r.message)}}):_jsxruntime.jsx.call(void 0, "span",{children:r.message})})})},Se= exports.h =()=>{let r=_react.useContext.call(void 0, xe);if(!r)throw new Error("useGlobalNotification debe ser usado dentro de un GlobalNotificationProvider");return r};var Ne=_react.createContext.call(void 0, void 0);function Pe({children:r,options:i={},config:e,showNotifications:t=!1,notificationOptions:o={}}){let s;try{let{showNotification:n}=Se();s=n}catch (e5){}let f={};try{let n=Ie();n.isInitialized&&n.adminCredentials&&(f=n.adminCredentials)}catch (e6){}let h=_react.useMemo.call(void 0, ()=>{let n=_chunkFC7HOMNQjs.b.call(void 0, {publicApiKey:_optionalChain([e, 'optionalAccess', _80 => _80.publicApiKey]),env:_optionalChain([e, 'optionalAccess', _81 => _81.env]),enableDebug:_optionalChain([i, 'optionalAccess', _82 => _82.enableLogging])});return{publicApiKey:n.publicApiKey,env:n.env||"prod"}},[e,_optionalChain([i, 'optionalAccess', _83 => _83.enableLogging])]),S=_react2.default.useMemo(()=>({...i,showNotification:s,apiEndpointAdmin:f.apiEndpointAdmin,apiKeyEndpointAdmin:f.apiKeyEndpointAdmin,publicApiKey:h.publicApiKey,env:h.env,onSessionExpired:()=>{_optionalChain([i, 'access', _84 => _84.onSessionExpired, 'optionalCall', _85 => _85()])}}),[i,s,f.apiEndpointAdmin,f.apiKeyEndpointAdmin,h]),I=be(S),v=_react.useMemo.call(void 0, ()=>{let n=_chunkFC7HOMNQjs.b.call(void 0, {publicApiKey:_optionalChain([e, 'optionalAccess', _86 => _86.publicApiKey]),env:_optionalChain([e, 'optionalAccess', _87 => _87.env]),appName:_optionalChain([e, 'optionalAccess', _88 => _88.appName]),logo:_optionalChain([e, 'optionalAccess', _89 => _89.logo]),loginActions:_optionalChain([e, 'optionalAccess', _90 => _90.loginActions]),enableDebug:_optionalChain([i, 'optionalAccess', _91 => _91.enableLogging])});return{publicApiKey:n.publicApiKey,env:n.env,appName:n.appName,loginActions:n.loginActions,logo:n.logo}},[e,_optionalChain([i, 'optionalAccess', _92 => _92.enableLogging])]),c=_react.useMemo.call(void 0, ()=>{if(!_optionalChain([I, 'access', _93 => _93.tokens, 'optionalAccess', _94 => _94.accessToken])||!I.isAuthenticated)return null;try{let n=_chunkFC7HOMNQjs.j.call(void 0, I.tokens.accessToken);if(n&&n.sub&&n.email&&n.subscriber){let p={_id:n.sub,email:n.email,subscriberKey:n.subscriber};return Object.keys(n).forEach(T=>{["sub","email","subscriber"].includes(T)||(p[T]=n[T])}),p}}catch(n){console.error("Error decoding JWT token for sessionData:",n)}return null},[_optionalChain([I, 'access', _95 => _95.tokens, 'optionalAccess', _96 => _96.accessToken]),I.isAuthenticated]),a={...I,sessionData:c,config:v},l={enabled:t,maxNotifications:o.maxNotifications||5,defaultAutoHideDuration:o.defaultAutoHideDuration||6e3,position:o.position||{vertical:"top",horizontal:"right"}};return _jsxruntime.jsx.call(void 0, Ne.Provider,{value:a,children:r})}function ji(r){let i={enabled:r.showNotifications,maxNotifications:_optionalChain([r, 'access', _97 => _97.notificationOptions, 'optionalAccess', _98 => _98.maxNotifications])||5,defaultAutoHideDuration:_optionalChain([r, 'access', _99 => _99.notificationOptions, 'optionalAccess', _100 => _100.defaultAutoHideDuration])||6e3,position:_optionalChain([r, 'access', _101 => _101.notificationOptions, 'optionalAccess', _102 => _102.position])||{vertical:"top",horizontal:"right"},allowHtml:_optionalChain([r, 'access', _103 => _103.notificationOptions, 'optionalAccess', _104 => _104.allowHtml])||!1};return _optionalChain([r, 'access', _105 => _105.config, 'optionalAccess', _106 => _106.publicApiKey])?_jsxruntime.jsx.call(void 0, Ae,{config:{publicApiKey:r.config.publicApiKey,env:r.config.env||"prod",appName:r.config.appName,loginActions:r.config.loginActions,logo:r.config.logo},children:_jsxruntime.jsx.call(void 0, ae,{...i,children:_jsxruntime.jsx.call(void 0, Pe,{...r})})}):_jsxruntime.jsx.call(void 0, ae,{...i,children:_jsxruntime.jsx.call(void 0, Pe,{...r})})}function ni(){let r=_react.useContext.call(void 0, Ne);if(r===void 0)throw new Error("useSessionContext must be used within a SessionProvider");return r}function Qi(){let r=ni();return r.isInitialized?_jsxruntime.jsxs.call(void 0, "div",{style:{padding:"10px",margin:"10px",border:"1px solid #ccc",borderRadius:"4px",fontSize:"12px",fontFamily:"monospace"},children:[_jsxruntime.jsx.call(void 0, "h4",{children:"Session Debug Info"}),_jsxruntime.jsxs.call(void 0, "div",{children:[_jsxruntime.jsx.call(void 0, "strong",{children:"Authenticated:"})," ",r.isAuthenticated?"Yes":"No"]}),_jsxruntime.jsxs.call(void 0, "div",{children:[_jsxruntime.jsx.call(void 0, "strong",{children:"Loading:"})," ",r.isLoading?"Yes":"No"]}),_jsxruntime.jsxs.call(void 0, "div",{children:[_jsxruntime.jsx.call(void 0, "strong",{children:"Error:"})," ",r.error||"None"]}),r.tokens&&_jsxruntime.jsxs.call(void 0, _jsxruntime.Fragment,{children:[_jsxruntime.jsxs.call(void 0, "div",{children:[_jsxruntime.jsx.call(void 0, "strong",{children:"Access Token:"})," ",r.tokens.accessToken.substring(0,20),"..."]}),_jsxruntime.jsxs.call(void 0, "div",{children:[_jsxruntime.jsx.call(void 0, "strong",{children:"Refresh Token:"})," ",r.tokens.refreshToken.substring(0,20),"..."]}),_jsxruntime.jsxs.call(void 0, "div",{children:[_jsxruntime.jsx.call(void 0, "strong",{children:"Access Expires In:"})," ",Math.round(r.expiresIn/1e3/60)," minutes"]}),_jsxruntime.jsxs.call(void 0, "div",{children:[_jsxruntime.jsx.call(void 0, "strong",{children:"Refresh Expires In:"})," ",Math.round(r.refreshExpiresIn/1e3/60/60)," hours"]}),_jsxruntime.jsxs.call(void 0, "div",{children:[_jsxruntime.jsx.call(void 0, "strong",{children:"Expiring Soon:"})," ",r.isExpiringSoon?"Yes":"No"]})]})]}):_jsxruntime.jsx.call(void 0, "div",{children:"Session not initialized"})}var ot=(r={})=>{let{autoFetch:i=!0,retryOnError:e=!1,maxRetries:t=3}=r,[o,s]=_react.useState.call(void 0, null),[f,h]=_react.useState.call(void 0, !1),[S,I]=_react.useState.call(void 0, null),[v,c]=_react.useState.call(void 0, {}),a=_react.useRef.call(void 0, null),l=_react.useRef.call(void 0, !0),n=_react.useRef.call(void 0, 0),p=_react.useRef.call(void 0, 0),T=_react.useCallback.call(void 0, ()=>{s(null),I(null),h(!1),c({})},[]),k=_react.useCallback.call(void 0, async()=>{let C=_chunkFC7HOMNQjs.k.call(void 0, );if(!C){l.current&&(I("No user email available"),h(!1));return}a.current&&a.current.abort();let b=new AbortController;a.current=b;let P=++n.current;try{l.current&&(h(!0),I(null));let z=await _crudifybrowser2.default.readItems("users",{filter:{email:C},pagination:{limit:1}});if(P===n.current&&l.current&&!b.signal.aborted)if(z.success&&z.data&&z.data.length>0){let E=z.data[0];s(E);let _={fullProfile:E,totalFields:Object.keys(E).length,displayData:{id:E.id,email:E.email,username:E.username,firstName:E.firstName,lastName:E.lastName,fullName:E.fullName||`${E.firstName||""} ${E.lastName||""}`.trim(),role:E.role,permissions:E.permissions||[],isActive:E.isActive,lastLogin:E.lastLogin,createdAt:E.createdAt,updatedAt:E.updatedAt,...Object.keys(E).filter(H=>!["id","email","username","firstName","lastName","fullName","role","permissions","isActive","lastLogin","createdAt","updatedAt"].includes(H)).reduce((H,$)=>({...H,[$]:E[$]}),{})}};c(_),I(null),p.current=0}else I("User profile not found"),s(null),c({})}catch(z){if(P===n.current&&l.current){let E=z;if(E.name==="AbortError")return;e&&p.current<t&&(_optionalChain([E, 'access', _107 => _107.message, 'optionalAccess', _108 => _108.includes, 'call', _109 => _109("Network Error")])||_optionalChain([E, 'access', _110 => _110.message, 'optionalAccess', _111 => _111.includes, 'call', _112 => _112("Failed to fetch")]))?(p.current++,setTimeout(()=>{l.current&&k()},1e3*p.current)):(I("Failed to load user profile"),s(null),c({}))}}finally{P===n.current&&l.current&&h(!1),a.current===b&&(a.current=null)}},[e,t]);return _react.useEffect.call(void 0, ()=>{i&&k()},[i,k]),_react.useEffect.call(void 0, ()=>(l.current=!0,()=>{l.current=!1,a.current&&(a.current.abort(),a.current=null)}),[]),{userProfile:o,loading:f,error:S,extendedData:v,refreshProfile:k,clearProfile:T}};var ct=(r,i={})=>{let{autoFetch:e=!0,onSuccess:t,onError:o}=i,{prefix:s,padding:f=0,separator:h=""}=r,[S,I]=_react.useState.call(void 0, ""),[v,c]=_react.useState.call(void 0, !1),[a,l]=_react.useState.call(void 0, null),n=_react.useRef.call(void 0, !1),p=_react.useCallback.call(void 0, b=>{let P=String(b).padStart(f,"0");return`${s}${h}${P}`},[s,f,h]),T=_react.useCallback.call(void 0, async()=>{c(!0),l(null);try{let b=await _crudifybrowser2.default.getNextSequence(s);if(b.success&&_optionalChain([b, 'access', _113 => _113.data, 'optionalAccess', _114 => _114.value])){let P=p(b.data.value);I(P),_optionalChain([t, 'optionalCall', _115 => _115(P)])}else{let P=_optionalChain([b, 'access', _116 => _116.errors, 'optionalAccess', _117 => _117._error, 'optionalAccess', _118 => _118[0]])||"Failed to generate code";l(P),_optionalChain([o, 'optionalCall', _119 => _119(P)])}}catch(b){let P=b instanceof Error?b.message:"Unknown error";l(P),_optionalChain([o, 'optionalCall', _120 => _120(P)])}finally{c(!1)}},[s,p,t,o]),k=_react.useCallback.call(void 0, async()=>{await T()},[T]),C=_react.useCallback.call(void 0, ()=>{l(null)},[]);return _react.useEffect.call(void 0, ()=>{e&&!S&&!n.current&&(n.current=!0,T())},[e,S,T]),{value:S,loading:v,error:a,regenerate:k,clearError:C}};var de=class r{constructor(){this.state={status:"UNINITIALIZED",priority:null,publicApiKey:null,env:null,error:null,initializedBy:null};this.initializationPromise=null;this.highPriorityInitializerPresent=!1;this.waitingForHighPriority=new Set;this.HIGH_PRIORITY_WAIT_TIMEOUT=100}static getInstance(){return r.instance||(r.instance=new r),r.instance}registerHighPriorityInitializer(){this.highPriorityInitializerPresent=!0}isHighPriorityInitializerPresent(){return this.highPriorityInitializerPresent}getState(){return{...this.state}}async initialize(i){let{priority:e,publicApiKey:t,env:o,enableLogging:s,requestedBy:f}=i;if(this.state.status==="INITIALIZED"){this.state.publicApiKey!==t&&console.warn(`[CrudifyInitialization] ${f} attempted to initialize with different key. Already initialized with key: ${_optionalChain([this, 'access', _121 => _121.state, 'access', _122 => _122.publicApiKey, 'optionalAccess', _123 => _123.slice, 'call', _124 => _124(0,10)])}... by ${this.state.initializedBy}`);return}if(this.initializationPromise)return s&&console.log(`[CrudifyInitialization] ${f} waiting for ongoing initialization...`),this.initializationPromise;if(e==="LOW"&&this.highPriorityInitializerPresent&&this.state.status==="UNINITIALIZED"){if(s&&console.log(`[CrudifyInitialization] ${f} (LOW priority) waiting for HIGH priority initializer...`),this.waitingForHighPriority.add(f),await this.waitForHighPriorityOrTimeout(s),this.waitingForHighPriority.delete(f),this.getState().status==="INITIALIZED"){s&&console.log(`[CrudifyInitialization] ${f} found initialization completed by HIGH priority`);return}s&&console.warn(`[CrudifyInitialization] ${f} timeout waiting for HIGH priority, initializing with LOW priority`)}e==="HIGH"&&this.state.status==="INITIALIZING"&&this.state.priority==="LOW"&&(console.warn(`[CrudifyInitialization] HIGH priority request from ${f} interrupting LOW priority initialization by ${this.state.initializedBy}`),this.state.status="UNINITIALIZED",this.initializationPromise=null),s&&console.log(`[CrudifyInitialization] ${f} starting initialization (${e} priority)...`),this.state.status="INITIALIZING",this.state.priority=e,this.state.initializedBy=f,this.initializationPromise=this.performInitialization(t,o,s);try{await this.initializationPromise,this.state.status="INITIALIZED",this.state.publicApiKey=t,this.state.env=o,this.state.error=null,s&&console.log(`[CrudifyInitialization] \u2705 Successfully initialized by ${f} (${e} priority)`)}catch(h){throw this.state.status="ERROR",this.state.error=h instanceof Error?h:new Error(String(h)),this.initializationPromise=null,console.error(`[CrudifyInitialization] \u274C Initialization failed for ${f}:`,h),h}}async waitForHighPriorityOrTimeout(i){return new Promise(e=>{let o=0,s=setInterval(()=>{if(o+=10,this.state.status==="INITIALIZED"&&this.state.priority==="HIGH"){clearInterval(s),e();return}if(this.state.status==="INITIALIZING"&&this.state.priority==="HIGH"){o=0;return}o>=this.HIGH_PRIORITY_WAIT_TIMEOUT&&(clearInterval(s),i&&console.log(`[CrudifyInitialization] Timeout waiting for HIGH priority (${this.HIGH_PRIORITY_WAIT_TIMEOUT}ms)`),e())},10)})}async performInitialization(i,e,t){let o=_crudifybrowser2.default.getTokenData();if(o&&o.endpoint){t&&console.log("[CrudifyInitialization] SDK already initialized externally");return}_crudifybrowser2.default.config(e);let s=t?"debug":"none",f=await _crudifybrowser2.default.init(i,s);if(f.success===!1)throw new Error(`Crudify initialization failed: ${JSON.stringify(f.errors||"Unknown error")}`)}reset(){this.state={status:"UNINITIALIZED",priority:null,publicApiKey:null,env:null,error:null,initializedBy:null},this.initializationPromise=null,this.highPriorityInitializerPresent=!1,this.waitingForHighPriority.clear()}isInitialized(){return this.state.status==="INITIALIZED"}getDiagnostics(){return{...this.state,waitingCount:this.waitingForHighPriority.size,waitingComponents:Array.from(this.waitingForHighPriority),hasActivePromise:this.initializationPromise!==null}}},ie= exports.o =de.getInstance();var Le=()=>`file_${Date.now()}_${Math.random().toString(36).substring(2,9)}`,ht= exports.p =(r={})=>{let{acceptedTypes:i,maxFileSize:e=10*1024*1024,maxFiles:t,minFiles:o=0,visibility:s="private",onUploadComplete:f,onUploadError:h,onFileRemoved:S,onFilesChange:I}=r,[v,c]=_react.useState.call(void 0, []),[a,l]=_react.useState.call(void 0, !1),n=_react.useRef.call(void 0, new Map),p=_react.useCallback.call(void 0, ()=>{l(!0)},[]),T=_react.useCallback.call(void 0, (u,y)=>{c(g=>g.map(m=>m.id===u?{...m,...y}:m))},[]),k=_react.useCallback.call(void 0, u=>{_optionalChain([I, 'optionalCall', _125 => _125(u)])},[I]),C=_react.useCallback.call(void 0, u=>i&&i.length>0&&!i.includes(u.type)?{valid:!1,error:`Tipo de archivo no permitido: ${u.type}`}:u.size>e?{valid:!1,error:`El archivo excede el tama\xF1o m\xE1ximo de ${(e/1048576).toFixed(1)}MB`}:{valid:!0},[i,e]),b=_react.useCallback.call(void 0, async(u,y)=>{try{if(!ie.isInitialized())throw new Error("Crudify no est\xE1 inicializado. Por favor espere a que la aplicaci\xF3n termine de cargar.");let g=await _crudifybrowser2.default.generateSignedUrl({fileName:y.name,contentType:y.type,visibility:s});if(!g.success||!g.data)throw new Error("No se pudo obtener URL de upload");let{uploadUrl:R,s3Key:m,publicUrl:x}=g.data;if(!R||!m)throw new Error("Respuesta de signed URL incompleta");let U=m.indexOf("/"),Ke=U>0?m.substring(U+1):m;T(u.id,{status:"uploading",progress:0}),await new Promise((X,V)=>{let L=new XMLHttpRequest;L.upload.addEventListener("progress",ne=>{if(ne.lengthComputable){let Oe=Math.round(ne.loaded/ne.total*100);T(u.id,{progress:Oe})}}),L.addEventListener("load",()=>{L.status>=200&&L.status<300?X():V(new Error(`Upload fall\xF3 con status ${L.status}`))}),L.addEventListener("error",()=>{V(new Error("Error de red durante el upload"))}),L.addEventListener("abort",()=>{V(new Error("Upload cancelado"))}),L.open("PUT",R),L.setRequestHeader("Content-Type",y.type),L.send(y)});let pe={status:"completed",progress:100,filePath:Ke,visibility:s,publicUrl:s==="public"?x:void 0,file:void 0};T(u.id,pe),c(X=>{let V=X.find(L=>L.id===u.id);return V&&_optionalChain([f, 'optionalCall', _126 => _126({...V,...pe})]),X})}catch(g){let R=g instanceof Error?g.message:"Error desconocido";T(u.id,{status:"error",progress:0,errorMessage:R}),c(m=>{let x=m.find(U=>U.id===u.id);return x&&_optionalChain([h, 'optionalCall', _127 => _127(x,R)]),m})}},[T,f,h,s]),P=_react.useCallback.call(void 0, async u=>{let y=Array.from(u);if(t!==void 0){let m=v.filter(U=>U.status!=="error").length,x=t-m;if(x<=0){console.warn(`Ya se alcanz\xF3 el l\xEDmite de ${t} archivos`);return}y.length>x&&(y.splice(x),console.warn(`Solo se agregar\xE1n ${x} archivos para no exceder el l\xEDmite`))}let g=[];for(let m of y){let x=C(m),U={id:Le(),name:m.name,size:m.size,contentType:m.type,status:x.valid?"pending":"error",progress:0,createdAt:Date.now(),file:x.valid?m:void 0,errorMessage:x.error};g.push(U)}c(m=>{let x=[...m,...g];return k(x),x});let R=g.filter(m=>m.status==="pending"&&m.file);for(let m of R)if(m.file){let x=b(m,m.file);n.current.set(m.id,x),x.finally(()=>{n.current.delete(m.id)})}},[v,t,C,b,k]),z=_react.useCallback.call(void 0, async u=>{let y=v.find(g=>g.id===u);if(!y)return!1;T(u,{status:"removing"});try{if(y.filePath){if(!ie.isInitialized())throw new Error("Crudify no est\xE1 inicializado. Por favor espere a que la aplicaci\xF3n termine de cargar.");if(!(await _crudifybrowser2.default.disableFile({filePath:y.filePath})).success)throw new Error("No se pudo eliminar el archivo del servidor")}return c(g=>{let R=g.filter(m=>m.id!==u);return k(R),R}),_optionalChain([S, 'optionalCall', _128 => _128(y)]),!0}catch(g){return T(u,{status:y.filePath?"completed":"error",errorMessage:g instanceof Error?g.message:"Error al eliminar"}),!1}},[v,T,k,S]),E=_react.useCallback.call(void 0, ()=>{c([]),k([])},[k]),_=_react.useCallback.call(void 0, async u=>{let y=v.find(R=>R.id===u);if(!y||y.status!=="error"||!y.file){console.warn("No se puede reintentar: archivo no encontrado o sin archivo original");return}T(u,{status:"pending",progress:0,errorMessage:void 0});let g=b(y,y.file);n.current.set(u,g),g.finally(()=>{n.current.delete(u)})},[v,T,b]),H=_react.useCallback.call(void 0, async()=>{let u=Array.from(n.current.values());u.length>0&&await Promise.allSettled(u)},[]),$=_react.useCallback.call(void 0, u=>{let y=u.map(g=>{let R=g.filePath.startsWith("public/")?"public":"private";return{id:Le(),name:g.name,size:g.size||0,contentType:g.contentType||"application/octet-stream",status:"completed",progress:100,filePath:g.filePath,visibility:R,createdAt:Date.now()}});c(y),k(y)},[k]),ge=_react.useCallback.call(void 0, async u=>{let y=v.find(g=>g.id===u);if(!y||!y.filePath)return null;if(y.visibility==="public"&&y.publicUrl)return y.publicUrl;try{if(!ie.isInitialized())return null;let g=await _crudifybrowser2.default.getFileUrl({filePath:y.filePath,expiresIn:3600});return g.success&&_optionalChain([g, 'access', _129 => _129.data, 'optionalAccess', _130 => _130.url])?g.data.url:null}catch (e7){return null}},[v]),F=_react.useMemo.call(void 0, ()=>v.some(u=>u.status==="uploading"||u.status==="pending"),[v]),re=_react.useMemo.call(void 0, ()=>v.filter(u=>u.status==="uploading"||u.status==="pending").length,[v]),De=_react.useMemo.call(void 0, ()=>v.filter(u=>u.status==="completed"&&u.filePath).map(u=>u.filePath),[v]),{isValid:ze,validationError:Fe}=_react.useMemo.call(void 0, ()=>{let u=v.filter(g=>g.status==="completed").length;return u<o?{isValid:!1,validationError:o===1?"Se requiere al menos un archivo":`Se requieren al menos ${o} archivos`}:t!==void 0&&u>t?{isValid:!1,validationError:`M\xE1ximo ${t} archivos permitidos`}:v.some(g=>g.status==="error")?{isValid:!1,validationError:"Algunos archivos tienen errores"}:{isValid:!0,validationError:null}},[v,o,t]);return{files:v,isUploading:F,pendingCount:re,addFiles:P,removeFile:z,clearFiles:E,retryUpload:_,isValid:ze,validationError:Fe,waitForUploads:H,completedFilePaths:De,initializeFiles:$,isTouched:a,markAsTouched:p,getPreviewUrl:ge}};exports.a = ve; exports.b = Ae; exports.c = Ie; exports.d = A; exports.e = W; exports.f = be; exports.g = ae; exports.h = Se; exports.i = ji; exports.j = ni; exports.k = Qi; exports.l = ot; exports.m = ct; exports.n = de; exports.o = ie; exports.p = ht;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{h as $,j as D}from"./chunk-4E2PRDUC.mjs";import{useState as K,useEffect as z,useCallback as j,useRef as v}from"react";import Q from"@nocios/crudify-browser";var G=(S={})=>{let{autoFetch:a=!0,retryOnError:N=!1,maxRetries:g=3}=S,{isAuthenticated:T,isInitialized:I,sessionData:c,tokens:R}=D(),[E,d]=K(null),[y,A]=K(a&&T),[_,p]=K(null),u=v(null),o=v(!0),m=v(0),l=v(0),x=j(()=>c&&(c.email||c["cognito:username"])||null,[c]),P=j(()=>{d(null),p(null),A(!1),l.current=0},[]),w=j(async()=>{let F=x();if(!F){o.current&&(p("No user email available from session data"),A(!1));return}if(!I){o.current&&(p("Session not initialized"),A(!1));return}u.current&&u.current.abort();let e=new AbortController;u.current=e;let i=++m.current;try{o.current&&(A(!0),p(null));let r=await Q.readItems("users",{filter:{email:F},pagination:{limit:1}});if(i===m.current&&o.current&&!e.signal.aborted){let t=null;if(r.success){if(Array.isArray(r.data)&&r.data.length>0)t=r.data[0];else if(r.data?.response?.data)try{let n=r.data.response.data,s=typeof n=="string"?JSON.parse(n):n;s&&s.items&&Array.isArray(s.items)&&s.items.length>0&&(t=s.items[0])}catch{}else if(r.data&&typeof r.data=="object")r.data.items&&Array.isArray(r.data.items)&&r.data.items.length>0&&(t=r.data.items[0]);else if(r.data?.data?.response?.data)try{let n=r.data.data.response.data,s=typeof n=="string"?JSON.parse(n):n;s&&s.items&&Array.isArray(s.items)&&s.items.length>0&&(t=s.items[0])}catch{}}t?(d(t),p(null),l.current=0):(p("User profile not found in database"),d(null))}}catch(r){if(i===m.current&&o.current){let t=r;if(t.name==="AbortError")return;N&&l.current<g&&(t.message?.includes("Network Error")||t.message?.includes("Failed to fetch"))?(l.current++,setTimeout(()=>{o.current&&w()},1e3*l.current)):(p("Failed to load user profile from database"),d(null))}}finally{i===m.current&&o.current&&A(!1),u.current===e&&(u.current=null)}},[I,x,N,g]);return z(()=>{a&&T&&I?w():T||P()},[a,T,I,w,P]),z(()=>(o.current=!0,()=>{o.current=!1,u.current&&(u.current.abort(),u.current=null)}),[]),{user:{session:c,data:E},loading:y,error:_,refreshProfile:w,clearProfile:P}};import{useCallback as W}from"react";var ee=()=>{let{isAuthenticated:S,isLoading:a,isInitialized:N,tokens:g,error:T,sessionData:I,login:c,logout:R,refreshTokens:E,clearError:d,getTokenInfo:y,isExpiringSoon:A,expiresIn:_,refreshExpiresIn:p}=D(),u=W(m=>{m?console.warn("useAuth.setToken() is deprecated. Use login() method instead for better security."):R()},[R]),o=g?.expiresAt?new Date(g.expiresAt):null;return{isAuthenticated:S,loading:a,error:T,token:g?.accessToken||null,user:I,tokenExpiration:o,setToken:u,logout:R,refreshToken:E,login:c,isExpiringSoon:A,expiresIn:_,refreshExpiresIn:p,getTokenInfo:y,clearError:d}};import{useCallback as h}from"react";import U from"@nocios/crudify-browser";var oe=()=>{let{isInitialized:S,isLoading:a,error:N,isAuthenticated:g,login:T}=D(),I=h(()=>S&&!a&&!N,[S,a,N]),c=h(async()=>new Promise((o,m)=>{let l=()=>{I()?o():N?m(new Error(N)):setTimeout(l,100)};l()}),[I,N]),R=h(async()=>{if(!I())throw new Error("System not ready. Check isInitialized, isLoading, and error states.")},[I]),E=h(async(o,m,l)=>(await R(),await U.readItems(o,m||{},l)),[R]),d=h(async(o,m,l)=>(await R(),await U.readItem(o,m,l)),[R]),y=h(async(o,m,l)=>(await R(),await U.createItem(o,m,l)),[R]),A=h(async(o,m,l)=>(await R(),await U.updateItem(o,m,l)),[R]),_=h(async(o,m,l)=>(await R(),await U.deleteItem(o,m,l)),[R]),p=h(async(o,m)=>(await R(),await U.transaction(o,m)),[R]),u=h(async(o,m)=>{try{let l=await T(o,m);return l.success?{success:!0,data:l.tokens}:{success:!1,errors:l.error||"Login failed"}}catch(l){return{success:!1,errors:l instanceof Error?l.message:"Login failed"}}},[T]);return{readItems:E,readItem:d,createItem:y,updateItem:A,deleteItem:_,transaction:p,login:u,isInitialized:S,isInitializing:a,initializationError:N,isReady:I,waitForReady:c}};import{useCallback as C}from"react";import b from"@nocios/crudify-browser";var Y={INVALID_CREDENTIALS:"warning",UNAUTHORIZED:"warning",INVALID_API_KEY:"error",USER_NOT_FOUND:"warning",USER_NOT_ACTIVE:"warning",NO_PERMISSION:"warning",ITEM_NOT_FOUND:"info",NOT_FOUND:"info",IN_USE:"warning",FIELD_ERROR:"warning",BAD_REQUEST:"warning",INTERNAL_SERVER_ERROR:"error",DATABASE_CONNECTION_ERROR:"error",INVALID_CONFIGURATION:"error",UNKNOWN_OPERATION:"error",TOO_MANY_REQUESTS:"warning"},M={INVALID_CREDENTIALS:"errors.auth.INVALID_CREDENTIALS",UNAUTHORIZED:"errors.auth.UNAUTHORIZED",INVALID_API_KEY:"errors.auth.INVALID_API_KEY",USER_NOT_FOUND:"errors.auth.USER_NOT_FOUND",USER_NOT_ACTIVE:"errors.auth.USER_NOT_ACTIVE",NO_PERMISSION:"errors.auth.NO_PERMISSION",ITEM_NOT_FOUND:"errors.data.ITEM_NOT_FOUND",NOT_FOUND:"errors.data.NOT_FOUND",IN_USE:"errors.data.IN_USE",FIELD_ERROR:"errors.data.FIELD_ERROR",BAD_REQUEST:"errors.data.BAD_REQUEST",INTERNAL_SERVER_ERROR:"errors.system.INTERNAL_SERVER_ERROR",DATABASE_CONNECTION_ERROR:"errors.system.DATABASE_CONNECTION_ERROR",INVALID_CONFIGURATION:"errors.system.INVALID_CONFIGURATION",UNKNOWN_OPERATION:"errors.system.UNKNOWN_OPERATION",TOO_MANY_REQUESTS:"errors.system.TOO_MANY_REQUESTS"},le=(S={})=>{let{showNotification:a}=$(),{showSuccessNotifications:N=!1,showErrorNotifications:g=!0,customErrorMessages:T={},defaultErrorMessage:I="Ha ocurrido un error inesperado",autoHideDuration:c=6e3,appStructure:R=[],translateFn:E=e=>e}=S,d=C(e=>!(!e.success&&e.errors&&(Object.keys(e.errors).some(r=>r!=="_error"&&r!=="_graphql"&&r!=="_transaction")||e.errors._transaction?.includes("ONE_OR_MORE_OPERATIONS_FAILED")||e.errors._error?.includes("TOO_MANY_REQUESTS"))||!e.success&&e.data?.response?.status==="TOO_MANY_REQUESTS"),[]),y=C((e,i)=>{let r=E(e);return r===e?i||E("error.unknown"):r},[E]),A=C(e=>["create","update","delete"].includes(e),[]),_=C((e,i)=>N?A(e)&&i?!0:R.some(r=>r.key===e):!1,[N,R,A]),p=C((e,i,r)=>{let t=r?.key&&typeof r.key=="string"?r.key:e,n=`action.onSuccess.${t}`,s=y(n);if(s!==E("error.unknown")){if(A(t)&&i){let f=`action.${i}Singular`,O=y(f);if(O!==E("error.unknown"))return E(n,{item:O});{let k=`action.onSuccess.${t}WithoutItem`,L=y(k);return L!==E("error.unknown")?L:s}}return s}return E("success.transaction")},[y,E,A]),u=C(e=>{if(e.errorCode&&T[e.errorCode])return T[e.errorCode];if(e.errorCode&&M[e.errorCode])return y(M[e.errorCode]);if(e.errorCode){let i=[`errors.auth.${e.errorCode}`,`errors.data.${e.errorCode}`,`errors.system.${e.errorCode}`,`errors.${e.errorCode}`];for(let r of i){let t=y(r);if(t!==E("error.unknown"))return t}}if(typeof e.data=="string"&&e.data.startsWith("errors.")){let i=y(e.data);if(i!==E("error.unknown"))return i}if(e.errors&&Object.keys(e.errors).length>0){let i=Object.keys(e.errors);if(i.length===1&&i[0]==="_transaction"){let r=e.errors._transaction;if(r?.includes("ONE_OR_MORE_OPERATIONS_FAILED"))return"";if(Array.isArray(r)&&r.length>0){let t=r[0];if(typeof t=="string"&&t!=="ONE_OR_MORE_OPERATIONS_FAILED")try{let n=JSON.parse(t);if(Array.isArray(n)&&n.length>0){let s=n[0];if(s?.response?.errorCode){let f=s.response.errorCode;if(M[f])return y(M[f]);let O=[`errors.auth.${f}`,`errors.data.${f}`,`errors.system.${f}`,`errors.${f}`];for(let k of O){let L=y(k);if(L!==y("error.unknown"))return L}}if(s?.response?.data)return s.response.data}if(n?.response?.message){let s=n.response.message.toLowerCase();return s.includes("expired")?y("resetPassword.linkExpired","El enlace ha expirado"):s.includes("invalid")?y("resetPassword.invalidCode","C\xF3digo inv\xE1lido"):n.response.message}}catch{return t.toLowerCase().includes("expired")?y("resetPassword.linkExpired","El enlace ha expirado"):t.toLowerCase().includes("invalid")?y("resetPassword.invalidCode","C\xF3digo inv\xE1lido"):t}}return y("error.transaction","Error en la operaci\xF3n")}if(i.length===1&&i[0]==="_error"){let r=e.errors._error;return Array.isArray(r)?r[0]:String(r)}return i.length===1&&i[0]==="_graphql"?y("errors.system.DATABASE_CONNECTION_ERROR"):`${y("errors.data.FIELD_ERROR")}: ${i.join(", ")}`}return I||E("error.unknown")},[T,I,E,y]),o=C(e=>e.errorCode&&Y[e.errorCode]?Y[e.errorCode]:"error",[]),m=C(async(e,i,r)=>{let t=await b.createItem(e,i,r);if(!t.success&&g&&d(t)){let n=u(t),s=o(t);a(n,s,{autoHideDuration:c})}else if(t.success){let n=r?.actionConfig,s=n?.key||"create",f=n?.moduleKey||e;if(_(s,f)){let O=p(s,f,n);a(O,"success",{autoHideDuration:c})}}return t},[g,_,a,u,o,p,c,d]),l=C(async(e,i,r)=>{let t=await b.updateItem(e,i,r),n=r?.skipNotifications===!0;if(!n&&!t.success&&g&&d(t)){let s=u(t),f=o(t);a(s,f,{autoHideDuration:c})}else if(!n&&t.success){let s=r?.actionConfig,f=s?.key||"update",O=s?.moduleKey||e;if(_(f,O)){let k=p(f,O,s);a(k,"success",{autoHideDuration:c})}}return t},[g,_,a,u,o,p,c,d]),x=C(async(e,i,r)=>{let t=await b.deleteItem(e,i,r);if(!t.success&&g&&d(t)){let n=u(t),s=o(t);a(n,s,{autoHideDuration:c})}else if(t.success){let n=r?.actionConfig,s=n?.key||"delete",f=n?.moduleKey||e;if(_(s,f)){let O=p(s,f,n);a(O,"success",{autoHideDuration:c})}}return t},[g,_,a,u,o,p,c,d]),P=C(async(e,i,r)=>{let t=await b.readItem(e,i,r);if(!t.success&&g&&d(t)){let n=u(t),s=o(t);a(n,s,{autoHideDuration:c})}return t},[g,a,u,o,c,d]),w=C(async(e,i,r)=>{let t=await b.readItems(e,i,r);if(!t.success&&g&&d(t)){let n=u(t),s=o(t);a(n,s,{autoHideDuration:c})}return t},[g,a,u,o,c,d]),V=C(async(e,i)=>{let r=await b.transaction(e,i),t=i?.skipNotifications===!0;if(!t&&!r.success&&g&&d(r)){let n=u(r),s=o(r);a(n,s,{autoHideDuration:c})}else if(!t&&r.success){let n="transaction",s,f=null;if(i?.actionConfig?(f=i.actionConfig,n=f.key,s=f.moduleKey):Array.isArray(e)&&e.length>0&&e[0].operation&&(n=e[0].operation,f=R.find(O=>O.key===n),f&&(s=f.moduleKey)),_(n,s)){let O=p(n,s,f);a(O,"success",{autoHideDuration:c})}}return r},[g,_,a,u,o,p,c,d,R]),F=C((e,i)=>{if(!e.success&&g&&d(e)){let r=u(e),t=o(e);a(r,t,{autoHideDuration:c})}else e.success&&N&&i&&a(i,"success",{autoHideDuration:c});return e},[g,N,a,u,o,c,d,E]);return{createItem:m,updateItem:l,deleteItem:x,readItem:P,readItems:w,transaction:V,handleResponse:F,getErrorMessage:u,getErrorSeverity:o,shouldShowNotification:d}};export{G as a,ee as b,oe as c,le as d};
|
|
1
|
+
import{h as $,j as D}from"./chunk-ZSP7TBON.mjs";import{useState as K,useEffect as z,useCallback as j,useRef as v}from"react";import Q from"@nocios/crudify-browser";var G=(S={})=>{let{autoFetch:a=!0,retryOnError:N=!1,maxRetries:g=3}=S,{isAuthenticated:T,isInitialized:I,sessionData:c,tokens:R}=D(),[E,d]=K(null),[y,A]=K(a&&T),[_,p]=K(null),u=v(null),o=v(!0),m=v(0),l=v(0),x=j(()=>c&&(c.email||c["cognito:username"])||null,[c]),P=j(()=>{d(null),p(null),A(!1),l.current=0},[]),w=j(async()=>{let F=x();if(!F){o.current&&(p("No user email available from session data"),A(!1));return}if(!I){o.current&&(p("Session not initialized"),A(!1));return}u.current&&u.current.abort();let e=new AbortController;u.current=e;let i=++m.current;try{o.current&&(A(!0),p(null));let r=await Q.readItems("users",{filter:{email:F},pagination:{limit:1}});if(i===m.current&&o.current&&!e.signal.aborted){let t=null;if(r.success){if(Array.isArray(r.data)&&r.data.length>0)t=r.data[0];else if(r.data?.response?.data)try{let n=r.data.response.data,s=typeof n=="string"?JSON.parse(n):n;s&&s.items&&Array.isArray(s.items)&&s.items.length>0&&(t=s.items[0])}catch{}else if(r.data&&typeof r.data=="object")r.data.items&&Array.isArray(r.data.items)&&r.data.items.length>0&&(t=r.data.items[0]);else if(r.data?.data?.response?.data)try{let n=r.data.data.response.data,s=typeof n=="string"?JSON.parse(n):n;s&&s.items&&Array.isArray(s.items)&&s.items.length>0&&(t=s.items[0])}catch{}}t?(d(t),p(null),l.current=0):(p("User profile not found in database"),d(null))}}catch(r){if(i===m.current&&o.current){let t=r;if(t.name==="AbortError")return;N&&l.current<g&&(t.message?.includes("Network Error")||t.message?.includes("Failed to fetch"))?(l.current++,setTimeout(()=>{o.current&&w()},1e3*l.current)):(p("Failed to load user profile from database"),d(null))}}finally{i===m.current&&o.current&&A(!1),u.current===e&&(u.current=null)}},[I,x,N,g]);return z(()=>{a&&T&&I?w():T||P()},[a,T,I,w,P]),z(()=>(o.current=!0,()=>{o.current=!1,u.current&&(u.current.abort(),u.current=null)}),[]),{user:{session:c,data:E},loading:y,error:_,refreshProfile:w,clearProfile:P}};import{useCallback as W}from"react";var ee=()=>{let{isAuthenticated:S,isLoading:a,isInitialized:N,tokens:g,error:T,sessionData:I,login:c,logout:R,refreshTokens:E,clearError:d,getTokenInfo:y,isExpiringSoon:A,expiresIn:_,refreshExpiresIn:p}=D(),u=W(m=>{m?console.warn("useAuth.setToken() is deprecated. Use login() method instead for better security."):R()},[R]),o=g?.expiresAt?new Date(g.expiresAt):null;return{isAuthenticated:S,loading:a,error:T,token:g?.accessToken||null,user:I,tokenExpiration:o,setToken:u,logout:R,refreshToken:E,login:c,isExpiringSoon:A,expiresIn:_,refreshExpiresIn:p,getTokenInfo:y,clearError:d}};import{useCallback as h}from"react";import U from"@nocios/crudify-browser";var oe=()=>{let{isInitialized:S,isLoading:a,error:N,isAuthenticated:g,login:T}=D(),I=h(()=>S&&!a&&!N,[S,a,N]),c=h(async()=>new Promise((o,m)=>{let l=()=>{I()?o():N?m(new Error(N)):setTimeout(l,100)};l()}),[I,N]),R=h(async()=>{if(!I())throw new Error("System not ready. Check isInitialized, isLoading, and error states.")},[I]),E=h(async(o,m,l)=>(await R(),await U.readItems(o,m||{},l)),[R]),d=h(async(o,m,l)=>(await R(),await U.readItem(o,m,l)),[R]),y=h(async(o,m,l)=>(await R(),await U.createItem(o,m,l)),[R]),A=h(async(o,m,l)=>(await R(),await U.updateItem(o,m,l)),[R]),_=h(async(o,m,l)=>(await R(),await U.deleteItem(o,m,l)),[R]),p=h(async(o,m)=>(await R(),await U.transaction(o,m)),[R]),u=h(async(o,m)=>{try{let l=await T(o,m);return l.success?{success:!0,data:l.tokens}:{success:!1,errors:l.error||"Login failed"}}catch(l){return{success:!1,errors:l instanceof Error?l.message:"Login failed"}}},[T]);return{readItems:E,readItem:d,createItem:y,updateItem:A,deleteItem:_,transaction:p,login:u,isInitialized:S,isInitializing:a,initializationError:N,isReady:I,waitForReady:c}};import{useCallback as C}from"react";import b from"@nocios/crudify-browser";var Y={INVALID_CREDENTIALS:"warning",UNAUTHORIZED:"warning",INVALID_API_KEY:"error",USER_NOT_FOUND:"warning",USER_NOT_ACTIVE:"warning",NO_PERMISSION:"warning",ITEM_NOT_FOUND:"info",NOT_FOUND:"info",IN_USE:"warning",FIELD_ERROR:"warning",BAD_REQUEST:"warning",INTERNAL_SERVER_ERROR:"error",DATABASE_CONNECTION_ERROR:"error",INVALID_CONFIGURATION:"error",UNKNOWN_OPERATION:"error",TOO_MANY_REQUESTS:"warning"},M={INVALID_CREDENTIALS:"errors.auth.INVALID_CREDENTIALS",UNAUTHORIZED:"errors.auth.UNAUTHORIZED",INVALID_API_KEY:"errors.auth.INVALID_API_KEY",USER_NOT_FOUND:"errors.auth.USER_NOT_FOUND",USER_NOT_ACTIVE:"errors.auth.USER_NOT_ACTIVE",NO_PERMISSION:"errors.auth.NO_PERMISSION",ITEM_NOT_FOUND:"errors.data.ITEM_NOT_FOUND",NOT_FOUND:"errors.data.NOT_FOUND",IN_USE:"errors.data.IN_USE",FIELD_ERROR:"errors.data.FIELD_ERROR",BAD_REQUEST:"errors.data.BAD_REQUEST",INTERNAL_SERVER_ERROR:"errors.system.INTERNAL_SERVER_ERROR",DATABASE_CONNECTION_ERROR:"errors.system.DATABASE_CONNECTION_ERROR",INVALID_CONFIGURATION:"errors.system.INVALID_CONFIGURATION",UNKNOWN_OPERATION:"errors.system.UNKNOWN_OPERATION",TOO_MANY_REQUESTS:"errors.system.TOO_MANY_REQUESTS"},le=(S={})=>{let{showNotification:a}=$(),{showSuccessNotifications:N=!1,showErrorNotifications:g=!0,customErrorMessages:T={},defaultErrorMessage:I="Ha ocurrido un error inesperado",autoHideDuration:c=6e3,appStructure:R=[],translateFn:E=e=>e}=S,d=C(e=>!(!e.success&&e.errors&&(Object.keys(e.errors).some(r=>r!=="_error"&&r!=="_graphql"&&r!=="_transaction")||e.errors._transaction?.includes("ONE_OR_MORE_OPERATIONS_FAILED")||e.errors._error?.includes("TOO_MANY_REQUESTS"))||!e.success&&e.data?.response?.status==="TOO_MANY_REQUESTS"),[]),y=C((e,i)=>{let r=E(e);return r===e?i||E("error.unknown"):r},[E]),A=C(e=>["create","update","delete"].includes(e),[]),_=C((e,i)=>N?A(e)&&i?!0:R.some(r=>r.key===e):!1,[N,R,A]),p=C((e,i,r)=>{let t=r?.key&&typeof r.key=="string"?r.key:e,n=`action.onSuccess.${t}`,s=y(n);if(s!==E("error.unknown")){if(A(t)&&i){let f=`action.${i}Singular`,O=y(f);if(O!==E("error.unknown"))return E(n,{item:O});{let k=`action.onSuccess.${t}WithoutItem`,L=y(k);return L!==E("error.unknown")?L:s}}return s}return E("success.transaction")},[y,E,A]),u=C(e=>{if(e.errorCode&&T[e.errorCode])return T[e.errorCode];if(e.errorCode&&M[e.errorCode])return y(M[e.errorCode]);if(e.errorCode){let i=[`errors.auth.${e.errorCode}`,`errors.data.${e.errorCode}`,`errors.system.${e.errorCode}`,`errors.${e.errorCode}`];for(let r of i){let t=y(r);if(t!==E("error.unknown"))return t}}if(typeof e.data=="string"&&e.data.startsWith("errors.")){let i=y(e.data);if(i!==E("error.unknown"))return i}if(e.errors&&Object.keys(e.errors).length>0){let i=Object.keys(e.errors);if(i.length===1&&i[0]==="_transaction"){let r=e.errors._transaction;if(r?.includes("ONE_OR_MORE_OPERATIONS_FAILED"))return"";if(Array.isArray(r)&&r.length>0){let t=r[0];if(typeof t=="string"&&t!=="ONE_OR_MORE_OPERATIONS_FAILED")try{let n=JSON.parse(t);if(Array.isArray(n)&&n.length>0){let s=n[0];if(s?.response?.errorCode){let f=s.response.errorCode;if(M[f])return y(M[f]);let O=[`errors.auth.${f}`,`errors.data.${f}`,`errors.system.${f}`,`errors.${f}`];for(let k of O){let L=y(k);if(L!==y("error.unknown"))return L}}if(s?.response?.data)return s.response.data}if(n?.response?.message){let s=n.response.message.toLowerCase();return s.includes("expired")?y("resetPassword.linkExpired","El enlace ha expirado"):s.includes("invalid")?y("resetPassword.invalidCode","C\xF3digo inv\xE1lido"):n.response.message}}catch{return t.toLowerCase().includes("expired")?y("resetPassword.linkExpired","El enlace ha expirado"):t.toLowerCase().includes("invalid")?y("resetPassword.invalidCode","C\xF3digo inv\xE1lido"):t}}return y("error.transaction","Error en la operaci\xF3n")}if(i.length===1&&i[0]==="_error"){let r=e.errors._error;return Array.isArray(r)?r[0]:String(r)}return i.length===1&&i[0]==="_graphql"?y("errors.system.DATABASE_CONNECTION_ERROR"):`${y("errors.data.FIELD_ERROR")}: ${i.join(", ")}`}return I||E("error.unknown")},[T,I,E,y]),o=C(e=>e.errorCode&&Y[e.errorCode]?Y[e.errorCode]:"error",[]),m=C(async(e,i,r)=>{let t=await b.createItem(e,i,r);if(!t.success&&g&&d(t)){let n=u(t),s=o(t);a(n,s,{autoHideDuration:c})}else if(t.success){let n=r?.actionConfig,s=n?.key||"create",f=n?.moduleKey||e;if(_(s,f)){let O=p(s,f,n);a(O,"success",{autoHideDuration:c})}}return t},[g,_,a,u,o,p,c,d]),l=C(async(e,i,r)=>{let t=await b.updateItem(e,i,r),n=r?.skipNotifications===!0;if(!n&&!t.success&&g&&d(t)){let s=u(t),f=o(t);a(s,f,{autoHideDuration:c})}else if(!n&&t.success){let s=r?.actionConfig,f=s?.key||"update",O=s?.moduleKey||e;if(_(f,O)){let k=p(f,O,s);a(k,"success",{autoHideDuration:c})}}return t},[g,_,a,u,o,p,c,d]),x=C(async(e,i,r)=>{let t=await b.deleteItem(e,i,r);if(!t.success&&g&&d(t)){let n=u(t),s=o(t);a(n,s,{autoHideDuration:c})}else if(t.success){let n=r?.actionConfig,s=n?.key||"delete",f=n?.moduleKey||e;if(_(s,f)){let O=p(s,f,n);a(O,"success",{autoHideDuration:c})}}return t},[g,_,a,u,o,p,c,d]),P=C(async(e,i,r)=>{let t=await b.readItem(e,i,r);if(!t.success&&g&&d(t)){let n=u(t),s=o(t);a(n,s,{autoHideDuration:c})}return t},[g,a,u,o,c,d]),w=C(async(e,i,r)=>{let t=await b.readItems(e,i,r);if(!t.success&&g&&d(t)){let n=u(t),s=o(t);a(n,s,{autoHideDuration:c})}return t},[g,a,u,o,c,d]),V=C(async(e,i)=>{let r=await b.transaction(e,i),t=i?.skipNotifications===!0;if(!t&&!r.success&&g&&d(r)){let n=u(r),s=o(r);a(n,s,{autoHideDuration:c})}else if(!t&&r.success){let n="transaction",s,f=null;if(i?.actionConfig?(f=i.actionConfig,n=f.key,s=f.moduleKey):Array.isArray(e)&&e.length>0&&e[0].operation&&(n=e[0].operation,f=R.find(O=>O.key===n),f&&(s=f.moduleKey)),_(n,s)){let O=p(n,s,f);a(O,"success",{autoHideDuration:c})}}return r},[g,_,a,u,o,p,c,d,R]),F=C((e,i)=>{if(!e.success&&g&&d(e)){let r=u(e),t=o(e);a(r,t,{autoHideDuration:c})}else e.success&&N&&i&&a(i,"success",{autoHideDuration:c});return e},[g,N,a,u,o,c,d,E]);return{createItem:m,updateItem:l,deleteItem:x,readItem:P,readItems:w,transaction:V,handleResponse:F,getErrorMessage:u,getErrorSeverity:o,shouldShowNotification:d}};export{G as a,ee as b,oe as c,le as d};
|