@nocios/crudify-ui 4.1.52 → 4.1.56
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{chunk-Q2I7YV7H.js → chunk-4UBPYCIC.js} +1 -1
- package/dist/chunk-52QAU7WN.mjs +1 -0
- package/dist/chunk-HWFUFWVT.js +1 -0
- package/dist/{chunk-EYZAGBSN.js → chunk-IK6A7RQJ.js} +1 -1
- package/dist/{chunk-AGI7BSLB.mjs → chunk-TBNNHH4H.mjs} +1 -1
- package/dist/{chunk-LQ26JZXI.mjs → chunk-YHZZCCX4.mjs} +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-DudiZgBg.d.mts → index-4MK_rZUi.d.mts} +10 -0
- package/dist/{index-FQzSa_vl.d.ts → index-Dpy6dlER.d.ts} +10 -0
- package/dist/index.d.mts +247 -8
- package/dist/index.d.ts +247 -8
- package/dist/index.js +2 -2
- package/dist/index.mjs +2 -2
- package/package.json +1 -1
- package/dist/chunk-ANP3YOXX.js +0 -1
- package/dist/chunk-P2PNKHPV.mjs +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
import{b as Yo,c as G,h as Qo,j as Q,l as Zo}from"./chunk-P2PNKHPV.mjs";import{g as z}from"./chunk-BJ6PIVZR.mjs";import{a as Jo,e as Xo}from"./chunk-5JKS55SE.mjs";import{Box as wr,Typography as Pr}from"@mui/material";import{createContext as Ne,useContext as Ve,useMemo as ee}from"react";import{useState as Bo,useEffect as Ue}from"react";var oe=(o,t)=>{let[a,i]=Bo({}),[f,n]=Bo(!1),[s,g]=Bo(null);return Ue(()=>{if(console.log("\u{1F527} [I18nProvider] Hybrid translation loading:",{hasProvidedTranslations:!!t&&Object.keys(t).length>0,hasUrl:!!o,providedKeys:t?Object.keys(t).length:0}),t&&Object.keys(t).length>0){console.log("\u2705 [I18nProvider] Using provided translations (highest priority)"),i(t),n(!1),g(null);return}if(!o){console.log("\u26A0\uFE0F [I18nProvider] No translations provided, using empty object (keys will show as-is)"),i({}),n(!1),g(null);return}console.log("\u{1F310} [I18nProvider] Loading translations from URL:",o);let l=!1;return n(!0),g(null),fetch(o).then(y=>{if(!y.ok)throw new Error(`Failed to load translations: ${y.status}`);return y.json()}).then(y=>{l||(console.log("\u2705 [I18nProvider] Translations loaded successfully from URL:",{url:o,keysLoaded:Object.keys(y).length}),i(y),n(!1))}).catch(y=>{l||(console.error("\u274C [I18nProvider] Failed to load translations from URL:",o,y),g(y.message),console.log("\u{1F504} [I18nProvider] Falling back to empty translations (keys will show as-is)"),i({}),n(!1))}),()=>{l=!0}},[o,t]),{translations:a,loading:f,error:s}};import{jsx as re}from"react/jsx-runtime";var te=Ne(null),Me=(o,t)=>o&&o[t]?o[t]:t.split(".").reduce((a,i)=>a&&typeof a=="object"?a[i]:void 0,o),ne=({children:o,translations:t,translationsUrl:a,language:i="en"})=>{let{translations:f,loading:n}=oe(a,t),s=ee(()=>(l,y)=>{let c=Me(f,l);return c==null&&(console.log(`\u{1F50D} [I18nProvider] Translation not found for key: "${l}" - showing key as-is`),c=l),y&&typeof c=="string"&&Object.entries(y).forEach(([h,d])=>{c=c.replace(new RegExp(`{{${h}}}`,"g"),d)}),typeof c=="string"?c:l},[f]),g=ee(()=>({t:s,language:i}),[s,i]);return n?re("div",{children:"Loading translations..."}):re(te.Provider,{value:g,children:o})},V=()=>{let o=Ve(te);if(!o)throw new Error("useTranslation must be used within I18nProvider");return o};import{createContext as He,useContext as $e,useReducer as je,useEffect as se}from"react";import{jsx as Ge}from"react/jsx-runtime";var ae={currentScreen:"login",searchParams:{},formData:{username:"",password:"",email:"",code:"",newPassword:"",confirmPassword:""},loading:!1,errors:{global:[]},emailSent:!1,codeAlreadyExists:!1,codeValidated:!1,fromCodeVerification:!1,config:{}};function qe(o,t){switch(t.type){case"SET_SCREEN":let a={...o,currentScreen:t.payload.screen,searchParams:t.payload.params||o.searchParams,errors:{global:[]}},i=new URLSearchParams(a.searchParams),f=i.toString()?`?${i.toString()}`:window.location.pathname;try{window.history.replaceState({},"",f)}catch{}return a;case"SET_SEARCH_PARAMS":return{...o,searchParams:t.payload};case"UPDATE_FORM_DATA":return{...o,formData:{...o.formData,...t.payload},errors:{...o.errors,...Object.keys(t.payload).reduce((n,s)=>({...n,[s]:void 0}),{})}};case"SET_LOADING":return{...o,loading:t.payload};case"SET_ERRORS":return{...o,errors:{...o.errors,...t.payload}};case"CLEAR_ERRORS":return{...o,errors:{global:[]}};case"SET_EMAIL_SENT":return{...o,emailSent:t.payload};case"SET_CODE_ALREADY_EXISTS":return{...o,codeAlreadyExists:t.payload};case"SET_CODE_VALIDATED":return{...o,codeValidated:t.payload};case"SET_FROM_CODE_VERIFICATION":return{...o,fromCodeVerification:t.payload};case"RESET_FORM":return{...o,formData:ae.formData,errors:{global:[]},loading:!1,emailSent:!1,codeAlreadyExists:!1,codeValidated:!1,fromCodeVerification:!1};case"INIT_CONFIG":return{...o,config:t.payload};default:return o}}var ie=He(void 0),le=({children:o,initialScreen:t="login",config:a,autoReadFromCookies:i=!0})=>{let[f,n]=je(qe,{...ae,currentScreen:t});se(()=>{n({type:"INIT_CONFIG",payload:(()=>{let e={};if(i)try{let r=Jo("logo");if(r){let m=decodeURIComponent(r);m.startsWith("http")&&(e.logo=m)}}catch(r){console.error("Error reading configuration from cookies:",r)}return{publicApiKey:a?.publicApiKey,env:a?.env,appName:a?.appName,logo:a?.logo||e.logo,loginActions:a?.loginActions}})()})},[a,i]),se(()=>{let d=new URLSearchParams(window.location.search),e={};d.forEach((r,m)=>{e[m]=r}),Object.keys(e).length>0&&n({type:"SET_SEARCH_PARAMS",payload:e}),t==="checkCode"&&e.email&&n({type:"UPDATE_FORM_DATA",payload:{email:e.email,code:e.code||""}}),t==="resetPassword"&&e.link&&n({type:"SET_SEARCH_PARAMS",payload:e})},[t]);let h={state:f,dispatch:n,setScreen:(d,e)=>{n({type:"SET_SCREEN",payload:{screen:d,params:e}})},updateFormData:d=>{n({type:"UPDATE_FORM_DATA",payload:d})},setFieldError:(d,e)=>{n({type:"SET_ERRORS",payload:{[d]:e}})},clearErrors:()=>{n({type:"CLEAR_ERRORS"})},setLoading:d=>{n({type:"SET_LOADING",payload:d})}};return Ge(ie.Provider,{value:h,children:o})},vo=()=>{let o=$e(ie);if(o===void 0)throw new Error("useLoginState must be used within a LoginStateProvider");return o};import{useEffect as Ke,useRef as Ye}from"react";import{Typography as Fo,TextField as ce,Button as Je,Box as fo,CircularProgress as Xe,Alert as Qe,Link as de}from"@mui/material";import{Fragment as or,jsx as M,jsxs as po}from"react/jsx-runtime";var Ze=({onScreenChange:o,onExternalNavigate:t,onLoginSuccess:a,onError:i,redirectUrl:f="/"})=>{let{crudify:n}=G(),{state:s,updateFormData:g,setFieldError:l,clearErrors:y,setLoading:c}=vo(),{login:h}=Q(),d=V(),{t:e}=d,r=d.i18n,m=Ye(null),P=Xo(e,{currentLanguage:r?.language,enableDebug:!1}),C=()=>{if(s.searchParams.redirect)try{let p=decodeURIComponent(s.searchParams.redirect);if(p.startsWith("/")&&!p.startsWith("//"))return p}catch{}return f||"/"};Ke(()=>{let p=setTimeout(()=>{m.current&&m.current.focus()},100);return()=>clearTimeout(p)},[]);let u=p=>{console.log("\u{1F50D} [LoginForm] Translating parsed error:",p);let S=P.translateError({code:p.code,message:p.message,field:p.field});return console.log("\u{1F50D} [LoginForm] Translation result:",S),S},x=async()=>{if(!s.loading){if(!s.formData.username.trim()){l("username",e("login.usernameRequired"));return}if(!s.formData.password.trim()){l("password",e("login.passwordRequired"));return}y(),c(!0);try{let p=await h(s.formData.username,s.formData.password);if(c(!1),p.success){console.log("\u{1F510} LoginForm - Login successful via SessionProvider, calling onLoginSuccess");let S=C();a&&a(p.data,S)}else{let S=p.rawResponse||p;w(S)}}catch(p){c(!1);let J=z(p).map(u);l("global",J),i&&i(J.join(", "))}}},w=p=>{z(p).forEach(J=>{if(J.field)l(J.field,u(J));else{let mo=s.errors.global||[];l("global",[...mo,u(J)])}})};return po(or,{children:[po(fo,{component:"form",noValidate:!0,onSubmit:p=>{p.preventDefault(),x()},onKeyDown:p=>{p.key==="Enter"&&!s.loading&&(p.preventDefault(),x())},sx:{width:"100%",display:"flex",flexDirection:"column",gap:2},children:[po(fo,{sx:{mb:1},children:[M(Fo,{variant:"body2",component:"label",htmlFor:"email",sx:{display:"block",fontWeight:500,color:"grey.700",mb:.5},children:e("login.usernameOrEmailLabel")}),M(ce,{fullWidth:!0,id:"email",name:"email",type:"email",value:s.formData.username,disabled:s.loading,onChange:p=>g({username:p.target.value}),error:!!s.errors.username,helperText:s.errors.username,autoComplete:"email",placeholder:e("login.usernameOrEmailPlaceholder"),inputRef:m,required:!0})]}),po(fo,{sx:{mb:1},children:[M(Fo,{variant:"body2",component:"label",htmlFor:"password",sx:{display:"block",fontWeight:500,color:"grey.700",mb:.5},children:e("login.passwordLabel")}),M(ce,{fullWidth:!0,id:"password",name:"password",type:"password",value:s.formData.password,disabled:s.loading,onChange:p=>g({password:p.target.value}),error:!!s.errors.password,helperText:s.errors.password,autoComplete:"current-password",placeholder:e("login.passwordPlaceholder"),required:!0})]}),s.config.loginActions?.includes("forgotPassword")&&M(fo,{sx:{display:"flex",justifyContent:"flex-end",alignItems:"center"},children:M(de,{sx:{cursor:"pointer"},onClick:()=>{o?.("forgotPassword",s.searchParams)},variant:"body2",color:"secondary",children:e("login.forgotPasswordLink")})}),M(Je,{disabled:s.loading,type:"submit",fullWidth:!0,variant:"contained",color:"primary",sx:{mt:1,mb:2},children:s.loading?M(Xe,{size:20}):e("login.loginButton")})]}),M(fo,{children:s.errors.global&&s.errors.global.length>0&&s.errors.global.map((p,S)=>M(Qe,{variant:"filled",sx:{mt:2},severity:"error",children:M("div",{children:p})},S))}),s.config.loginActions?.includes("createUser")&&po(Fo,{variant:"body2",align:"center",sx:{color:"text.secondary",mt:3},children:[e("login.noAccountPrompt")," ",M(de,{sx:{cursor:"pointer"},onClick:()=>{let S=`/public/users/create${Object.keys(s.searchParams).length>0?`?${new URLSearchParams(s.searchParams).toString()}`:""}`;t?.(S)},fontWeight:"medium",color:"secondary",children:e("login.signUpLink")})]})]})},me=Ze;import{useState as so}from"react";import{Typography as ao,TextField as er,Button as ue,Box as Z,CircularProgress as rr,Alert as tr,Link as Do}from"@mui/material";import{Fragment as fe,jsx as B,jsxs as to}from"react/jsx-runtime";var nr=({onScreenChange:o,onError:t})=>{let{crudify:a}=G(),[i,f]=so(""),[n,s]=so(!1),[g,l]=so([]),[y,c]=so(null),[h,d]=so(!1),[e,r]=so(!1),{t:m}=V(),P=v=>{let E=[`errors.auth.${v.code}`,`errors.data.${v.code}`,`errors.system.${v.code}`,`errors.${v.code}`,`forgotPassword.${v.code.toLowerCase()}`];for(let p of E){let S=m(p);if(S!==p)return S}return v.message||m("error.unknown")},C=v=>/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(v),u=async()=>{if(!(n||!a)){if(l([]),c(null),!i){c(m("forgotPassword.emailRequired"));return}if(!C(i)){c(m("forgotPassword.invalidEmail"));return}s(!0);try{let v=[{operation:"requestPasswordReset",data:{email:i}}],E=await a.transaction(v);if(E.success)E.data&&E.data.existingCodeValid?r(!0):d(!0);else{let S=z(E).map(P);l(S)}}catch(v){let p=z(v).map(P);l(p),t&&t(p.join(", "))}finally{s(!1)}}},x=()=>{o?.("login")},w=()=>{if(h||e){o?.("checkCode",{email:i});return}if(!i){c(m("forgotPassword.emailRequired"));return}if(!C(i)){c(m("forgotPassword.invalidEmail"));return}o?.("checkCode",{email:i})};return h||e?B(fe,{children:to(Z,{sx:{width:"100%",display:"flex",flexDirection:"column",gap:2,textAlign:"center"},children:[to(Z,{sx:{mb:2},children:[B(ao,{variant:"h5",component:"h1",sx:{mb:1,fontWeight:600},children:m(e?"forgotPassword.codeAlreadyExistsMessage":"forgotPassword.emailSentMessage")}),B(ao,{variant:"body2",sx:{color:e?"success.main":"grey.600"},children:m("forgotPassword.checkEmailInstructions")})]}),B(ue,{type:"button",onClick:w,fullWidth:!0,variant:"contained",color:"primary",sx:{mt:2,mb:2},children:m("forgotPassword.enterCodeLink")}),B(Z,{sx:{display:"flex",justifyContent:"center",alignItems:"center"},children:B(Do,{sx:{cursor:"pointer"},onClick:x,variant:"body2",color:"secondary",children:m("common.back")})})]})}):to(fe,{children:[to(Z,{component:"form",noValidate:!0,sx:{width:"100%",display:"flex",flexDirection:"column",gap:2},children:[to(Z,{sx:{mb:2},children:[B(ao,{variant:"h5",component:"h1",sx:{mb:1,fontWeight:600},children:m("forgotPassword.title")}),B(ao,{variant:"body2",sx:{color:"grey.600"},children:m("forgotPassword.instructions")})]}),to(Z,{sx:{mb:1},children:[B(ao,{variant:"body2",component:"label",htmlFor:"email",sx:{display:"block",fontWeight:500,color:"grey.700",mb:.5},children:m("forgotPassword.emailLabel")}),B(er,{fullWidth:!0,id:"email",name:"email",type:"email",value:i,disabled:n,onChange:v=>f(v.target.value),error:!!y,helperText:y,autoComplete:"email",placeholder:m("forgotPassword.emailPlaceholder"),required:!0})]}),B(ue,{disabled:n,type:"button",onClick:u,fullWidth:!0,variant:"contained",color:"primary",sx:{mt:2,mb:2},children:n?B(rr,{size:20}):m("forgotPassword.sendCodeButton")}),to(Z,{sx:{display:"flex",justifyContent:"center",alignItems:"center",gap:2},children:[B(Do,{sx:{cursor:"pointer"},onClick:x,variant:"body2",color:"secondary",children:m("common.back")}),B(ao,{variant:"body2",sx:{color:"grey.400"},children:"\u2022"}),B(Do,{sx:{cursor:"pointer"},onClick:w,variant:"body2",color:"secondary",children:m("login.alreadyHaveCodeLink")})]})]}),B(Z,{children:g.length>0&&g.map((v,E)=>B(tr,{variant:"filled",sx:{mt:2},severity:"error",children:v},E))})]})},pe=nr;import{useState as U,useEffect as ge}from"react";import{Typography as To,TextField as ye,Button as sr,Box as oo,CircularProgress as xe,Alert as he,Link as ar}from"@mui/material";import{Fragment as lr,jsx as F,jsxs as go}from"react/jsx-runtime";var ir=({onScreenChange:o,onError:t,searchParams:a,onResetSuccess:i})=>{let{crudify:f}=G(),[n,s]=U(""),[g,l]=U(""),[y,c]=U(!1),[h,d]=U([]),[e,r]=U(null),[m,P]=U(null),[C,u]=U(""),[x,w]=U(""),[v,E]=U(!1),[p,S]=U(!0),[J,mo]=U(!1),[wo,Io]=U(null),[_e,Ko]=U(!1),{t:I}=V(),Po=T=>{let k=[`errors.auth.${T.code}`,`errors.data.${T.code}`,`errors.system.${T.code}`,`errors.${T.code}`,`resetPassword.${T.code.toLowerCase()}`];for(let O of k){let W=I(O);if(W!==O)return W}return T.message||I("error.unknown")},Co=T=>a?a instanceof URLSearchParams?a.get(T):a[T]||null:null;ge(()=>{if(a){if(a){let T=Co("fromCodeVerification"),k=Co("email"),O=Co("code");if(T==="true"&&k&&O){u(k),w(O),E(!0),mo(!0),S(!1);return}let W=Co("link");if(W)try{let H=decodeURIComponent(W),[$,uo]=H.split("/");if($&&uo&&$.length===6){w($),u(uo),E(!1),Io({email:uo,code:$});return}}catch{}if(k&&O){u(k),w(O),E(!1),Io({email:k,code:O});return}}d([I("resetPassword.invalidCode")]),S(!1),setTimeout(()=>o?.("forgotPassword"),3e3)}},[a,f,I,o]),ge(()=>{f&&wo&&!_e&&(Ko(!0),(async(k,O)=>{try{let W=[{operation:"validatePasswordResetCode",data:{email:k,codePassword:O}}],H=await f.transaction(W);if(H.data&&Array.isArray(H.data)){let $=H.data[0];if($&&$.response&&$.response.status==="OK"){mo(!0);return}}if(H.success)mo(!0);else{let uo=z(H).map(Po);d(uo),setTimeout(()=>o?.("forgotPassword"),3e3)}}catch(W){let $=z(W).map(Po);d($),setTimeout(()=>o?.("forgotPassword"),3e3)}finally{S(!1),Io(null),Ko(!1)}})(wo.email,wo.code))},[f,wo,I,o]);let Oe=T=>T.length<8?I("resetPassword.passwordTooShort"):null,ze=async()=>{if(y||!f)return;d([]),r(null),P(null);let T=!1;if(!n)r(I("resetPassword.newPasswordRequired")),T=!0;else{let k=Oe(n);k&&(r(k),T=!0)}if(g?n!==g&&(P(I("resetPassword.passwordsDoNotMatch")),T=!0):(P(I("resetPassword.confirmPasswordRequired")),T=!0),!T){c(!0);try{let k=[{operation:"validateAndResetPassword",data:{email:C,codePassword:x,newPassword:n}}],O=await f.transaction(k);if(O.success)d([]),setTimeout(()=>{i?.()},1e3);else{let H=z(O).map(Po);d(H)}}catch(k){let W=z(k).map(Po);d(W),t&&t(W.join(", "))}c(!1)}},We=()=>{v?o?.("checkCode",{email:C}):o?.("forgotPassword")};return p?F(oo,{sx:{display:"flex",justifyContent:"center",alignItems:"center",minHeight:"300px"},children:F(xe,{})}):J?go(lr,{children:[go(oo,{component:"form",noValidate:!0,sx:{width:"100%",display:"flex",flexDirection:"column",gap:2},children:[go(oo,{sx:{mb:2},children:[F(To,{variant:"h5",component:"h1",sx:{mb:1,fontWeight:600},children:I("resetPassword.title")}),F(To,{variant:"body2",sx:{color:"grey.600"},children:I("resetPassword.instructions")})]}),go(oo,{sx:{mb:1},children:[F(To,{variant:"body2",component:"label",htmlFor:"newPassword",sx:{display:"block",fontWeight:500,color:"grey.700",mb:.5},children:I("resetPassword.newPasswordLabel")}),F(ye,{fullWidth:!0,id:"newPassword",name:"newPassword",type:"password",value:n,disabled:y,onChange:T=>s(T.target.value),error:!!e,helperText:e,autoComplete:"new-password",placeholder:I("resetPassword.newPasswordPlaceholder"),required:!0})]}),go(oo,{sx:{mb:1},children:[F(To,{variant:"body2",component:"label",htmlFor:"confirmPassword",sx:{display:"block",fontWeight:500,color:"grey.700",mb:.5},children:I("resetPassword.confirmPasswordLabel")}),F(ye,{fullWidth:!0,id:"confirmPassword",name:"confirmPassword",type:"password",value:g,disabled:y,onChange:T=>l(T.target.value),error:!!m,helperText:m,autoComplete:"new-password",placeholder:I("resetPassword.confirmPasswordPlaceholder"),required:!0})]}),F(sr,{disabled:y,type:"button",onClick:ze,fullWidth:!0,variant:"contained",color:"primary",sx:{mt:2,mb:2},children:y?F(xe,{size:20}):I("resetPassword.resetPasswordButton")}),F(oo,{sx:{display:"flex",justifyContent:"center",alignItems:"center"},children:F(ar,{sx:{cursor:"pointer"},onClick:We,variant:"body2",color:"secondary",children:I("common.back")})})]}),F(oo,{children:h.length>0&&h.map((T,k)=>F(he,{variant:"filled",sx:{mt:2},severity:"error",children:T},k))})]}):F(oo,{children:h.length>0&&h.map((T,k)=>F(he,{variant:"filled",sx:{mt:2},severity:"error",children:T},k))})},be=ir;import{useState as yo,useEffect as cr}from"react";import{Typography as _o,TextField as dr,Button as mr,Box as xo,CircularProgress as ur,Alert as fr,Link as pr}from"@mui/material";import{Fragment as yr,jsx as K,jsxs as Eo}from"react/jsx-runtime";var gr=({onScreenChange:o,onError:t,searchParams:a})=>{let{crudify:i}=G(),[f,n]=yo(""),[s,g]=yo(!1),[l,y]=yo([]),[c,h]=yo(null),[d,e]=yo(""),{t:r}=V(),m=w=>a?a instanceof URLSearchParams?a.get(w):a[w]||null:null,P=w=>{let v=[`errors.auth.${w.code}`,`errors.data.${w.code}`,`errors.system.${w.code}`,`errors.${w.code}`,`checkCode.${w.code.toLowerCase()}`];for(let E of v){let p=r(E);if(p!==E)return p}return w.message||r("error.unknown")};cr(()=>{let w=m("email");w?e(w):o?.("forgotPassword")},[a,o]);let C=async()=>{if(!(s||!i)){if(y([]),h(null),!f){h(r("checkCode.codeRequired"));return}if(f.length!==6){h(r("checkCode.codeRequired"));return}g(!0);try{let w=[{operation:"validatePasswordResetCode",data:{email:d,codePassword:f}}],v=await i.transaction(w);if(v.success)o?.("resetPassword",{email:d,code:f,fromCodeVerification:"true"});else{let p=z(v).map(P);y(p),g(!1)}}catch(w){let E=z(w).map(P);y(E),g(!1),t&&t(E.join(", "))}}},u=()=>{o?.("forgotPassword")},x=w=>{let v=w.target.value.replace(/\D/g,"").slice(0,6);n(v)};return Eo(yr,{children:[Eo(xo,{component:"form",noValidate:!0,sx:{width:"100%",display:"flex",flexDirection:"column",gap:2},children:[Eo(xo,{sx:{mb:2},children:[K(_o,{variant:"h5",component:"h1",sx:{mb:1,fontWeight:600},children:r("checkCode.title")}),K(_o,{variant:"body2",sx:{color:"grey.600"},children:r("checkCode.instructions")})]}),Eo(xo,{sx:{mb:1},children:[K(_o,{variant:"body2",component:"label",htmlFor:"code",sx:{display:"block",fontWeight:500,color:"grey.700",mb:.5},children:r("checkCode.codeLabel")}),K(dr,{fullWidth:!0,id:"code",name:"code",type:"text",value:f,disabled:s,onChange:x,error:!!c,helperText:c,placeholder:r("checkCode.codePlaceholder"),inputProps:{maxLength:6,style:{textAlign:"center",fontSize:"1.5rem",letterSpacing:"0.4rem"}},required:!0})]}),K(mr,{disabled:s||f.length!==6,type:"button",onClick:C,fullWidth:!0,variant:"contained",color:"primary",sx:{mt:2,mb:2},children:s?K(ur,{size:20}):r("checkCode.verifyButton")}),K(xo,{sx:{display:"flex",justifyContent:"center",alignItems:"center"},children:K(pr,{sx:{cursor:"pointer"},onClick:u,variant:"body2",color:"secondary",children:r("common.back")})})]}),K(xo,{children:l.length>0&&l.map((w,v)=>K(fr,{sx:{mt:2},severity:"error",children:w},v))})]})},we=gr;import{Box as xr,CircularProgress as hr,Alert as Pe,Typography as Oo}from"@mui/material";import{Fragment as br,jsx as io,jsxs as Ce}from"react/jsx-runtime";var ve=({children:o,fallback:t})=>{let{isLoading:a,error:i,isInitialized:f}=G(),{t:n}=V();return a?t||Ce(xr,{sx:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",minHeight:"200px",gap:2},children:[io(hr,{}),io(Oo,{variant:"body2",color:"text.secondary",children:n("login.initializing")!=="login.initializing"?n("login.initializing"):"Initializing..."})]}):i?io(Pe,{severity:"error",sx:{mt:2},children:Ce(Oo,{variant:"body2",children:[n("login.initializationError")!=="login.initializationError"?n("login.initializationError"):"Initialization error",":"," ",i]})}):f?io(br,{children:o}):io(Pe,{severity:"warning",sx:{mt:2},children:io(Oo,{variant:"body2",children:n("login.notInitialized")!=="login.notInitialized"?n("login.notInitialized"):"System not initialized"})})};import{jsx as j,jsxs as Tr}from"react/jsx-runtime";var Cr=({onScreenChange:o,onExternalNavigate:t,onLoginSuccess:a,onError:i,redirectUrl:f="/"})=>{let{t:n}=V(),{state:s,setScreen:g}=vo(),{config:l}=Q(),{showNotification:y}=Qo(),c=(d,e)=>{let r=e;d==="login"?r={}:d==="forgotPassword"&&!e&&(r={}),g(d,r),o?.(d,r)},h=()=>{let d={onScreenChange:c,onExternalNavigate:t,onError:i,redirectUrl:f};switch(s.currentScreen){case"forgotPassword":return j(pe,{...d});case"checkCode":return j(we,{...d,searchParams:s.searchParams});case"resetPassword":return j(be,{...d,searchParams:s.searchParams,onResetSuccess:()=>{let e=n("resetPassword.successMessage");y(e,"success"),c("login")}});default:return j(me,{...d,onLoginSuccess:a})}};return Tr(ve,{children:[j(wr,{sx:{display:"flex",justifyContent:"center",mb:3},children:j("img",{src:l.logo||"https://logos.crudia.com/nocios-default.png",alt:n("login.logoAlt"),style:{width:"100%",maxWidth:"150px",height:"auto"},onError:d=>{let e=d.target;e.src="https://logos.crudia.com/nocios-default.png"}})}),!l.logo&&l.appName&&j(Pr,{variant:"h6",component:"h1",sx:{textAlign:"center",mb:2},children:l.appName}),h()]})},vr=({translations:o,translationsUrl:t,language:a="en",initialScreen:i="login",autoReadFromCookies:f=!0,...n})=>{let{config:s}=Q();return j(ne,{translations:o,translationsUrl:t,language:a,children:j(Yo,{config:s,children:j(le,{config:s,initialScreen:i,autoReadFromCookies:f,children:j(Cr,{...n})})})})},Ln=vr;import{Box as N,Card as Te,CardContent as Ee,Typography as q,Chip as So,Avatar as Er,Divider as Sr,CircularProgress as kr,Alert as Se,List as Lr,ListItem as zo,ListItemText as Wo,ListItemIcon as Rr,Collapse as Ar,IconButton as Uo}from"@mui/material";import{Person as Ir,Email as Br,Badge as Fr,Security as Dr,Schedule as _r,AccountCircle as Or,ExpandMore as zr,ExpandLess as Wr,Info as Ur}from"@mui/icons-material";import{useState as Nr}from"react";import{Fragment as Hr,jsx as b,jsxs as L}from"react/jsx-runtime";var Vr=({showExtendedData:o=!0,showProfileCard:t=!0,autoRefresh:a=!0})=>{let{userProfile:i,loading:f,error:n,extendedData:s,refreshProfile:g}=Zo({autoFetch:a,retryOnError:!0,maxRetries:3}),[l,y]=Nr(!1);if(f)return L(N,{display:"flex",justifyContent:"center",alignItems:"center",p:3,children:[b(kr,{}),b(q,{variant:"body2",sx:{ml:2},children:"Cargando perfil de usuario..."})]});if(n)return L(Se,{severity:"error",action:b(Uo,{color:"inherit",size:"small",onClick:g,children:b(q,{variant:"caption",children:"Reintentar"})}),children:["Error al cargar el perfil: ",n]});if(!i)return b(Se,{severity:"warning",children:"No se encontr\xF3 informaci\xF3n del usuario"});let c=s?.displayData||{},h=s?.totalFields||0,d=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}},e=(u,x)=>x==null?"No disponible":typeof x=="boolean"?x?"S\xED":"No":Array.isArray(x)?x.length>0?x.join(", "):"Ninguno":typeof x=="object"?JSON.stringify(x,null,2):String(x),r=[{key:"id",label:"ID",icon:b(Fr,{})},{key:"email",label:"Email",icon:b(Br,{})},{key:"username",label:"Usuario",icon:b(Ir,{})},{key:"fullName",label:"Nombre completo",icon:b(Or,{})},{key:"role",label:"Rol",icon:b(Dr,{})}],m=[{key:"firstName",label:"Nombre"},{key:"lastName",label:"Apellido"},{key:"isActive",label:"Activo"},{key:"lastLogin",label:"\xDAltimo login"},{key:"createdAt",label:"Creado"},{key:"updatedAt",label:"Actualizado"}],P=[...r.map(u=>u.key),...m.map(u=>u.key),"permissions"],C=Object.keys(c).filter(u=>!P.includes(u)).map(u=>({key:u,label:u}));return L(N,{children:[t&&b(Te,{sx:{mb:2},children:L(Ee,{children:[L(N,{display:"flex",alignItems:"center",mb:2,children:[b(Er,{src:c.avatar,sx:{width:56,height:56,mr:2},children:c.fullName?.[0]||c.username?.[0]||c.email?.[0]}),L(N,{children:[b(q,{variant:"h6",children:c.fullName||c.username||c.email}),b(q,{variant:"body2",color:"text.secondary",children:c.role||"Usuario"}),c.isActive!==void 0&&b(So,{label:c.isActive?"Activo":"Inactivo",color:c.isActive?"success":"error",size:"small",sx:{mt:.5}})]})]}),b(N,{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(250px, 1fr))",gap:2,children:r.map(({key:u,label:x,icon:w})=>c[u]?L(N,{display:"flex",alignItems:"center",children:[b(N,{sx:{mr:1,color:"text.secondary"},children:w}),L(N,{children:[b(q,{variant:"caption",color:"text.secondary",children:x}),b(q,{variant:"body2",children:e(u,c[u])})]})]},u):null)}),c.permissions&&Array.isArray(c.permissions)&&c.permissions.length>0&&L(N,{mt:2,children:[b(q,{variant:"caption",color:"text.secondary",display:"block",children:"Permisos"}),L(N,{display:"flex",flexWrap:"wrap",gap:.5,mt:.5,children:[c.permissions.slice(0,5).map((u,x)=>b(So,{label:u,size:"small",variant:"outlined"},x)),c.permissions.length>5&&b(So,{label:`+${c.permissions.length-5} m\xE1s`,size:"small"})]})]})]})}),o&&b(Te,{children:L(Ee,{children:[L(N,{display:"flex",justifyContent:"space-between",alignItems:"center",mb:2,children:[L(q,{variant:"h6",display:"flex",alignItems:"center",children:[b(Ur,{sx:{mr:1}}),"Informaci\xF3n Detallada"]}),b(So,{label:`${h} campos totales`,size:"small"})]}),L(Lr,{dense:!0,children:[m.map(({key:u,label:x})=>c[u]!==void 0&&L(zo,{divider:!0,children:[b(Rr,{children:b(_r,{fontSize:"small"})}),b(Wo,{primary:x,secondary:u.includes("At")||u.includes("Login")?d(c[u]):e(u,c[u])})]},u)),C.length>0&&L(Hr,{children:[b(Sr,{sx:{my:1}}),b(zo,{children:b(Wo,{primary:L(N,{display:"flex",justifyContent:"space-between",alignItems:"center",children:[L(q,{variant:"subtitle2",children:["Campos Personalizados (",C.length,")"]}),b(Uo,{size:"small",onClick:()=>y(!l),children:l?b(Wr,{}):b(zr,{})})]})})}),b(Ar,{in:l,children:C.map(({key:u,label:x})=>b(zo,{sx:{pl:4},children:b(Wo,{primary:x,secondary:e(u,c[u])})},u))})]})]}),L(N,{mt:2,display:"flex",justifyContent:"space-between",alignItems:"center",children:[L(q,{variant:"caption",color:"text.secondary",children:["\xDAltima actualizaci\xF3n: ",d(c.updatedAt)]}),b(Uo,{size:"small",onClick:g,disabled:f,children:b(q,{variant:"caption",children:"Actualizar"})})]})]})})]})},Mr=Vr;var ke=["create","read","update","delete"],Le=["create","read","update","delete"];import{useRef as ft}from"react";import{useTranslation as pt}from"react-i18next";import{Box as Lo,Typography as Be,Button as gt,Stack as yt,Alert as Fe,Divider as xt}from"@mui/material";import{Add as ht}from"@mui/icons-material";import{forwardRef as ot}from"react";import{useTranslation as et}from"react-i18next";import{Box as no,FormControl as rt,InputLabel as tt,Select as nt,MenuItem as st,IconButton as at,Typography as lo,FormHelperText as it,Stack as ko,Paper as Ie,Divider as lt,Button as $o}from"@mui/material";import{Delete as ct,SelectAll as dt,ClearAll as mt}from"@mui/icons-material";import{useState as $r,useEffect as jr,useRef as qr}from"react";import{useTranslation as Gr}from"react-i18next";import{Box as No,Typography as ho,Button as Re,Stack as Vo,FormHelperText as Ae,ToggleButton as Mo,ToggleButtonGroup as Kr}from"@mui/material";import{CheckCircle as Yr,Cancel as Jr,SelectAll as Xr,ClearAll as Qr}from"@mui/icons-material";import{jsx as D,jsxs as eo}from"react/jsx-runtime";var Zr=({value:o,onChange:t,availableFields:a,error:i,disabled:f=!1})=>{let{t:n}=Gr(),[s,g]=$r("custom"),l=qr(!1);jr(()=>{let e=o||{allow:[],owner_allow:[],deny:[]},r=new Set(a),m=(e.allow||[]).filter(x=>r.has(x)),P=(e.owner_allow||[]).filter(x=>r.has(x)),C=(e.deny||[]).filter(x=>r.has(x));a.forEach(x=>{!m.includes(x)&&!P.includes(x)&&!C.includes(x)&&C.push(x)});let u={allow:m,owner_allow:P,deny:C};JSON.stringify(u)!==JSON.stringify(e)&&t(u),m.length===a.length?g("all"):C.length===a.length?g("none"):g("custom")},[a,o]);let y=()=>{l.current=!0,t({allow:[...a],owner_allow:[],deny:[]}),g("all"),setTimeout(()=>{l.current=!1},0)},c=()=>{l.current=!0,t({allow:[],owner_allow:[],deny:[...a]}),g("none"),setTimeout(()=>{l.current=!1},0)},h=e=>o?.allow?.includes(e)?"allow":o?.owner_allow?.includes(e)?"owner_allow":"deny",d=(e,r)=>{l.current=!0;let m=new Set(o?.allow||[]),P=new Set(o?.owner_allow||[]),C=new Set(o?.deny||[]);m.delete(e),P.delete(e),C.delete(e),r==="allow"&&m.add(e),r==="owner_allow"&&P.add(e),r==="deny"&&C.add(e),t({allow:Array.from(m),owner_allow:Array.from(P),deny:Array.from(C)}),g("custom"),setTimeout(()=>{l.current=!1},0)};return a.length===0?eo(No,{children:[D(ho,{variant:"body2",color:"text.secondary",sx:{mb:1},children:n("modules.form.publicPolicies.fields.conditions.label")}),D(ho,{variant:"body2",color:"text.secondary",sx:{fontStyle:"italic"},children:n("modules.form.publicPolicies.fields.conditions.noFieldsAvailable")}),i&&D(Ae,{error:!0,sx:{mt:1},children:i})]}):eo(No,{children:[D(ho,{variant:"body2",color:"text.secondary",sx:{mb:2},children:n("modules.form.publicPolicies.fields.conditions.label")}),eo(Vo,{direction:"row",spacing:1,sx:{mb:3},children:[D(Re,{variant:s==="all"?"contained":"outlined",startIcon:D(Xr,{}),onClick:y,disabled:f,size:"small",sx:{minWidth:120,...s==="all"&&{backgroundColor:"#16a34a","&:hover":{backgroundColor:"#15803d"}}},children:n("modules.form.publicPolicies.fields.conditions.allFields")}),D(Re,{variant:s==="none"?"contained":"outlined",startIcon:D(Qr,{}),onClick:c,disabled:f,size:"small",sx:{minWidth:120,...s==="none"&&{backgroundColor:"#cf222e","&:hover":{backgroundColor:"#bc1f2c"}}},children:n("modules.form.publicPolicies.fields.conditions.noFields")})]}),eo(No,{sx:{p:2,border:"1px solid #d1d9e0",borderRadius:1,backgroundColor:"#f6f8fa"},children:[D(ho,{variant:"body2",color:"text.secondary",sx:{mb:2},children:n("modules.form.publicPolicies.fields.conditions.help")}),D(Vo,{spacing:1,children:a.map(e=>{let r=h(e);return eo(Vo,{direction:"row",spacing:1,alignItems:"center",children:[D(ho,{variant:"body2",sx:{minWidth:100,fontFamily:"monospace"},children:e}),eo(Kr,{value:r,exclusive:!0,size:"small",children:[eo(Mo,{value:"allow",onClick:()=>d(e,"allow"),disabled:f,sx:{px:2,color:r==="allow"?"#ffffff":"#6b7280",backgroundColor:r==="allow"?"#16a34a":"#f3f4f6",borderColor:r==="allow"?"#16a34a":"#d1d5db","&:hover":{backgroundColor:r==="allow"?"#15803d":"#e5e7eb",borderColor:r==="allow"?"#15803d":"#9ca3af"},"&.Mui-selected":{backgroundColor:"#16a34a",color:"#ffffff","&:hover":{backgroundColor:"#15803d"}}},children:[D(Yr,{sx:{fontSize:16,mr:.5}}),n("modules.form.publicPolicies.fields.conditions.states.allow")]}),D(Mo,{value:"owner_allow",onClick:()=>d(e,"owner_allow"),disabled:f,sx:{px:2,color:r==="owner_allow"?"#ffffff":"#6b7280",backgroundColor:r==="owner_allow"?"#0ea5e9":"#f3f4f6",borderColor:r==="owner_allow"?"#0ea5e9":"#d1d5db","&:hover":{backgroundColor:r==="owner_allow"?"#0284c7":"#e5e7eb",borderColor:r==="owner_allow"?"#0284c7":"#9ca3af"},"&.Mui-selected":{backgroundColor:"#0ea5e9",color:"#ffffff","&:hover":{backgroundColor:"#0284c7"}}},children:n("modules.form.publicPolicies.fields.conditions.states.ownerAllow")}),eo(Mo,{value:"deny",onClick:()=>d(e,"deny"),disabled:f,sx:{px:2,color:r==="deny"?"#ffffff":"#6b7280",backgroundColor:r==="deny"?"#dc2626":"#f3f4f6",borderColor:r==="deny"?"#dc2626":"#d1d5db","&:hover":{backgroundColor:r==="deny"?"#b91c1c":"#e5e7eb",borderColor:r==="deny"?"#b91c1c":"#9ca3af"},"&.Mui-selected":{backgroundColor:"#dc2626",color:"#ffffff","&:hover":{backgroundColor:"#b91c1c"}}},children:[D(Jr,{sx:{fontSize:16,mr:.5}}),n("modules.form.publicPolicies.fields.conditions.states.deny")]})]})]},e)})})]}),i&&D(Ae,{error:!0,sx:{mt:1},children:i})]})},Ho=Zr;import{jsx as A,jsxs as _}from"react/jsx-runtime";var ut=ot(({policy:o,onChange:t,onRemove:a,availableFields:i,isSubmitting:f=!1,usedActions:n,error:s},g)=>{let{t:l}=et(),y=new Set(Array.from(n||[]));y.delete(o.action);let c=ke.map(h=>({value:h,label:l(`modules.form.publicPolicies.fields.action.options.${h}`)}));return _(Ie,{ref:g,sx:{p:3,border:"1px solid #d1d9e0",borderRadius:2,position:"relative",backgroundColor:"#ffffff"},children:[_(no,{sx:{display:"flex",justifyContent:"space-between",alignItems:"flex-start",mb:3},children:[A(lo,{variant:"subtitle1",sx:{fontWeight:600,color:"#111418",fontSize:"1rem"},children:l("modules.form.publicPolicies.policyTitle")}),A(at,{onClick:a,size:"small",disabled:f,"aria-label":l("modules.form.publicPolicies.removePolicy"),sx:{color:"#656d76","&:hover":{color:"#cf222e",backgroundColor:"rgba(207, 34, 46, 0.1)"}},children:A(ct,{})})]}),_(ko,{spacing:3,children:[A(ko,{direction:{xs:"column",md:"row"},spacing:2,children:A(no,{sx:{flex:1,minWidth:200},children:_(rt,{fullWidth:!0,children:[A(tt,{children:l("modules.form.publicPolicies.fields.action.label")}),A(nt,{value:o.action,label:l("modules.form.publicPolicies.fields.action.label"),disabled:f,onChange:h=>{let d=h.target.value,e={...o,action:d};d==="delete"?(e.permission="deny",delete e.fields):(e.fields={allow:[],owner_allow:[],deny:i},delete e.permission),t(e)},sx:{backgroundColor:"#ffffff","&:hover .MuiOutlinedInput-notchedOutline":{borderColor:"#8c959f"},"&.Mui-focused .MuiOutlinedInput-notchedOutline":{borderColor:"#0969da",borderWidth:2}},children:c.map(h=>{let d=y.has(h.value);return A(st,{value:h.value,disabled:d,children:h.label},h.value)})}),s&&A(it,{error:!0,children:s})]})})}),o.action==="delete"?_(no,{children:[A(lo,{variant:"body2",color:"text.secondary",sx:{mb:2},children:l("modules.form.publicPolicies.fields.conditions.label")}),_(ko,{direction:"row",spacing:1,sx:{mb:3},children:[A($o,{variant:o.permission==="*"?"contained":"outlined",startIcon:A(dt,{}),onClick:()=>t({...o,permission:"*"}),disabled:f,size:"small",sx:{minWidth:140,whiteSpace:"nowrap",...o.permission==="*"&&{backgroundColor:"#16a34a","&:hover":{backgroundColor:"#15803d"}}},children:l("modules.form.publicPolicies.fields.conditions.allFields")}),A($o,{variant:o.permission==="owner"?"contained":"outlined",onClick:()=>t({...o,permission:"owner"}),disabled:f,size:"small",sx:{minWidth:140,whiteSpace:"nowrap",...o.permission==="owner"&&{backgroundColor:"#0ea5e9","&:hover":{backgroundColor:"#0284c7"}}},children:l("modules.form.publicPolicies.fields.conditions.states.ownerAllow")}),A($o,{variant:o.permission==="deny"?"contained":"outlined",startIcon:A(mt,{}),onClick:()=>t({...o,permission:"deny"}),disabled:f,size:"small",sx:{minWidth:140,whiteSpace:"nowrap",...o.permission==="deny"&&{backgroundColor:"#cf222e","&:hover":{backgroundColor:"#bc1f2c"}}},children:l("modules.form.publicPolicies.fields.conditions.noFields")})]})]}):A(Ho,{value:o.fields||{allow:[],owner_allow:[],deny:[]},onChange:h=>t({...o,fields:h}),availableFields:i,disabled:f}),A(Ie,{variant:"outlined",sx:{p:2,backgroundColor:"#f9fafb"},children:o.action==="delete"?_(lo,{variant:"body2",sx:{fontFamily:"monospace",color:"text.secondary"},children:[_(no,{component:"span",sx:{color:o.permission==="*"?"#16a34a":o.permission==="owner"?"#0ea5e9":"#dc2626"},children:[l("modules.form.publicPolicies.fields.conditions.states.allow"),":"]})," ",o.permission||"-"]}):_(ko,{spacing:.5,divider:A(lt,{sx:{borderColor:"#e5e7eb"}}),children:[_(lo,{variant:"body2",sx:{fontFamily:"monospace",color:"text.secondary"},children:[_(no,{component:"span",sx:{color:"#16a34a"},children:[l("modules.form.publicPolicies.fields.conditions.states.allow"),":"]})," ",(o?.fields?.allow||[]).join(", ")||"-"]}),_(lo,{variant:"body2",sx:{fontFamily:"monospace",color:"text.secondary"},children:[_(no,{component:"span",sx:{color:"#0ea5e9"},children:[l("modules.form.publicPolicies.fields.conditions.states.ownerAllow"),":"]})," ",(o?.fields?.owner_allow||[]).join(", ")||"-"]}),_(lo,{variant:"body2",sx:{fontFamily:"monospace",color:"text.secondary"},children:[_(no,{component:"span",sx:{color:"#dc2626"},children:[l("modules.form.publicPolicies.fields.conditions.states.deny"),":"]})," ",(o?.fields?.deny||[]).join(", ")||"-"]})]})})]})]})}),jo=ut;import{Fragment as Pt,jsx as Y,jsxs as Ro}from"react/jsx-runtime";var bt=()=>{let o=globalThis?.crypto;return o&&typeof o.randomUUID=="function"?o.randomUUID():`${Date.now()}-${Math.random().toString(16).slice(2)}`},wt=({policies:o,onChange:t,availableFields:a,errors:i,isSubmitting:f=!1})=>{let{t:n}=pt(),s=ft({}),g=new Set((o||[]).map(r=>r.action).filter(Boolean)),l=Le.filter(r=>!g.has(r)),y=l.length>0,c=()=>{let r=l[0]||"create",m={id:bt(),action:r};r==="delete"?m.permission="deny":m.fields={allow:[],owner_allow:[],deny:a};let P=[...o||[],m];t(P),setTimeout(()=>{let C=P.length-1,u=s.current[C];u&&u.scrollIntoView({behavior:"smooth",block:"center"})},100)},h=r=>{let m=[...o];m.splice(r,1),t(m)},d=(()=>{if(!i)return null;if(typeof i=="string")return i;let r=i._error;return typeof r=="string"?r:null})(),e=new Set((o||[]).map(r=>r.action));return Ro(Pt,{children:[Y(xt,{sx:{borderColor:"#e0e4e7"}}),Ro(Lo,{children:[Y(Lo,{display:"flex",justifyContent:"space-between",alignItems:"center",mb:3,children:Ro(Lo,{children:[Y(Be,{variant:"h6",sx:{fontWeight:600,color:"#111418",mb:1},children:n("modules.form.publicPolicies.title")}),Y(Be,{variant:"body2",color:"text.secondary",sx:{fontSize:"0.875rem"},children:n("modules.form.publicPolicies.description")})]})}),d&&Y(Fe,{severity:"error",sx:{mb:3},children:d}),Ro(yt,{spacing:3,children:[(o||[]).length===0?Y(Fe,{severity:"info",children:n("modules.form.publicPolicies.noPolicies")}):o.map((r,m)=>Y(jo,{ref:P=>{s.current[m]=P},policy:r,onChange:P=>{let C=[...o];C[m]=P,t(C)},onRemove:()=>h(m),availableFields:a,isSubmitting:f,usedActions:e,error:typeof i=="object"&&i&&r.id in i?i[r.id]:void 0},r.id)),y&&Y(Lo,{children:Y(gt,{type:"button",variant:"outlined",startIcon:Y(ht,{}),onClick:c,disabled:f,sx:{borderColor:"#d0d7de",color:"#656d76","&:hover":{borderColor:"#8c959f",backgroundColor:"transparent"}},children:n("modules.form.publicPolicies.addPolicy")})})]})]})]})},us=wt;import{useState as qo}from"react";import{Button as Ao,TextField as De,Box as co,Alert as bo,Typography as ro,CircularProgress as Go}from"@mui/material";import{jsx as R,jsxs as X}from"react/jsx-runtime";function bs(){let[o,t]=qo(""),[a,i]=qo(""),[f,n]=qo(!1),{isAuthenticated:s,isLoading:g,error:l,login:y,logout:c,refreshTokens:h,clearError:d,isExpiringSoon:e,expiresIn:r}=Q(),m=async u=>{if(u.preventDefault(),!o||!a)return;(await y(o,a)).success&&(t(""),i(""),n(!1))},P=async()=>{await c()},C=async()=>{await h()};return s?X(co,{sx:{maxWidth:600,mx:"auto",p:3},children:[R(ro,{variant:"h4",gutterBottom:!0,children:"Welcome! \u{1F389}"}),R(bo,{severity:"success",sx:{mb:3},children:"You are successfully logged in with Refresh Token Pattern enabled"}),X(co,{sx:{mb:3,p:2,bgcolor:"background.paper",border:1,borderColor:"divider",borderRadius:1},children:[R(ro,{variant:"h6",gutterBottom:!0,children:"Token Status"}),X(ro,{variant:"body2",color:"text.secondary",children:["Access Token expires in: ",Math.round(r/1e3/60)," minutes"]}),e&&R(bo,{severity:"warning",sx:{mt:1},children:"Token expires soon - automatic refresh will happen"})]}),X(co,{sx:{display:"flex",gap:2,flexWrap:"wrap"},children:[R(Ao,{variant:"contained",onClick:C,disabled:g,startIcon:g?R(Go,{size:16}):null,children:"Refresh Tokens"}),R(Ao,{variant:"outlined",color:"error",onClick:P,disabled:g,children:"Logout"})]}),l&&R(bo,{severity:"error",sx:{mt:2},onClose:d,children:l})]}):X(co,{sx:{maxWidth:400,mx:"auto",p:3},children:[R(ro,{variant:"h4",gutterBottom:!0,align:"center",children:"Login with Refresh Tokens"}),R(bo,{severity:"info",sx:{mb:3},children:"This demo shows the new Refresh Token Pattern with automatic session management"}),f?X("form",{onSubmit:m,children:[R(De,{fullWidth:!0,label:"Email",type:"email",value:o,onChange:u=>t(u.target.value),margin:"normal",required:!0,autoComplete:"email"}),R(De,{fullWidth:!0,label:"Password",type:"password",value:a,onChange:u=>i(u.target.value),margin:"normal",required:!0,autoComplete:"current-password"}),R(Ao,{type:"submit",fullWidth:!0,variant:"contained",size:"large",disabled:g,startIcon:g?R(Go,{size:16}):null,sx:{mt:3,mb:2},children:g?"Logging in...":"Login"})]}):R(Ao,{fullWidth:!0,variant:"contained",size:"large",onClick:()=>n(!0),sx:{mt:2},children:"Show Login Form"}),l&&R(bo,{severity:"error",sx:{mt:2},onClose:d,children:l})]})}function ws(){let{isAuthenticated:o,isLoading:t,isExpiringSoon:a,expiresIn:i}=Q();return t?X(co,{sx:{display:"flex",alignItems:"center",gap:1},children:[R(Go,{size:16}),R(ro,{variant:"caption",children:"Loading session..."})]}):o?X(co,{children:[R(ro,{variant:"caption",color:"success.main",children:"\u2713 Authenticated"}),a&&X(ro,{variant:"caption",color:"warning.main",display:"block",children:["\u26A0 Token expires in ",Math.round(i/1e3/60)," min"]})]}):R(ro,{variant:"caption",color:"text.secondary",children:"Not logged in"})}export{Ln as a,Mr as b,ke as c,Le as d,us as e,bs as f,ws as g};
|
|
1
|
+
import{b as Yo,c as G,h as Qo,j as Q,l as Zo}from"./chunk-52QAU7WN.mjs";import{g as z}from"./chunk-BJ6PIVZR.mjs";import{a as Jo,e as Xo}from"./chunk-5JKS55SE.mjs";import{Box as wr,Typography as Pr}from"@mui/material";import{createContext as Ne,useContext as Ve,useMemo as ee}from"react";import{useState as Bo,useEffect as Ue}from"react";var oe=(o,t)=>{let[a,i]=Bo({}),[f,n]=Bo(!1),[s,g]=Bo(null);return Ue(()=>{if(console.log("\u{1F527} [I18nProvider] Hybrid translation loading:",{hasProvidedTranslations:!!t&&Object.keys(t).length>0,hasUrl:!!o,providedKeys:t?Object.keys(t).length:0}),t&&Object.keys(t).length>0){console.log("\u2705 [I18nProvider] Using provided translations (highest priority)"),i(t),n(!1),g(null);return}if(!o){console.log("\u26A0\uFE0F [I18nProvider] No translations provided, using empty object (keys will show as-is)"),i({}),n(!1),g(null);return}console.log("\u{1F310} [I18nProvider] Loading translations from URL:",o);let l=!1;return n(!0),g(null),fetch(o).then(y=>{if(!y.ok)throw new Error(`Failed to load translations: ${y.status}`);return y.json()}).then(y=>{l||(console.log("\u2705 [I18nProvider] Translations loaded successfully from URL:",{url:o,keysLoaded:Object.keys(y).length}),i(y),n(!1))}).catch(y=>{l||(console.error("\u274C [I18nProvider] Failed to load translations from URL:",o,y),g(y.message),console.log("\u{1F504} [I18nProvider] Falling back to empty translations (keys will show as-is)"),i({}),n(!1))}),()=>{l=!0}},[o,t]),{translations:a,loading:f,error:s}};import{jsx as re}from"react/jsx-runtime";var te=Ne(null),Me=(o,t)=>o&&o[t]?o[t]:t.split(".").reduce((a,i)=>a&&typeof a=="object"?a[i]:void 0,o),ne=({children:o,translations:t,translationsUrl:a,language:i="en"})=>{let{translations:f,loading:n}=oe(a,t),s=ee(()=>(l,y)=>{let c=Me(f,l);return c==null&&(console.log(`\u{1F50D} [I18nProvider] Translation not found for key: "${l}" - showing key as-is`),c=l),y&&typeof c=="string"&&Object.entries(y).forEach(([h,d])=>{c=c.replace(new RegExp(`{{${h}}}`,"g"),d)}),typeof c=="string"?c:l},[f]),g=ee(()=>({t:s,language:i}),[s,i]);return n?re("div",{children:"Loading translations..."}):re(te.Provider,{value:g,children:o})},V=()=>{let o=Ve(te);if(!o)throw new Error("useTranslation must be used within I18nProvider");return o};import{createContext as He,useContext as $e,useReducer as je,useEffect as se}from"react";import{jsx as Ge}from"react/jsx-runtime";var ae={currentScreen:"login",searchParams:{},formData:{username:"",password:"",email:"",code:"",newPassword:"",confirmPassword:""},loading:!1,errors:{global:[]},emailSent:!1,codeAlreadyExists:!1,codeValidated:!1,fromCodeVerification:!1,config:{}};function qe(o,t){switch(t.type){case"SET_SCREEN":let a={...o,currentScreen:t.payload.screen,searchParams:t.payload.params||o.searchParams,errors:{global:[]}},i=new URLSearchParams(a.searchParams),f=i.toString()?`?${i.toString()}`:window.location.pathname;try{window.history.replaceState({},"",f)}catch{}return a;case"SET_SEARCH_PARAMS":return{...o,searchParams:t.payload};case"UPDATE_FORM_DATA":return{...o,formData:{...o.formData,...t.payload},errors:{...o.errors,...Object.keys(t.payload).reduce((n,s)=>({...n,[s]:void 0}),{})}};case"SET_LOADING":return{...o,loading:t.payload};case"SET_ERRORS":return{...o,errors:{...o.errors,...t.payload}};case"CLEAR_ERRORS":return{...o,errors:{global:[]}};case"SET_EMAIL_SENT":return{...o,emailSent:t.payload};case"SET_CODE_ALREADY_EXISTS":return{...o,codeAlreadyExists:t.payload};case"SET_CODE_VALIDATED":return{...o,codeValidated:t.payload};case"SET_FROM_CODE_VERIFICATION":return{...o,fromCodeVerification:t.payload};case"RESET_FORM":return{...o,formData:ae.formData,errors:{global:[]},loading:!1,emailSent:!1,codeAlreadyExists:!1,codeValidated:!1,fromCodeVerification:!1};case"INIT_CONFIG":return{...o,config:t.payload};default:return o}}var ie=He(void 0),le=({children:o,initialScreen:t="login",config:a,autoReadFromCookies:i=!0})=>{let[f,n]=je(qe,{...ae,currentScreen:t});se(()=>{n({type:"INIT_CONFIG",payload:(()=>{let e={};if(i)try{let r=Jo("logo");if(r){let m=decodeURIComponent(r);m.startsWith("http")&&(e.logo=m)}}catch(r){console.error("Error reading configuration from cookies:",r)}return{publicApiKey:a?.publicApiKey,env:a?.env,appName:a?.appName,logo:a?.logo||e.logo,loginActions:a?.loginActions}})()})},[a,i]),se(()=>{let d=new URLSearchParams(window.location.search),e={};d.forEach((r,m)=>{e[m]=r}),Object.keys(e).length>0&&n({type:"SET_SEARCH_PARAMS",payload:e}),t==="checkCode"&&e.email&&n({type:"UPDATE_FORM_DATA",payload:{email:e.email,code:e.code||""}}),t==="resetPassword"&&e.link&&n({type:"SET_SEARCH_PARAMS",payload:e})},[t]);let h={state:f,dispatch:n,setScreen:(d,e)=>{n({type:"SET_SCREEN",payload:{screen:d,params:e}})},updateFormData:d=>{n({type:"UPDATE_FORM_DATA",payload:d})},setFieldError:(d,e)=>{n({type:"SET_ERRORS",payload:{[d]:e}})},clearErrors:()=>{n({type:"CLEAR_ERRORS"})},setLoading:d=>{n({type:"SET_LOADING",payload:d})}};return Ge(ie.Provider,{value:h,children:o})},vo=()=>{let o=$e(ie);if(o===void 0)throw new Error("useLoginState must be used within a LoginStateProvider");return o};import{useEffect as Ke,useRef as Ye}from"react";import{Typography as Fo,TextField as ce,Button as Je,Box as fo,CircularProgress as Xe,Alert as Qe,Link as de}from"@mui/material";import{Fragment as or,jsx as M,jsxs as po}from"react/jsx-runtime";var Ze=({onScreenChange:o,onExternalNavigate:t,onLoginSuccess:a,onError:i,redirectUrl:f="/"})=>{let{crudify:n}=G(),{state:s,updateFormData:g,setFieldError:l,clearErrors:y,setLoading:c}=vo(),{login:h}=Q(),d=V(),{t:e}=d,r=d.i18n,m=Ye(null),P=Xo(e,{currentLanguage:r?.language,enableDebug:!1}),C=()=>{if(s.searchParams.redirect)try{let p=decodeURIComponent(s.searchParams.redirect);if(p.startsWith("/")&&!p.startsWith("//"))return p}catch{}return f||"/"};Ke(()=>{let p=setTimeout(()=>{m.current&&m.current.focus()},100);return()=>clearTimeout(p)},[]);let u=p=>{console.log("\u{1F50D} [LoginForm] Translating parsed error:",p);let S=P.translateError({code:p.code,message:p.message,field:p.field});return console.log("\u{1F50D} [LoginForm] Translation result:",S),S},x=async()=>{if(!s.loading){if(!s.formData.username.trim()){l("username",e("login.usernameRequired"));return}if(!s.formData.password.trim()){l("password",e("login.passwordRequired"));return}y(),c(!0);try{let p=await h(s.formData.username,s.formData.password);if(c(!1),p.success){console.log("\u{1F510} LoginForm - Login successful via SessionProvider, calling onLoginSuccess");let S=C();a&&a(p.data,S)}else{let S=p.rawResponse||p;w(S)}}catch(p){c(!1);let J=z(p).map(u);l("global",J),i&&i(J.join(", "))}}},w=p=>{z(p).forEach(J=>{if(J.field)l(J.field,u(J));else{let mo=s.errors.global||[];l("global",[...mo,u(J)])}})};return po(or,{children:[po(fo,{component:"form",noValidate:!0,onSubmit:p=>{p.preventDefault(),x()},onKeyDown:p=>{p.key==="Enter"&&!s.loading&&(p.preventDefault(),x())},sx:{width:"100%",display:"flex",flexDirection:"column",gap:2},children:[po(fo,{sx:{mb:1},children:[M(Fo,{variant:"body2",component:"label",htmlFor:"email",sx:{display:"block",fontWeight:500,color:"grey.700",mb:.5},children:e("login.usernameOrEmailLabel")}),M(ce,{fullWidth:!0,id:"email",name:"email",type:"email",value:s.formData.username,disabled:s.loading,onChange:p=>g({username:p.target.value}),error:!!s.errors.username,helperText:s.errors.username,autoComplete:"email",placeholder:e("login.usernameOrEmailPlaceholder"),inputRef:m,required:!0})]}),po(fo,{sx:{mb:1},children:[M(Fo,{variant:"body2",component:"label",htmlFor:"password",sx:{display:"block",fontWeight:500,color:"grey.700",mb:.5},children:e("login.passwordLabel")}),M(ce,{fullWidth:!0,id:"password",name:"password",type:"password",value:s.formData.password,disabled:s.loading,onChange:p=>g({password:p.target.value}),error:!!s.errors.password,helperText:s.errors.password,autoComplete:"current-password",placeholder:e("login.passwordPlaceholder"),required:!0})]}),s.config.loginActions?.includes("forgotPassword")&&M(fo,{sx:{display:"flex",justifyContent:"flex-end",alignItems:"center"},children:M(de,{sx:{cursor:"pointer"},onClick:()=>{o?.("forgotPassword",s.searchParams)},variant:"body2",color:"secondary",children:e("login.forgotPasswordLink")})}),M(Je,{disabled:s.loading,type:"submit",fullWidth:!0,variant:"contained",color:"primary",sx:{mt:1,mb:2},children:s.loading?M(Xe,{size:20}):e("login.loginButton")})]}),M(fo,{children:s.errors.global&&s.errors.global.length>0&&s.errors.global.map((p,S)=>M(Qe,{variant:"filled",sx:{mt:2},severity:"error",children:M("div",{children:p})},S))}),s.config.loginActions?.includes("createUser")&&po(Fo,{variant:"body2",align:"center",sx:{color:"text.secondary",mt:3},children:[e("login.noAccountPrompt")," ",M(de,{sx:{cursor:"pointer"},onClick:()=>{let S=`/public/users/create${Object.keys(s.searchParams).length>0?`?${new URLSearchParams(s.searchParams).toString()}`:""}`;t?.(S)},fontWeight:"medium",color:"secondary",children:e("login.signUpLink")})]})]})},me=Ze;import{useState as so}from"react";import{Typography as ao,TextField as er,Button as ue,Box as Z,CircularProgress as rr,Alert as tr,Link as Do}from"@mui/material";import{Fragment as fe,jsx as B,jsxs as to}from"react/jsx-runtime";var nr=({onScreenChange:o,onError:t})=>{let{crudify:a}=G(),[i,f]=so(""),[n,s]=so(!1),[g,l]=so([]),[y,c]=so(null),[h,d]=so(!1),[e,r]=so(!1),{t:m}=V(),P=v=>{let E=[`errors.auth.${v.code}`,`errors.data.${v.code}`,`errors.system.${v.code}`,`errors.${v.code}`,`forgotPassword.${v.code.toLowerCase()}`];for(let p of E){let S=m(p);if(S!==p)return S}return v.message||m("error.unknown")},C=v=>/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(v),u=async()=>{if(!(n||!a)){if(l([]),c(null),!i){c(m("forgotPassword.emailRequired"));return}if(!C(i)){c(m("forgotPassword.invalidEmail"));return}s(!0);try{let v=[{operation:"requestPasswordReset",data:{email:i}}],E=await a.transaction(v);if(E.success)E.data&&E.data.existingCodeValid?r(!0):d(!0);else{let S=z(E).map(P);l(S)}}catch(v){let p=z(v).map(P);l(p),t&&t(p.join(", "))}finally{s(!1)}}},x=()=>{o?.("login")},w=()=>{if(h||e){o?.("checkCode",{email:i});return}if(!i){c(m("forgotPassword.emailRequired"));return}if(!C(i)){c(m("forgotPassword.invalidEmail"));return}o?.("checkCode",{email:i})};return h||e?B(fe,{children:to(Z,{sx:{width:"100%",display:"flex",flexDirection:"column",gap:2,textAlign:"center"},children:[to(Z,{sx:{mb:2},children:[B(ao,{variant:"h5",component:"h1",sx:{mb:1,fontWeight:600},children:m(e?"forgotPassword.codeAlreadyExistsMessage":"forgotPassword.emailSentMessage")}),B(ao,{variant:"body2",sx:{color:e?"success.main":"grey.600"},children:m("forgotPassword.checkEmailInstructions")})]}),B(ue,{type:"button",onClick:w,fullWidth:!0,variant:"contained",color:"primary",sx:{mt:2,mb:2},children:m("forgotPassword.enterCodeLink")}),B(Z,{sx:{display:"flex",justifyContent:"center",alignItems:"center"},children:B(Do,{sx:{cursor:"pointer"},onClick:x,variant:"body2",color:"secondary",children:m("common.back")})})]})}):to(fe,{children:[to(Z,{component:"form",noValidate:!0,sx:{width:"100%",display:"flex",flexDirection:"column",gap:2},children:[to(Z,{sx:{mb:2},children:[B(ao,{variant:"h5",component:"h1",sx:{mb:1,fontWeight:600},children:m("forgotPassword.title")}),B(ao,{variant:"body2",sx:{color:"grey.600"},children:m("forgotPassword.instructions")})]}),to(Z,{sx:{mb:1},children:[B(ao,{variant:"body2",component:"label",htmlFor:"email",sx:{display:"block",fontWeight:500,color:"grey.700",mb:.5},children:m("forgotPassword.emailLabel")}),B(er,{fullWidth:!0,id:"email",name:"email",type:"email",value:i,disabled:n,onChange:v=>f(v.target.value),error:!!y,helperText:y,autoComplete:"email",placeholder:m("forgotPassword.emailPlaceholder"),required:!0})]}),B(ue,{disabled:n,type:"button",onClick:u,fullWidth:!0,variant:"contained",color:"primary",sx:{mt:2,mb:2},children:n?B(rr,{size:20}):m("forgotPassword.sendCodeButton")}),to(Z,{sx:{display:"flex",justifyContent:"center",alignItems:"center",gap:2},children:[B(Do,{sx:{cursor:"pointer"},onClick:x,variant:"body2",color:"secondary",children:m("common.back")}),B(ao,{variant:"body2",sx:{color:"grey.400"},children:"\u2022"}),B(Do,{sx:{cursor:"pointer"},onClick:w,variant:"body2",color:"secondary",children:m("login.alreadyHaveCodeLink")})]})]}),B(Z,{children:g.length>0&&g.map((v,E)=>B(tr,{variant:"filled",sx:{mt:2},severity:"error",children:v},E))})]})},pe=nr;import{useState as U,useEffect as ge}from"react";import{Typography as To,TextField as ye,Button as sr,Box as oo,CircularProgress as xe,Alert as he,Link as ar}from"@mui/material";import{Fragment as lr,jsx as F,jsxs as go}from"react/jsx-runtime";var ir=({onScreenChange:o,onError:t,searchParams:a,onResetSuccess:i})=>{let{crudify:f}=G(),[n,s]=U(""),[g,l]=U(""),[y,c]=U(!1),[h,d]=U([]),[e,r]=U(null),[m,P]=U(null),[C,u]=U(""),[x,w]=U(""),[v,E]=U(!1),[p,S]=U(!0),[J,mo]=U(!1),[wo,Io]=U(null),[_e,Ko]=U(!1),{t:I}=V(),Po=T=>{let k=[`errors.auth.${T.code}`,`errors.data.${T.code}`,`errors.system.${T.code}`,`errors.${T.code}`,`resetPassword.${T.code.toLowerCase()}`];for(let O of k){let W=I(O);if(W!==O)return W}return T.message||I("error.unknown")},Co=T=>a?a instanceof URLSearchParams?a.get(T):a[T]||null:null;ge(()=>{if(a){if(a){let T=Co("fromCodeVerification"),k=Co("email"),O=Co("code");if(T==="true"&&k&&O){u(k),w(O),E(!0),mo(!0),S(!1);return}let W=Co("link");if(W)try{let H=decodeURIComponent(W),[$,uo]=H.split("/");if($&&uo&&$.length===6){w($),u(uo),E(!1),Io({email:uo,code:$});return}}catch{}if(k&&O){u(k),w(O),E(!1),Io({email:k,code:O});return}}d([I("resetPassword.invalidCode")]),S(!1),setTimeout(()=>o?.("forgotPassword"),3e3)}},[a,f,I,o]),ge(()=>{f&&wo&&!_e&&(Ko(!0),(async(k,O)=>{try{let W=[{operation:"validatePasswordResetCode",data:{email:k,codePassword:O}}],H=await f.transaction(W);if(H.data&&Array.isArray(H.data)){let $=H.data[0];if($&&$.response&&$.response.status==="OK"){mo(!0);return}}if(H.success)mo(!0);else{let uo=z(H).map(Po);d(uo),setTimeout(()=>o?.("forgotPassword"),3e3)}}catch(W){let $=z(W).map(Po);d($),setTimeout(()=>o?.("forgotPassword"),3e3)}finally{S(!1),Io(null),Ko(!1)}})(wo.email,wo.code))},[f,wo,I,o]);let Oe=T=>T.length<8?I("resetPassword.passwordTooShort"):null,ze=async()=>{if(y||!f)return;d([]),r(null),P(null);let T=!1;if(!n)r(I("resetPassword.newPasswordRequired")),T=!0;else{let k=Oe(n);k&&(r(k),T=!0)}if(g?n!==g&&(P(I("resetPassword.passwordsDoNotMatch")),T=!0):(P(I("resetPassword.confirmPasswordRequired")),T=!0),!T){c(!0);try{let k=[{operation:"validateAndResetPassword",data:{email:C,codePassword:x,newPassword:n}}],O=await f.transaction(k);if(O.success)d([]),setTimeout(()=>{i?.()},1e3);else{let H=z(O).map(Po);d(H)}}catch(k){let W=z(k).map(Po);d(W),t&&t(W.join(", "))}c(!1)}},We=()=>{v?o?.("checkCode",{email:C}):o?.("forgotPassword")};return p?F(oo,{sx:{display:"flex",justifyContent:"center",alignItems:"center",minHeight:"300px"},children:F(xe,{})}):J?go(lr,{children:[go(oo,{component:"form",noValidate:!0,sx:{width:"100%",display:"flex",flexDirection:"column",gap:2},children:[go(oo,{sx:{mb:2},children:[F(To,{variant:"h5",component:"h1",sx:{mb:1,fontWeight:600},children:I("resetPassword.title")}),F(To,{variant:"body2",sx:{color:"grey.600"},children:I("resetPassword.instructions")})]}),go(oo,{sx:{mb:1},children:[F(To,{variant:"body2",component:"label",htmlFor:"newPassword",sx:{display:"block",fontWeight:500,color:"grey.700",mb:.5},children:I("resetPassword.newPasswordLabel")}),F(ye,{fullWidth:!0,id:"newPassword",name:"newPassword",type:"password",value:n,disabled:y,onChange:T=>s(T.target.value),error:!!e,helperText:e,autoComplete:"new-password",placeholder:I("resetPassword.newPasswordPlaceholder"),required:!0})]}),go(oo,{sx:{mb:1},children:[F(To,{variant:"body2",component:"label",htmlFor:"confirmPassword",sx:{display:"block",fontWeight:500,color:"grey.700",mb:.5},children:I("resetPassword.confirmPasswordLabel")}),F(ye,{fullWidth:!0,id:"confirmPassword",name:"confirmPassword",type:"password",value:g,disabled:y,onChange:T=>l(T.target.value),error:!!m,helperText:m,autoComplete:"new-password",placeholder:I("resetPassword.confirmPasswordPlaceholder"),required:!0})]}),F(sr,{disabled:y,type:"button",onClick:ze,fullWidth:!0,variant:"contained",color:"primary",sx:{mt:2,mb:2},children:y?F(xe,{size:20}):I("resetPassword.resetPasswordButton")}),F(oo,{sx:{display:"flex",justifyContent:"center",alignItems:"center"},children:F(ar,{sx:{cursor:"pointer"},onClick:We,variant:"body2",color:"secondary",children:I("common.back")})})]}),F(oo,{children:h.length>0&&h.map((T,k)=>F(he,{variant:"filled",sx:{mt:2},severity:"error",children:T},k))})]}):F(oo,{children:h.length>0&&h.map((T,k)=>F(he,{variant:"filled",sx:{mt:2},severity:"error",children:T},k))})},be=ir;import{useState as yo,useEffect as cr}from"react";import{Typography as _o,TextField as dr,Button as mr,Box as xo,CircularProgress as ur,Alert as fr,Link as pr}from"@mui/material";import{Fragment as yr,jsx as K,jsxs as Eo}from"react/jsx-runtime";var gr=({onScreenChange:o,onError:t,searchParams:a})=>{let{crudify:i}=G(),[f,n]=yo(""),[s,g]=yo(!1),[l,y]=yo([]),[c,h]=yo(null),[d,e]=yo(""),{t:r}=V(),m=w=>a?a instanceof URLSearchParams?a.get(w):a[w]||null:null,P=w=>{let v=[`errors.auth.${w.code}`,`errors.data.${w.code}`,`errors.system.${w.code}`,`errors.${w.code}`,`checkCode.${w.code.toLowerCase()}`];for(let E of v){let p=r(E);if(p!==E)return p}return w.message||r("error.unknown")};cr(()=>{let w=m("email");w?e(w):o?.("forgotPassword")},[a,o]);let C=async()=>{if(!(s||!i)){if(y([]),h(null),!f){h(r("checkCode.codeRequired"));return}if(f.length!==6){h(r("checkCode.codeRequired"));return}g(!0);try{let w=[{operation:"validatePasswordResetCode",data:{email:d,codePassword:f}}],v=await i.transaction(w);if(v.success)o?.("resetPassword",{email:d,code:f,fromCodeVerification:"true"});else{let p=z(v).map(P);y(p),g(!1)}}catch(w){let E=z(w).map(P);y(E),g(!1),t&&t(E.join(", "))}}},u=()=>{o?.("forgotPassword")},x=w=>{let v=w.target.value.replace(/\D/g,"").slice(0,6);n(v)};return Eo(yr,{children:[Eo(xo,{component:"form",noValidate:!0,sx:{width:"100%",display:"flex",flexDirection:"column",gap:2},children:[Eo(xo,{sx:{mb:2},children:[K(_o,{variant:"h5",component:"h1",sx:{mb:1,fontWeight:600},children:r("checkCode.title")}),K(_o,{variant:"body2",sx:{color:"grey.600"},children:r("checkCode.instructions")})]}),Eo(xo,{sx:{mb:1},children:[K(_o,{variant:"body2",component:"label",htmlFor:"code",sx:{display:"block",fontWeight:500,color:"grey.700",mb:.5},children:r("checkCode.codeLabel")}),K(dr,{fullWidth:!0,id:"code",name:"code",type:"text",value:f,disabled:s,onChange:x,error:!!c,helperText:c,placeholder:r("checkCode.codePlaceholder"),inputProps:{maxLength:6,style:{textAlign:"center",fontSize:"1.5rem",letterSpacing:"0.4rem"}},required:!0})]}),K(mr,{disabled:s||f.length!==6,type:"button",onClick:C,fullWidth:!0,variant:"contained",color:"primary",sx:{mt:2,mb:2},children:s?K(ur,{size:20}):r("checkCode.verifyButton")}),K(xo,{sx:{display:"flex",justifyContent:"center",alignItems:"center"},children:K(pr,{sx:{cursor:"pointer"},onClick:u,variant:"body2",color:"secondary",children:r("common.back")})})]}),K(xo,{children:l.length>0&&l.map((w,v)=>K(fr,{sx:{mt:2},severity:"error",children:w},v))})]})},we=gr;import{Box as xr,CircularProgress as hr,Alert as Pe,Typography as Oo}from"@mui/material";import{Fragment as br,jsx as io,jsxs as Ce}from"react/jsx-runtime";var ve=({children:o,fallback:t})=>{let{isLoading:a,error:i,isInitialized:f}=G(),{t:n}=V();return a?t||Ce(xr,{sx:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",minHeight:"200px",gap:2},children:[io(hr,{}),io(Oo,{variant:"body2",color:"text.secondary",children:n("login.initializing")!=="login.initializing"?n("login.initializing"):"Initializing..."})]}):i?io(Pe,{severity:"error",sx:{mt:2},children:Ce(Oo,{variant:"body2",children:[n("login.initializationError")!=="login.initializationError"?n("login.initializationError"):"Initialization error",":"," ",i]})}):f?io(br,{children:o}):io(Pe,{severity:"warning",sx:{mt:2},children:io(Oo,{variant:"body2",children:n("login.notInitialized")!=="login.notInitialized"?n("login.notInitialized"):"System not initialized"})})};import{jsx as j,jsxs as Tr}from"react/jsx-runtime";var Cr=({onScreenChange:o,onExternalNavigate:t,onLoginSuccess:a,onError:i,redirectUrl:f="/"})=>{let{t:n}=V(),{state:s,setScreen:g}=vo(),{config:l}=Q(),{showNotification:y}=Qo(),c=(d,e)=>{let r=e;d==="login"?r={}:d==="forgotPassword"&&!e&&(r={}),g(d,r),o?.(d,r)},h=()=>{let d={onScreenChange:c,onExternalNavigate:t,onError:i,redirectUrl:f};switch(s.currentScreen){case"forgotPassword":return j(pe,{...d});case"checkCode":return j(we,{...d,searchParams:s.searchParams});case"resetPassword":return j(be,{...d,searchParams:s.searchParams,onResetSuccess:()=>{let e=n("resetPassword.successMessage");y(e,"success"),c("login")}});default:return j(me,{...d,onLoginSuccess:a})}};return Tr(ve,{children:[j(wr,{sx:{display:"flex",justifyContent:"center",mb:3},children:j("img",{src:l.logo||"https://logos.crudia.com/nocios-default.png",alt:n("login.logoAlt"),style:{width:"100%",maxWidth:"150px",height:"auto"},onError:d=>{let e=d.target;e.src="https://logos.crudia.com/nocios-default.png"}})}),!l.logo&&l.appName&&j(Pr,{variant:"h6",component:"h1",sx:{textAlign:"center",mb:2},children:l.appName}),h()]})},vr=({translations:o,translationsUrl:t,language:a="en",initialScreen:i="login",autoReadFromCookies:f=!0,...n})=>{let{config:s}=Q();return j(ne,{translations:o,translationsUrl:t,language:a,children:j(Yo,{config:s,children:j(le,{config:s,initialScreen:i,autoReadFromCookies:f,children:j(Cr,{...n})})})})},Ln=vr;import{Box as N,Card as Te,CardContent as Ee,Typography as q,Chip as So,Avatar as Er,Divider as Sr,CircularProgress as kr,Alert as Se,List as Lr,ListItem as zo,ListItemText as Wo,ListItemIcon as Rr,Collapse as Ar,IconButton as Uo}from"@mui/material";import{Person as Ir,Email as Br,Badge as Fr,Security as Dr,Schedule as _r,AccountCircle as Or,ExpandMore as zr,ExpandLess as Wr,Info as Ur}from"@mui/icons-material";import{useState as Nr}from"react";import{Fragment as Hr,jsx as b,jsxs as L}from"react/jsx-runtime";var Vr=({showExtendedData:o=!0,showProfileCard:t=!0,autoRefresh:a=!0})=>{let{userProfile:i,loading:f,error:n,extendedData:s,refreshProfile:g}=Zo({autoFetch:a,retryOnError:!0,maxRetries:3}),[l,y]=Nr(!1);if(f)return L(N,{display:"flex",justifyContent:"center",alignItems:"center",p:3,children:[b(kr,{}),b(q,{variant:"body2",sx:{ml:2},children:"Cargando perfil de usuario..."})]});if(n)return L(Se,{severity:"error",action:b(Uo,{color:"inherit",size:"small",onClick:g,children:b(q,{variant:"caption",children:"Reintentar"})}),children:["Error al cargar el perfil: ",n]});if(!i)return b(Se,{severity:"warning",children:"No se encontr\xF3 informaci\xF3n del usuario"});let c=s?.displayData||{},h=s?.totalFields||0,d=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}},e=(u,x)=>x==null?"No disponible":typeof x=="boolean"?x?"S\xED":"No":Array.isArray(x)?x.length>0?x.join(", "):"Ninguno":typeof x=="object"?JSON.stringify(x,null,2):String(x),r=[{key:"id",label:"ID",icon:b(Fr,{})},{key:"email",label:"Email",icon:b(Br,{})},{key:"username",label:"Usuario",icon:b(Ir,{})},{key:"fullName",label:"Nombre completo",icon:b(Or,{})},{key:"role",label:"Rol",icon:b(Dr,{})}],m=[{key:"firstName",label:"Nombre"},{key:"lastName",label:"Apellido"},{key:"isActive",label:"Activo"},{key:"lastLogin",label:"\xDAltimo login"},{key:"createdAt",label:"Creado"},{key:"updatedAt",label:"Actualizado"}],P=[...r.map(u=>u.key),...m.map(u=>u.key),"permissions"],C=Object.keys(c).filter(u=>!P.includes(u)).map(u=>({key:u,label:u}));return L(N,{children:[t&&b(Te,{sx:{mb:2},children:L(Ee,{children:[L(N,{display:"flex",alignItems:"center",mb:2,children:[b(Er,{src:c.avatar,sx:{width:56,height:56,mr:2},children:c.fullName?.[0]||c.username?.[0]||c.email?.[0]}),L(N,{children:[b(q,{variant:"h6",children:c.fullName||c.username||c.email}),b(q,{variant:"body2",color:"text.secondary",children:c.role||"Usuario"}),c.isActive!==void 0&&b(So,{label:c.isActive?"Activo":"Inactivo",color:c.isActive?"success":"error",size:"small",sx:{mt:.5}})]})]}),b(N,{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(250px, 1fr))",gap:2,children:r.map(({key:u,label:x,icon:w})=>c[u]?L(N,{display:"flex",alignItems:"center",children:[b(N,{sx:{mr:1,color:"text.secondary"},children:w}),L(N,{children:[b(q,{variant:"caption",color:"text.secondary",children:x}),b(q,{variant:"body2",children:e(u,c[u])})]})]},u):null)}),c.permissions&&Array.isArray(c.permissions)&&c.permissions.length>0&&L(N,{mt:2,children:[b(q,{variant:"caption",color:"text.secondary",display:"block",children:"Permisos"}),L(N,{display:"flex",flexWrap:"wrap",gap:.5,mt:.5,children:[c.permissions.slice(0,5).map((u,x)=>b(So,{label:u,size:"small",variant:"outlined"},x)),c.permissions.length>5&&b(So,{label:`+${c.permissions.length-5} m\xE1s`,size:"small"})]})]})]})}),o&&b(Te,{children:L(Ee,{children:[L(N,{display:"flex",justifyContent:"space-between",alignItems:"center",mb:2,children:[L(q,{variant:"h6",display:"flex",alignItems:"center",children:[b(Ur,{sx:{mr:1}}),"Informaci\xF3n Detallada"]}),b(So,{label:`${h} campos totales`,size:"small"})]}),L(Lr,{dense:!0,children:[m.map(({key:u,label:x})=>c[u]!==void 0&&L(zo,{divider:!0,children:[b(Rr,{children:b(_r,{fontSize:"small"})}),b(Wo,{primary:x,secondary:u.includes("At")||u.includes("Login")?d(c[u]):e(u,c[u])})]},u)),C.length>0&&L(Hr,{children:[b(Sr,{sx:{my:1}}),b(zo,{children:b(Wo,{primary:L(N,{display:"flex",justifyContent:"space-between",alignItems:"center",children:[L(q,{variant:"subtitle2",children:["Campos Personalizados (",C.length,")"]}),b(Uo,{size:"small",onClick:()=>y(!l),children:l?b(Wr,{}):b(zr,{})})]})})}),b(Ar,{in:l,children:C.map(({key:u,label:x})=>b(zo,{sx:{pl:4},children:b(Wo,{primary:x,secondary:e(u,c[u])})},u))})]})]}),L(N,{mt:2,display:"flex",justifyContent:"space-between",alignItems:"center",children:[L(q,{variant:"caption",color:"text.secondary",children:["\xDAltima actualizaci\xF3n: ",d(c.updatedAt)]}),b(Uo,{size:"small",onClick:g,disabled:f,children:b(q,{variant:"caption",children:"Actualizar"})})]})]})})]})},Mr=Vr;var ke=["create","read","update","delete"],Le=["create","read","update","delete"];import{useRef as ft}from"react";import{useTranslation as pt}from"react-i18next";import{Box as Lo,Typography as Be,Button as gt,Stack as yt,Alert as Fe,Divider as xt}from"@mui/material";import{Add as ht}from"@mui/icons-material";import{forwardRef as ot}from"react";import{useTranslation as et}from"react-i18next";import{Box as no,FormControl as rt,InputLabel as tt,Select as nt,MenuItem as st,IconButton as at,Typography as lo,FormHelperText as it,Stack as ko,Paper as Ie,Divider as lt,Button as $o}from"@mui/material";import{Delete as ct,SelectAll as dt,ClearAll as mt}from"@mui/icons-material";import{useState as $r,useEffect as jr,useRef as qr}from"react";import{useTranslation as Gr}from"react-i18next";import{Box as No,Typography as ho,Button as Re,Stack as Vo,FormHelperText as Ae,ToggleButton as Mo,ToggleButtonGroup as Kr}from"@mui/material";import{CheckCircle as Yr,Cancel as Jr,SelectAll as Xr,ClearAll as Qr}from"@mui/icons-material";import{jsx as D,jsxs as eo}from"react/jsx-runtime";var Zr=({value:o,onChange:t,availableFields:a,error:i,disabled:f=!1})=>{let{t:n}=Gr(),[s,g]=$r("custom"),l=qr(!1);jr(()=>{let e=o||{allow:[],owner_allow:[],deny:[]},r=new Set(a),m=(e.allow||[]).filter(x=>r.has(x)),P=(e.owner_allow||[]).filter(x=>r.has(x)),C=(e.deny||[]).filter(x=>r.has(x));a.forEach(x=>{!m.includes(x)&&!P.includes(x)&&!C.includes(x)&&C.push(x)});let u={allow:m,owner_allow:P,deny:C};JSON.stringify(u)!==JSON.stringify(e)&&t(u),m.length===a.length?g("all"):C.length===a.length?g("none"):g("custom")},[a,o]);let y=()=>{l.current=!0,t({allow:[...a],owner_allow:[],deny:[]}),g("all"),setTimeout(()=>{l.current=!1},0)},c=()=>{l.current=!0,t({allow:[],owner_allow:[],deny:[...a]}),g("none"),setTimeout(()=>{l.current=!1},0)},h=e=>o?.allow?.includes(e)?"allow":o?.owner_allow?.includes(e)?"owner_allow":"deny",d=(e,r)=>{l.current=!0;let m=new Set(o?.allow||[]),P=new Set(o?.owner_allow||[]),C=new Set(o?.deny||[]);m.delete(e),P.delete(e),C.delete(e),r==="allow"&&m.add(e),r==="owner_allow"&&P.add(e),r==="deny"&&C.add(e),t({allow:Array.from(m),owner_allow:Array.from(P),deny:Array.from(C)}),g("custom"),setTimeout(()=>{l.current=!1},0)};return a.length===0?eo(No,{children:[D(ho,{variant:"body2",color:"text.secondary",sx:{mb:1},children:n("modules.form.publicPolicies.fields.conditions.label")}),D(ho,{variant:"body2",color:"text.secondary",sx:{fontStyle:"italic"},children:n("modules.form.publicPolicies.fields.conditions.noFieldsAvailable")}),i&&D(Ae,{error:!0,sx:{mt:1},children:i})]}):eo(No,{children:[D(ho,{variant:"body2",color:"text.secondary",sx:{mb:2},children:n("modules.form.publicPolicies.fields.conditions.label")}),eo(Vo,{direction:"row",spacing:1,sx:{mb:3},children:[D(Re,{variant:s==="all"?"contained":"outlined",startIcon:D(Xr,{}),onClick:y,disabled:f,size:"small",sx:{minWidth:120,...s==="all"&&{backgroundColor:"#16a34a","&:hover":{backgroundColor:"#15803d"}}},children:n("modules.form.publicPolicies.fields.conditions.allFields")}),D(Re,{variant:s==="none"?"contained":"outlined",startIcon:D(Qr,{}),onClick:c,disabled:f,size:"small",sx:{minWidth:120,...s==="none"&&{backgroundColor:"#cf222e","&:hover":{backgroundColor:"#bc1f2c"}}},children:n("modules.form.publicPolicies.fields.conditions.noFields")})]}),eo(No,{sx:{p:2,border:"1px solid #d1d9e0",borderRadius:1,backgroundColor:"#f6f8fa"},children:[D(ho,{variant:"body2",color:"text.secondary",sx:{mb:2},children:n("modules.form.publicPolicies.fields.conditions.help")}),D(Vo,{spacing:1,children:a.map(e=>{let r=h(e);return eo(Vo,{direction:"row",spacing:1,alignItems:"center",children:[D(ho,{variant:"body2",sx:{minWidth:100,fontFamily:"monospace"},children:e}),eo(Kr,{value:r,exclusive:!0,size:"small",children:[eo(Mo,{value:"allow",onClick:()=>d(e,"allow"),disabled:f,sx:{px:2,color:r==="allow"?"#ffffff":"#6b7280",backgroundColor:r==="allow"?"#16a34a":"#f3f4f6",borderColor:r==="allow"?"#16a34a":"#d1d5db","&:hover":{backgroundColor:r==="allow"?"#15803d":"#e5e7eb",borderColor:r==="allow"?"#15803d":"#9ca3af"},"&.Mui-selected":{backgroundColor:"#16a34a",color:"#ffffff","&:hover":{backgroundColor:"#15803d"}}},children:[D(Yr,{sx:{fontSize:16,mr:.5}}),n("modules.form.publicPolicies.fields.conditions.states.allow")]}),D(Mo,{value:"owner_allow",onClick:()=>d(e,"owner_allow"),disabled:f,sx:{px:2,color:r==="owner_allow"?"#ffffff":"#6b7280",backgroundColor:r==="owner_allow"?"#0ea5e9":"#f3f4f6",borderColor:r==="owner_allow"?"#0ea5e9":"#d1d5db","&:hover":{backgroundColor:r==="owner_allow"?"#0284c7":"#e5e7eb",borderColor:r==="owner_allow"?"#0284c7":"#9ca3af"},"&.Mui-selected":{backgroundColor:"#0ea5e9",color:"#ffffff","&:hover":{backgroundColor:"#0284c7"}}},children:n("modules.form.publicPolicies.fields.conditions.states.ownerAllow")}),eo(Mo,{value:"deny",onClick:()=>d(e,"deny"),disabled:f,sx:{px:2,color:r==="deny"?"#ffffff":"#6b7280",backgroundColor:r==="deny"?"#dc2626":"#f3f4f6",borderColor:r==="deny"?"#dc2626":"#d1d5db","&:hover":{backgroundColor:r==="deny"?"#b91c1c":"#e5e7eb",borderColor:r==="deny"?"#b91c1c":"#9ca3af"},"&.Mui-selected":{backgroundColor:"#dc2626",color:"#ffffff","&:hover":{backgroundColor:"#b91c1c"}}},children:[D(Jr,{sx:{fontSize:16,mr:.5}}),n("modules.form.publicPolicies.fields.conditions.states.deny")]})]})]},e)})})]}),i&&D(Ae,{error:!0,sx:{mt:1},children:i})]})},Ho=Zr;import{jsx as A,jsxs as _}from"react/jsx-runtime";var ut=ot(({policy:o,onChange:t,onRemove:a,availableFields:i,isSubmitting:f=!1,usedActions:n,error:s},g)=>{let{t:l}=et(),y=new Set(Array.from(n||[]));y.delete(o.action);let c=ke.map(h=>({value:h,label:l(`modules.form.publicPolicies.fields.action.options.${h}`)}));return _(Ie,{ref:g,sx:{p:3,border:"1px solid #d1d9e0",borderRadius:2,position:"relative",backgroundColor:"#ffffff"},children:[_(no,{sx:{display:"flex",justifyContent:"space-between",alignItems:"flex-start",mb:3},children:[A(lo,{variant:"subtitle1",sx:{fontWeight:600,color:"#111418",fontSize:"1rem"},children:l("modules.form.publicPolicies.policyTitle")}),A(at,{onClick:a,size:"small",disabled:f,"aria-label":l("modules.form.publicPolicies.removePolicy"),sx:{color:"#656d76","&:hover":{color:"#cf222e",backgroundColor:"rgba(207, 34, 46, 0.1)"}},children:A(ct,{})})]}),_(ko,{spacing:3,children:[A(ko,{direction:{xs:"column",md:"row"},spacing:2,children:A(no,{sx:{flex:1,minWidth:200},children:_(rt,{fullWidth:!0,children:[A(tt,{children:l("modules.form.publicPolicies.fields.action.label")}),A(nt,{value:o.action,label:l("modules.form.publicPolicies.fields.action.label"),disabled:f,onChange:h=>{let d=h.target.value,e={...o,action:d};d==="delete"?(e.permission="deny",delete e.fields):(e.fields={allow:[],owner_allow:[],deny:i},delete e.permission),t(e)},sx:{backgroundColor:"#ffffff","&:hover .MuiOutlinedInput-notchedOutline":{borderColor:"#8c959f"},"&.Mui-focused .MuiOutlinedInput-notchedOutline":{borderColor:"#0969da",borderWidth:2}},children:c.map(h=>{let d=y.has(h.value);return A(st,{value:h.value,disabled:d,children:h.label},h.value)})}),s&&A(it,{error:!0,children:s})]})})}),o.action==="delete"?_(no,{children:[A(lo,{variant:"body2",color:"text.secondary",sx:{mb:2},children:l("modules.form.publicPolicies.fields.conditions.label")}),_(ko,{direction:"row",spacing:1,sx:{mb:3},children:[A($o,{variant:o.permission==="*"?"contained":"outlined",startIcon:A(dt,{}),onClick:()=>t({...o,permission:"*"}),disabled:f,size:"small",sx:{minWidth:140,whiteSpace:"nowrap",...o.permission==="*"&&{backgroundColor:"#16a34a","&:hover":{backgroundColor:"#15803d"}}},children:l("modules.form.publicPolicies.fields.conditions.allFields")}),A($o,{variant:o.permission==="owner"?"contained":"outlined",onClick:()=>t({...o,permission:"owner"}),disabled:f,size:"small",sx:{minWidth:140,whiteSpace:"nowrap",...o.permission==="owner"&&{backgroundColor:"#0ea5e9","&:hover":{backgroundColor:"#0284c7"}}},children:l("modules.form.publicPolicies.fields.conditions.states.ownerAllow")}),A($o,{variant:o.permission==="deny"?"contained":"outlined",startIcon:A(mt,{}),onClick:()=>t({...o,permission:"deny"}),disabled:f,size:"small",sx:{minWidth:140,whiteSpace:"nowrap",...o.permission==="deny"&&{backgroundColor:"#cf222e","&:hover":{backgroundColor:"#bc1f2c"}}},children:l("modules.form.publicPolicies.fields.conditions.noFields")})]})]}):A(Ho,{value:o.fields||{allow:[],owner_allow:[],deny:[]},onChange:h=>t({...o,fields:h}),availableFields:i,disabled:f}),A(Ie,{variant:"outlined",sx:{p:2,backgroundColor:"#f9fafb"},children:o.action==="delete"?_(lo,{variant:"body2",sx:{fontFamily:"monospace",color:"text.secondary"},children:[_(no,{component:"span",sx:{color:o.permission==="*"?"#16a34a":o.permission==="owner"?"#0ea5e9":"#dc2626"},children:[l("modules.form.publicPolicies.fields.conditions.states.allow"),":"]})," ",o.permission||"-"]}):_(ko,{spacing:.5,divider:A(lt,{sx:{borderColor:"#e5e7eb"}}),children:[_(lo,{variant:"body2",sx:{fontFamily:"monospace",color:"text.secondary"},children:[_(no,{component:"span",sx:{color:"#16a34a"},children:[l("modules.form.publicPolicies.fields.conditions.states.allow"),":"]})," ",(o?.fields?.allow||[]).join(", ")||"-"]}),_(lo,{variant:"body2",sx:{fontFamily:"monospace",color:"text.secondary"},children:[_(no,{component:"span",sx:{color:"#0ea5e9"},children:[l("modules.form.publicPolicies.fields.conditions.states.ownerAllow"),":"]})," ",(o?.fields?.owner_allow||[]).join(", ")||"-"]}),_(lo,{variant:"body2",sx:{fontFamily:"monospace",color:"text.secondary"},children:[_(no,{component:"span",sx:{color:"#dc2626"},children:[l("modules.form.publicPolicies.fields.conditions.states.deny"),":"]})," ",(o?.fields?.deny||[]).join(", ")||"-"]})]})})]})]})}),jo=ut;import{Fragment as Pt,jsx as Y,jsxs as Ro}from"react/jsx-runtime";var bt=()=>{let o=globalThis?.crypto;return o&&typeof o.randomUUID=="function"?o.randomUUID():`${Date.now()}-${Math.random().toString(16).slice(2)}`},wt=({policies:o,onChange:t,availableFields:a,errors:i,isSubmitting:f=!1})=>{let{t:n}=pt(),s=ft({}),g=new Set((o||[]).map(r=>r.action).filter(Boolean)),l=Le.filter(r=>!g.has(r)),y=l.length>0,c=()=>{let r=l[0]||"create",m={id:bt(),action:r};r==="delete"?m.permission="deny":m.fields={allow:[],owner_allow:[],deny:a};let P=[...o||[],m];t(P),setTimeout(()=>{let C=P.length-1,u=s.current[C];u&&u.scrollIntoView({behavior:"smooth",block:"center"})},100)},h=r=>{let m=[...o];m.splice(r,1),t(m)},d=(()=>{if(!i)return null;if(typeof i=="string")return i;let r=i._error;return typeof r=="string"?r:null})(),e=new Set((o||[]).map(r=>r.action));return Ro(Pt,{children:[Y(xt,{sx:{borderColor:"#e0e4e7"}}),Ro(Lo,{children:[Y(Lo,{display:"flex",justifyContent:"space-between",alignItems:"center",mb:3,children:Ro(Lo,{children:[Y(Be,{variant:"h6",sx:{fontWeight:600,color:"#111418",mb:1},children:n("modules.form.publicPolicies.title")}),Y(Be,{variant:"body2",color:"text.secondary",sx:{fontSize:"0.875rem"},children:n("modules.form.publicPolicies.description")})]})}),d&&Y(Fe,{severity:"error",sx:{mb:3},children:d}),Ro(yt,{spacing:3,children:[(o||[]).length===0?Y(Fe,{severity:"info",children:n("modules.form.publicPolicies.noPolicies")}):o.map((r,m)=>Y(jo,{ref:P=>{s.current[m]=P},policy:r,onChange:P=>{let C=[...o];C[m]=P,t(C)},onRemove:()=>h(m),availableFields:a,isSubmitting:f,usedActions:e,error:typeof i=="object"&&i&&r.id in i?i[r.id]:void 0},r.id)),y&&Y(Lo,{children:Y(gt,{type:"button",variant:"outlined",startIcon:Y(ht,{}),onClick:c,disabled:f,sx:{borderColor:"#d0d7de",color:"#656d76","&:hover":{borderColor:"#8c959f",backgroundColor:"transparent"}},children:n("modules.form.publicPolicies.addPolicy")})})]})]})]})},us=wt;import{useState as qo}from"react";import{Button as Ao,TextField as De,Box as co,Alert as bo,Typography as ro,CircularProgress as Go}from"@mui/material";import{jsx as R,jsxs as X}from"react/jsx-runtime";function bs(){let[o,t]=qo(""),[a,i]=qo(""),[f,n]=qo(!1),{isAuthenticated:s,isLoading:g,error:l,login:y,logout:c,refreshTokens:h,clearError:d,isExpiringSoon:e,expiresIn:r}=Q(),m=async u=>{if(u.preventDefault(),!o||!a)return;(await y(o,a)).success&&(t(""),i(""),n(!1))},P=async()=>{await c()},C=async()=>{await h()};return s?X(co,{sx:{maxWidth:600,mx:"auto",p:3},children:[R(ro,{variant:"h4",gutterBottom:!0,children:"Welcome! \u{1F389}"}),R(bo,{severity:"success",sx:{mb:3},children:"You are successfully logged in with Refresh Token Pattern enabled"}),X(co,{sx:{mb:3,p:2,bgcolor:"background.paper",border:1,borderColor:"divider",borderRadius:1},children:[R(ro,{variant:"h6",gutterBottom:!0,children:"Token Status"}),X(ro,{variant:"body2",color:"text.secondary",children:["Access Token expires in: ",Math.round(r/1e3/60)," minutes"]}),e&&R(bo,{severity:"warning",sx:{mt:1},children:"Token expires soon - automatic refresh will happen"})]}),X(co,{sx:{display:"flex",gap:2,flexWrap:"wrap"},children:[R(Ao,{variant:"contained",onClick:C,disabled:g,startIcon:g?R(Go,{size:16}):null,children:"Refresh Tokens"}),R(Ao,{variant:"outlined",color:"error",onClick:P,disabled:g,children:"Logout"})]}),l&&R(bo,{severity:"error",sx:{mt:2},onClose:d,children:l})]}):X(co,{sx:{maxWidth:400,mx:"auto",p:3},children:[R(ro,{variant:"h4",gutterBottom:!0,align:"center",children:"Login with Refresh Tokens"}),R(bo,{severity:"info",sx:{mb:3},children:"This demo shows the new Refresh Token Pattern with automatic session management"}),f?X("form",{onSubmit:m,children:[R(De,{fullWidth:!0,label:"Email",type:"email",value:o,onChange:u=>t(u.target.value),margin:"normal",required:!0,autoComplete:"email"}),R(De,{fullWidth:!0,label:"Password",type:"password",value:a,onChange:u=>i(u.target.value),margin:"normal",required:!0,autoComplete:"current-password"}),R(Ao,{type:"submit",fullWidth:!0,variant:"contained",size:"large",disabled:g,startIcon:g?R(Go,{size:16}):null,sx:{mt:3,mb:2},children:g?"Logging in...":"Login"})]}):R(Ao,{fullWidth:!0,variant:"contained",size:"large",onClick:()=>n(!0),sx:{mt:2},children:"Show Login Form"}),l&&R(bo,{severity:"error",sx:{mt:2},onClose:d,children:l})]})}function ws(){let{isAuthenticated:o,isLoading:t,isExpiringSoon:a,expiresIn:i}=Q();return t?X(co,{sx:{display:"flex",alignItems:"center",gap:1},children:[R(Go,{size:16}),R(ro,{variant:"caption",children:"Loading session..."})]}):o?X(co,{children:[R(ro,{variant:"caption",color:"success.main",children:"\u2713 Authenticated"}),a&&X(ro,{variant:"caption",color:"warning.main",display:"block",children:["\u26A0 Token expires in ",Math.round(i/1e3/60)," min"]})]}):R(ro,{variant:"caption",color:"text.secondary",children:"Not logged in"})}export{Ln as a,Mr as b,ke as c,Le as d,us as e,bs as f,ws as g};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{h as $,j as D}from"./chunk-P2PNKHPV.mjs";import{useState as K,useEffect as z,useCallback as j,useRef as F}from"react";import Q from"@nocios/crudify-browser";var G=(S={})=>{let{autoFetch:c=!0,retryOnError:N=!1,maxRetries:g=3}=S,{isAuthenticated:T,isInitialized:I,sessionData:a,tokens:R}=D(),[E,d]=K(null),[y,O]=K(!1),[A,p]=K(null),u=F(null),o=F(!0),m=F(0),l=F(0),L=j(()=>a&&(a.email||a["cognito:username"])||null,[a]),P=j(()=>{d(null),p(null),O(!1),l.current=0},[]),w=j(async()=>{let x=L();if(!x){o.current&&(p("No user email available from session data"),O(!1));return}if(!I){o.current&&(p("Session not initialized"),O(!1));return}u.current&&u.current.abort();let e=new AbortController;u.current=e;let i=++m.current;try{o.current&&(O(!0),p(null));let r=await Q.readItems("users",{filter:{email:x},pagination:{limit:1}});if(i===m.current&&o.current&&!e.signal.aborted){let t=null;if(r.success){if(Array.isArray(r.data)&&r.data.length>0)t=r.data[0];else if(r.data?.response?.data)try{let s=r.data.response.data,n=typeof s=="string"?JSON.parse(s):s;n&&n.items&&Array.isArray(n.items)&&n.items.length>0&&(t=n.items[0])}catch{}else if(r.data&&typeof r.data=="object")r.data.items&&Array.isArray(r.data.items)&&r.data.items.length>0&&(t=r.data.items[0]);else if(r.data?.data?.response?.data)try{let s=r.data.data.response.data,n=typeof s=="string"?JSON.parse(s):s;n&&n.items&&Array.isArray(n.items)&&n.items.length>0&&(t=n.items[0])}catch{}}t?(d(t),p(null),l.current=0):(p("User profile not found in database"),d(null))}}catch(r){if(i===m.current&&o.current){let t=r;if(t.name==="AbortError")return;N&&l.current<g&&(t.message?.includes("Network Error")||t.message?.includes("Failed to fetch"))?(l.current++,setTimeout(()=>{o.current&&w()},1e3*l.current)):(p("Failed to load user profile from database"),d(null))}}finally{i===m.current&&o.current&&O(!1),u.current===e&&(u.current=null)}},[I,L,N,g]);return z(()=>{c&&T&&I?w():T||P()},[c,T,I,w,P]),z(()=>(o.current=!0,()=>{o.current=!1,u.current&&(u.current.abort(),u.current=null)}),[]),{user:{session:a,data:E},loading:y,error:A,refreshProfile:w,clearProfile:P}};import{useCallback as W}from"react";var ee=()=>{let{isAuthenticated:S,isLoading:c,isInitialized:N,tokens:g,error:T,sessionData:I,login:a,logout:R,refreshTokens:E,clearError:d,getTokenInfo:y,isExpiringSoon:O,expiresIn:A,refreshExpiresIn:p}=D(),u=W(m=>{m?console.warn("useAuth.setToken() is deprecated. Use login() method instead for better security."):R()},[R]),o=g?.expiresAt?new Date(g.expiresAt):null;return{isAuthenticated:S,loading:c,error:T,token:g?.accessToken||null,user:I,tokenExpiration:o,setToken:u,logout:R,refreshToken:E,login:a,isExpiringSoon:O,expiresIn:A,refreshExpiresIn:p,getTokenInfo:y,clearError:d}};import{useCallback as h}from"react";import U from"@nocios/crudify-browser";var oe=()=>{let{isInitialized:S,isLoading:c,error:N,isAuthenticated:g,login:T}=D(),I=h(()=>S&&!c&&!N,[S,c,N]),a=h(async()=>new Promise((o,m)=>{let l=()=>{I()?o():N?m(new Error(N)):setTimeout(l,100)};l()}),[I,N]),R=h(async()=>{if(!I())throw new Error("System not ready. Check isInitialized, isLoading, and error states.")},[I]),E=h(async(o,m,l)=>(await R(),await U.readItems(o,m||{},l)),[R]),d=h(async(o,m,l)=>(await R(),await U.readItem(o,m,l)),[R]),y=h(async(o,m,l)=>(await R(),await U.createItem(o,m,l)),[R]),O=h(async(o,m,l)=>(await R(),await U.updateItem(o,m,l)),[R]),A=h(async(o,m,l)=>(await R(),await U.deleteItem(o,m,l)),[R]),p=h(async(o,m)=>(await R(),await U.transaction(o,m)),[R]),u=h(async(o,m)=>{try{let l=await T(o,m);return l.success?{success:!0,data:l.tokens}:{success:!1,errors:l.error||"Login failed"}}catch(l){return{success:!1,errors:l instanceof Error?l.message:"Login failed"}}},[T]);return{readItems:E,readItem:d,createItem:y,updateItem:O,deleteItem:A,transaction:p,login:u,isInitialized:S,isInitializing:c,initializationError:N,isReady:I,waitForReady:a}};import{useCallback as C}from"react";import b from"@nocios/crudify-browser";var Y={INVALID_CREDENTIALS:"warning",UNAUTHORIZED:"warning",INVALID_API_KEY:"error",USER_NOT_FOUND:"warning",USER_NOT_ACTIVE:"warning",NO_PERMISSION:"warning",ITEM_NOT_FOUND:"info",NOT_FOUND:"info",IN_USE:"warning",FIELD_ERROR:"warning",BAD_REQUEST:"warning",INTERNAL_SERVER_ERROR:"error",DATABASE_CONNECTION_ERROR:"error",INVALID_CONFIGURATION:"error",UNKNOWN_OPERATION:"error",TOO_MANY_REQUESTS:"warning"},v={INVALID_CREDENTIALS:"errors.auth.INVALID_CREDENTIALS",UNAUTHORIZED:"errors.auth.UNAUTHORIZED",INVALID_API_KEY:"errors.auth.INVALID_API_KEY",USER_NOT_FOUND:"errors.auth.USER_NOT_FOUND",USER_NOT_ACTIVE:"errors.auth.USER_NOT_ACTIVE",NO_PERMISSION:"errors.auth.NO_PERMISSION",ITEM_NOT_FOUND:"errors.data.ITEM_NOT_FOUND",NOT_FOUND:"errors.data.NOT_FOUND",IN_USE:"errors.data.IN_USE",FIELD_ERROR:"errors.data.FIELD_ERROR",BAD_REQUEST:"errors.data.BAD_REQUEST",INTERNAL_SERVER_ERROR:"errors.system.INTERNAL_SERVER_ERROR",DATABASE_CONNECTION_ERROR:"errors.system.DATABASE_CONNECTION_ERROR",INVALID_CONFIGURATION:"errors.system.INVALID_CONFIGURATION",UNKNOWN_OPERATION:"errors.system.UNKNOWN_OPERATION",TOO_MANY_REQUESTS:"errors.system.TOO_MANY_REQUESTS"},le=(S={})=>{let{showNotification:c}=$(),{showSuccessNotifications:N=!1,showErrorNotifications:g=!0,customErrorMessages:T={},defaultErrorMessage:I="Ha ocurrido un error inesperado",autoHideDuration:a=6e3,appStructure:R=[],translateFn:E=e=>e}=S,d=C(e=>!(!e.success&&e.errors&&(Object.keys(e.errors).some(r=>r!=="_error"&&r!=="_graphql"&&r!=="_transaction")||e.errors._transaction?.includes("ONE_OR_MORE_OPERATIONS_FAILED")||e.errors._error?.includes("TOO_MANY_REQUESTS"))||!e.success&&e.data?.response?.status==="TOO_MANY_REQUESTS"),[]),y=C((e,i)=>{let r=E(e);return r===e?i||E("error.unknown"):r},[E]),O=C(e=>["create","update","delete"].includes(e),[]),A=C((e,i)=>N?O(e)&&i?!0:R.some(r=>r.key===e):!1,[N,R,O]),p=C((e,i,r)=>{let t=r?.key&&typeof r.key=="string"?r.key:e,s=`action.onSuccess.${t}`,n=y(s);if(n!==E("error.unknown")){if(O(t)&&i){let f=`action.${i}Singular`,_=y(f);if(_!==E("error.unknown"))return E(s,{item:_});{let M=`action.onSuccess.${t}WithoutItem`,k=y(M);return k!==E("error.unknown")?k:n}}return n}return E("success.transaction")},[y,E,O]),u=C(e=>{if(e.errorCode&&T[e.errorCode])return T[e.errorCode];if(e.errorCode&&v[e.errorCode])return y(v[e.errorCode]);if(e.errorCode){let i=[`errors.auth.${e.errorCode}`,`errors.data.${e.errorCode}`,`errors.system.${e.errorCode}`,`errors.${e.errorCode}`];for(let r of i){let t=y(r);if(t!==E("error.unknown"))return t}}if(typeof e.data=="string"&&e.data.startsWith("errors.")){let i=y(e.data);if(i!==E("error.unknown"))return i}if(e.errors&&Object.keys(e.errors).length>0){let i=Object.keys(e.errors);if(i.length===1&&i[0]==="_transaction"){let r=e.errors._transaction;if(r?.includes("ONE_OR_MORE_OPERATIONS_FAILED"))return"";if(Array.isArray(r)&&r.length>0){let t=r[0];if(typeof t=="string"&&t!=="ONE_OR_MORE_OPERATIONS_FAILED")try{let s=JSON.parse(t);if(Array.isArray(s)&&s.length>0){let n=s[0];if(n?.response?.errorCode){let f=n.response.errorCode;if(v[f])return y(v[f]);let _=[`errors.auth.${f}`,`errors.data.${f}`,`errors.system.${f}`,`errors.${f}`];for(let M of _){let k=y(M);if(k!==y("error.unknown"))return k}}if(n?.response?.data)return n.response.data}if(s?.response?.message){let n=s.response.message.toLowerCase();return n.includes("expired")?y("resetPassword.linkExpired","El enlace ha expirado"):n.includes("invalid")?y("resetPassword.invalidCode","C\xF3digo inv\xE1lido"):s.response.message}}catch{return t.toLowerCase().includes("expired")?y("resetPassword.linkExpired","El enlace ha expirado"):t.toLowerCase().includes("invalid")?y("resetPassword.invalidCode","C\xF3digo inv\xE1lido"):t}}return y("error.transaction","Error en la operaci\xF3n")}if(i.length===1&&i[0]==="_error"){let r=e.errors._error;return Array.isArray(r)?r[0]:String(r)}return i.length===1&&i[0]==="_graphql"?y("errors.system.DATABASE_CONNECTION_ERROR"):`${y("errors.data.FIELD_ERROR")}: ${i.join(", ")}`}return I||E("error.unknown")},[T,I,E,y]),o=C(e=>e.errorCode&&Y[e.errorCode]?Y[e.errorCode]:"error",[]),m=C(async(e,i,r)=>{let t=await b.createItem(e,i,r);if(!t.success&&g&&d(t)){let s=u(t),n=o(t);c(s,n,{autoHideDuration:a})}else if(t.success){let s=r?.actionConfig,n=s?.key||"create",f=s?.moduleKey||e;if(A(n,f)){let _=p(n,f,s);c(_,"success",{autoHideDuration:a})}}return t},[g,A,c,u,o,p,a,d]),l=C(async(e,i,r)=>{let t=await b.updateItem(e,i,r);if(!t.success&&g&&d(t)){let s=u(t),n=o(t);c(s,n,{autoHideDuration:a})}else if(t.success){let s=r?.actionConfig,n=s?.key||"update",f=s?.moduleKey||e;if(A(n,f)){let _=p(n,f,s);c(_,"success",{autoHideDuration:a})}}return t},[g,A,c,u,o,p,a,d]),L=C(async(e,i,r)=>{let t=await b.deleteItem(e,i,r);if(!t.success&&g&&d(t)){let s=u(t),n=o(t);c(s,n,{autoHideDuration:a})}else if(t.success){let s=r?.actionConfig,n=s?.key||"delete",f=s?.moduleKey||e;if(A(n,f)){let _=p(n,f,s);c(_,"success",{autoHideDuration:a})}}return t},[g,A,c,u,o,p,a,d]),P=C(async(e,i,r)=>{let t=await b.readItem(e,i,r);if(!t.success&&g&&d(t)){let s=u(t),n=o(t);c(s,n,{autoHideDuration:a})}return t},[g,c,u,o,a,d]),w=C(async(e,i,r)=>{let t=await b.readItems(e,i,r);if(!t.success&&g&&d(t)){let s=u(t),n=o(t);c(s,n,{autoHideDuration:a})}return t},[g,c,u,o,a,d]),V=C(async(e,i)=>{let r=await b.transaction(e,i),t=i?.skipNotifications===!0;if(!t&&!r.success&&g&&d(r)){let s=u(r),n=o(r);c(s,n,{autoHideDuration:a})}else if(!t&&r.success){let s="transaction",n,f=null;if(i?.actionConfig?(f=i.actionConfig,s=f.key,n=f.moduleKey):Array.isArray(e)&&e.length>0&&e[0].operation&&(s=e[0].operation,f=R.find(_=>_.key===s),f&&(n=f.moduleKey)),A(s,n)){let _=p(s,n,f);c(_,"success",{autoHideDuration:a})}}return r},[g,A,c,u,o,p,a,d,R]),x=C((e,i)=>{if(!e.success&&g&&d(e)){let r=u(e),t=o(e);c(r,t,{autoHideDuration:a})}else e.success&&N&&i&&c(i,"success",{autoHideDuration:a});return e},[g,N,c,u,o,a,d,E]);return{createItem:m,updateItem:l,deleteItem:L,readItem:P,readItems:w,transaction:V,handleResponse:x,getErrorMessage:u,getErrorSeverity:o,shouldShowNotification:d}};export{G as a,ee as b,oe as c,le as d};
|
|
1
|
+
import{h as $,j as D}from"./chunk-52QAU7WN.mjs";import{useState as K,useEffect as z,useCallback as j,useRef as F}from"react";import Q from"@nocios/crudify-browser";var G=(S={})=>{let{autoFetch:c=!0,retryOnError:N=!1,maxRetries:g=3}=S,{isAuthenticated:T,isInitialized:I,sessionData:a,tokens:R}=D(),[E,d]=K(null),[y,O]=K(!1),[A,p]=K(null),u=F(null),o=F(!0),m=F(0),l=F(0),L=j(()=>a&&(a.email||a["cognito:username"])||null,[a]),P=j(()=>{d(null),p(null),O(!1),l.current=0},[]),w=j(async()=>{let x=L();if(!x){o.current&&(p("No user email available from session data"),O(!1));return}if(!I){o.current&&(p("Session not initialized"),O(!1));return}u.current&&u.current.abort();let e=new AbortController;u.current=e;let i=++m.current;try{o.current&&(O(!0),p(null));let r=await Q.readItems("users",{filter:{email:x},pagination:{limit:1}});if(i===m.current&&o.current&&!e.signal.aborted){let t=null;if(r.success){if(Array.isArray(r.data)&&r.data.length>0)t=r.data[0];else if(r.data?.response?.data)try{let s=r.data.response.data,n=typeof s=="string"?JSON.parse(s):s;n&&n.items&&Array.isArray(n.items)&&n.items.length>0&&(t=n.items[0])}catch{}else if(r.data&&typeof r.data=="object")r.data.items&&Array.isArray(r.data.items)&&r.data.items.length>0&&(t=r.data.items[0]);else if(r.data?.data?.response?.data)try{let s=r.data.data.response.data,n=typeof s=="string"?JSON.parse(s):s;n&&n.items&&Array.isArray(n.items)&&n.items.length>0&&(t=n.items[0])}catch{}}t?(d(t),p(null),l.current=0):(p("User profile not found in database"),d(null))}}catch(r){if(i===m.current&&o.current){let t=r;if(t.name==="AbortError")return;N&&l.current<g&&(t.message?.includes("Network Error")||t.message?.includes("Failed to fetch"))?(l.current++,setTimeout(()=>{o.current&&w()},1e3*l.current)):(p("Failed to load user profile from database"),d(null))}}finally{i===m.current&&o.current&&O(!1),u.current===e&&(u.current=null)}},[I,L,N,g]);return z(()=>{c&&T&&I?w():T||P()},[c,T,I,w,P]),z(()=>(o.current=!0,()=>{o.current=!1,u.current&&(u.current.abort(),u.current=null)}),[]),{user:{session:a,data:E},loading:y,error:A,refreshProfile:w,clearProfile:P}};import{useCallback as W}from"react";var ee=()=>{let{isAuthenticated:S,isLoading:c,isInitialized:N,tokens:g,error:T,sessionData:I,login:a,logout:R,refreshTokens:E,clearError:d,getTokenInfo:y,isExpiringSoon:O,expiresIn:A,refreshExpiresIn:p}=D(),u=W(m=>{m?console.warn("useAuth.setToken() is deprecated. Use login() method instead for better security."):R()},[R]),o=g?.expiresAt?new Date(g.expiresAt):null;return{isAuthenticated:S,loading:c,error:T,token:g?.accessToken||null,user:I,tokenExpiration:o,setToken:u,logout:R,refreshToken:E,login:a,isExpiringSoon:O,expiresIn:A,refreshExpiresIn:p,getTokenInfo:y,clearError:d}};import{useCallback as h}from"react";import U from"@nocios/crudify-browser";var oe=()=>{let{isInitialized:S,isLoading:c,error:N,isAuthenticated:g,login:T}=D(),I=h(()=>S&&!c&&!N,[S,c,N]),a=h(async()=>new Promise((o,m)=>{let l=()=>{I()?o():N?m(new Error(N)):setTimeout(l,100)};l()}),[I,N]),R=h(async()=>{if(!I())throw new Error("System not ready. Check isInitialized, isLoading, and error states.")},[I]),E=h(async(o,m,l)=>(await R(),await U.readItems(o,m||{},l)),[R]),d=h(async(o,m,l)=>(await R(),await U.readItem(o,m,l)),[R]),y=h(async(o,m,l)=>(await R(),await U.createItem(o,m,l)),[R]),O=h(async(o,m,l)=>(await R(),await U.updateItem(o,m,l)),[R]),A=h(async(o,m,l)=>(await R(),await U.deleteItem(o,m,l)),[R]),p=h(async(o,m)=>(await R(),await U.transaction(o,m)),[R]),u=h(async(o,m)=>{try{let l=await T(o,m);return l.success?{success:!0,data:l.tokens}:{success:!1,errors:l.error||"Login failed"}}catch(l){return{success:!1,errors:l instanceof Error?l.message:"Login failed"}}},[T]);return{readItems:E,readItem:d,createItem:y,updateItem:O,deleteItem:A,transaction:p,login:u,isInitialized:S,isInitializing:c,initializationError:N,isReady:I,waitForReady:a}};import{useCallback as C}from"react";import b from"@nocios/crudify-browser";var Y={INVALID_CREDENTIALS:"warning",UNAUTHORIZED:"warning",INVALID_API_KEY:"error",USER_NOT_FOUND:"warning",USER_NOT_ACTIVE:"warning",NO_PERMISSION:"warning",ITEM_NOT_FOUND:"info",NOT_FOUND:"info",IN_USE:"warning",FIELD_ERROR:"warning",BAD_REQUEST:"warning",INTERNAL_SERVER_ERROR:"error",DATABASE_CONNECTION_ERROR:"error",INVALID_CONFIGURATION:"error",UNKNOWN_OPERATION:"error",TOO_MANY_REQUESTS:"warning"},v={INVALID_CREDENTIALS:"errors.auth.INVALID_CREDENTIALS",UNAUTHORIZED:"errors.auth.UNAUTHORIZED",INVALID_API_KEY:"errors.auth.INVALID_API_KEY",USER_NOT_FOUND:"errors.auth.USER_NOT_FOUND",USER_NOT_ACTIVE:"errors.auth.USER_NOT_ACTIVE",NO_PERMISSION:"errors.auth.NO_PERMISSION",ITEM_NOT_FOUND:"errors.data.ITEM_NOT_FOUND",NOT_FOUND:"errors.data.NOT_FOUND",IN_USE:"errors.data.IN_USE",FIELD_ERROR:"errors.data.FIELD_ERROR",BAD_REQUEST:"errors.data.BAD_REQUEST",INTERNAL_SERVER_ERROR:"errors.system.INTERNAL_SERVER_ERROR",DATABASE_CONNECTION_ERROR:"errors.system.DATABASE_CONNECTION_ERROR",INVALID_CONFIGURATION:"errors.system.INVALID_CONFIGURATION",UNKNOWN_OPERATION:"errors.system.UNKNOWN_OPERATION",TOO_MANY_REQUESTS:"errors.system.TOO_MANY_REQUESTS"},le=(S={})=>{let{showNotification:c}=$(),{showSuccessNotifications:N=!1,showErrorNotifications:g=!0,customErrorMessages:T={},defaultErrorMessage:I="Ha ocurrido un error inesperado",autoHideDuration:a=6e3,appStructure:R=[],translateFn:E=e=>e}=S,d=C(e=>!(!e.success&&e.errors&&(Object.keys(e.errors).some(r=>r!=="_error"&&r!=="_graphql"&&r!=="_transaction")||e.errors._transaction?.includes("ONE_OR_MORE_OPERATIONS_FAILED")||e.errors._error?.includes("TOO_MANY_REQUESTS"))||!e.success&&e.data?.response?.status==="TOO_MANY_REQUESTS"),[]),y=C((e,i)=>{let r=E(e);return r===e?i||E("error.unknown"):r},[E]),O=C(e=>["create","update","delete"].includes(e),[]),A=C((e,i)=>N?O(e)&&i?!0:R.some(r=>r.key===e):!1,[N,R,O]),p=C((e,i,r)=>{let t=r?.key&&typeof r.key=="string"?r.key:e,s=`action.onSuccess.${t}`,n=y(s);if(n!==E("error.unknown")){if(O(t)&&i){let f=`action.${i}Singular`,_=y(f);if(_!==E("error.unknown"))return E(s,{item:_});{let M=`action.onSuccess.${t}WithoutItem`,k=y(M);return k!==E("error.unknown")?k:n}}return n}return E("success.transaction")},[y,E,O]),u=C(e=>{if(e.errorCode&&T[e.errorCode])return T[e.errorCode];if(e.errorCode&&v[e.errorCode])return y(v[e.errorCode]);if(e.errorCode){let i=[`errors.auth.${e.errorCode}`,`errors.data.${e.errorCode}`,`errors.system.${e.errorCode}`,`errors.${e.errorCode}`];for(let r of i){let t=y(r);if(t!==E("error.unknown"))return t}}if(typeof e.data=="string"&&e.data.startsWith("errors.")){let i=y(e.data);if(i!==E("error.unknown"))return i}if(e.errors&&Object.keys(e.errors).length>0){let i=Object.keys(e.errors);if(i.length===1&&i[0]==="_transaction"){let r=e.errors._transaction;if(r?.includes("ONE_OR_MORE_OPERATIONS_FAILED"))return"";if(Array.isArray(r)&&r.length>0){let t=r[0];if(typeof t=="string"&&t!=="ONE_OR_MORE_OPERATIONS_FAILED")try{let s=JSON.parse(t);if(Array.isArray(s)&&s.length>0){let n=s[0];if(n?.response?.errorCode){let f=n.response.errorCode;if(v[f])return y(v[f]);let _=[`errors.auth.${f}`,`errors.data.${f}`,`errors.system.${f}`,`errors.${f}`];for(let M of _){let k=y(M);if(k!==y("error.unknown"))return k}}if(n?.response?.data)return n.response.data}if(s?.response?.message){let n=s.response.message.toLowerCase();return n.includes("expired")?y("resetPassword.linkExpired","El enlace ha expirado"):n.includes("invalid")?y("resetPassword.invalidCode","C\xF3digo inv\xE1lido"):s.response.message}}catch{return t.toLowerCase().includes("expired")?y("resetPassword.linkExpired","El enlace ha expirado"):t.toLowerCase().includes("invalid")?y("resetPassword.invalidCode","C\xF3digo inv\xE1lido"):t}}return y("error.transaction","Error en la operaci\xF3n")}if(i.length===1&&i[0]==="_error"){let r=e.errors._error;return Array.isArray(r)?r[0]:String(r)}return i.length===1&&i[0]==="_graphql"?y("errors.system.DATABASE_CONNECTION_ERROR"):`${y("errors.data.FIELD_ERROR")}: ${i.join(", ")}`}return I||E("error.unknown")},[T,I,E,y]),o=C(e=>e.errorCode&&Y[e.errorCode]?Y[e.errorCode]:"error",[]),m=C(async(e,i,r)=>{let t=await b.createItem(e,i,r);if(!t.success&&g&&d(t)){let s=u(t),n=o(t);c(s,n,{autoHideDuration:a})}else if(t.success){let s=r?.actionConfig,n=s?.key||"create",f=s?.moduleKey||e;if(A(n,f)){let _=p(n,f,s);c(_,"success",{autoHideDuration:a})}}return t},[g,A,c,u,o,p,a,d]),l=C(async(e,i,r)=>{let t=await b.updateItem(e,i,r);if(!t.success&&g&&d(t)){let s=u(t),n=o(t);c(s,n,{autoHideDuration:a})}else if(t.success){let s=r?.actionConfig,n=s?.key||"update",f=s?.moduleKey||e;if(A(n,f)){let _=p(n,f,s);c(_,"success",{autoHideDuration:a})}}return t},[g,A,c,u,o,p,a,d]),L=C(async(e,i,r)=>{let t=await b.deleteItem(e,i,r);if(!t.success&&g&&d(t)){let s=u(t),n=o(t);c(s,n,{autoHideDuration:a})}else if(t.success){let s=r?.actionConfig,n=s?.key||"delete",f=s?.moduleKey||e;if(A(n,f)){let _=p(n,f,s);c(_,"success",{autoHideDuration:a})}}return t},[g,A,c,u,o,p,a,d]),P=C(async(e,i,r)=>{let t=await b.readItem(e,i,r);if(!t.success&&g&&d(t)){let s=u(t),n=o(t);c(s,n,{autoHideDuration:a})}return t},[g,c,u,o,a,d]),w=C(async(e,i,r)=>{let t=await b.readItems(e,i,r);if(!t.success&&g&&d(t)){let s=u(t),n=o(t);c(s,n,{autoHideDuration:a})}return t},[g,c,u,o,a,d]),V=C(async(e,i)=>{let r=await b.transaction(e,i),t=i?.skipNotifications===!0;if(!t&&!r.success&&g&&d(r)){let s=u(r),n=o(r);c(s,n,{autoHideDuration:a})}else if(!t&&r.success){let s="transaction",n,f=null;if(i?.actionConfig?(f=i.actionConfig,s=f.key,n=f.moduleKey):Array.isArray(e)&&e.length>0&&e[0].operation&&(s=e[0].operation,f=R.find(_=>_.key===s),f&&(n=f.moduleKey)),A(s,n)){let _=p(s,n,f);c(_,"success",{autoHideDuration:a})}}return r},[g,A,c,u,o,p,a,d,R]),x=C((e,i)=>{if(!e.success&&g&&d(e)){let r=u(e),t=o(e);c(r,t,{autoHideDuration:a})}else e.success&&N&&i&&c(i,"success",{autoHideDuration:a});return e},[g,N,c,u,o,a,d,E]);return{createItem:m,updateItem:l,deleteItem:L,readItem:P,readItems:w,transaction:V,handleResponse:x,getErrorMessage:u,getErrorSeverity:o,shouldShowNotification:d}};export{G as a,ee as b,oe as c,le as d};
|
package/dist/components.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports, "__esModule", {value: true});var
|
|
1
|
+
"use strict";Object.defineProperty(exports, "__esModule", {value: true});var _chunkIK6A7RQJjs = require('./chunk-IK6A7RQJ.js');var _chunkHWFUFWVTjs = require('./chunk-HWFUFWVT.js');require('./chunk-YIIUEOXC.js');require('./chunk-AT74WV5W.js');var _react = require('react');var _jsxruntime = require('react/jsx-runtime');function G({showBelowMinutes:d=5,position:f="bottom-right",colorNormal:m="#ed6c02",colorCritical:x="#d32f2f",style:g,className:u}={}){let{isAuthenticated:o,tokens:t}=_chunkHWFUFWVTjs.f.call(void 0, ),[i,h]=_react.useState.call(void 0, 0),[y,S]=_react.useState.call(void 0, 100);if(_react.useEffect.call(void 0, ()=>{if(!o||!t)return;let P=setInterval(()=>{let C=Date.now(),p=t.expiresAt-C,w=900*1e3;h(Math.max(0,p)),S(Math.max(0,p/w*100))},1e3);return()=>clearInterval(P)},[o,t]),!o||i<=0)return null;let e=Math.floor(i/6e4),b=Math.floor(i%6e4/1e3);if(e>=d)return null;let s=e<2,a=s?x:m,v={"top-left":{top:"16px",left:"16px"},"top-right":{top:"16px",right:"16px"},"bottom-left":{bottom:"16px",left:"16px"},"bottom-right":{bottom:"16px",right:"16px"}}[f];return _jsxruntime.jsxs.call(void 0, "div",{className:u,style:{position:"fixed",...v,padding:"12px 16px",backgroundColor:"white",borderRadius:"8px",boxShadow:"0 4px 12px rgba(0, 0, 0, 0.15)",minWidth:"200px",zIndex:9999,fontFamily:"system-ui, -apple-system, sans-serif",...g},children:[_jsxruntime.jsxs.call(void 0, "div",{style:{marginBottom:"8px"},children:[_jsxruntime.jsx.call(void 0, "div",{style:{fontSize:"12px",fontWeight:600,color:a,marginBottom:"4px"},children:s?"\u26A0\uFE0F Sesi\xF3n expirando":"\u23F0 Sesi\xF3n por expirar"}),_jsxruntime.jsxs.call(void 0, "div",{style:{fontSize:"14px",color:"#333",fontWeight:500},children:[e,":",b.toString().padStart(2,"0")]})]}),_jsxruntime.jsx.call(void 0, "div",{style:{width:"100%",height:"6px",backgroundColor:"#e0e0e0",borderRadius:"3px",overflow:"hidden"},children:_jsxruntime.jsx.call(void 0, "div",{style:{width:`${y}%`,height:"100%",backgroundColor:a,transition:"width 1s linear"}})})]})}exports.CrudifyLogin = _chunkIK6A7RQJjs.a; exports.GlobalNotificationProvider = _chunkHWFUFWVTjs.g; exports.LoginComponent = _chunkIK6A7RQJjs.f; exports.Policies = _chunkIK6A7RQJjs.e; exports.SessionStatus = _chunkIK6A7RQJjs.g; exports.SessionTimeIndicator = G; exports.UserProfileDisplay = _chunkIK6A7RQJjs.b; exports.useGlobalNotification = _chunkHWFUFWVTjs.h;
|
package/dist/components.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as T,b as L,e as M,f as R,g as k}from"./chunk-
|
|
1
|
+
import{a as T,b as L,e as M,f as R,g as k}from"./chunk-TBNNHH4H.mjs";import{f as l,g as I,h as N}from"./chunk-52QAU7WN.mjs";import"./chunk-BJ6PIVZR.mjs";import"./chunk-5JKS55SE.mjs";import{useEffect as B,useState as c}from"react";import{jsx as r,jsxs as n}from"react/jsx-runtime";function G({showBelowMinutes:d=5,position:f="bottom-right",colorNormal:m="#ed6c02",colorCritical:x="#d32f2f",style:g,className:u}={}){let{isAuthenticated:o,tokens:t}=l(),[i,h]=c(0),[y,S]=c(100);if(B(()=>{if(!o||!t)return;let P=setInterval(()=>{let C=Date.now(),p=t.expiresAt-C,w=900*1e3;h(Math.max(0,p)),S(Math.max(0,p/w*100))},1e3);return()=>clearInterval(P)},[o,t]),!o||i<=0)return null;let e=Math.floor(i/6e4),b=Math.floor(i%6e4/1e3);if(e>=d)return null;let s=e<2,a=s?x:m,v={"top-left":{top:"16px",left:"16px"},"top-right":{top:"16px",right:"16px"},"bottom-left":{bottom:"16px",left:"16px"},"bottom-right":{bottom:"16px",right:"16px"}}[f];return n("div",{className:u,style:{position:"fixed",...v,padding:"12px 16px",backgroundColor:"white",borderRadius:"8px",boxShadow:"0 4px 12px rgba(0, 0, 0, 0.15)",minWidth:"200px",zIndex:9999,fontFamily:"system-ui, -apple-system, sans-serif",...g},children:[n("div",{style:{marginBottom:"8px"},children:[r("div",{style:{fontSize:"12px",fontWeight:600,color:a,marginBottom:"4px"},children:s?"\u26A0\uFE0F Sesi\xF3n expirando":"\u23F0 Sesi\xF3n por expirar"}),n("div",{style:{fontSize:"14px",color:"#333",fontWeight:500},children:[e,":",b.toString().padStart(2,"0")]})]}),r("div",{style:{width:"100%",height:"6px",backgroundColor:"#e0e0e0",borderRadius:"3px",overflow:"hidden"},children:r("div",{style:{width:`${y}%`,height:"100%",backgroundColor:a,transition:"width 1s linear"}})})]})}export{T as CrudifyLogin,I as GlobalNotificationProvider,R as LoginComponent,M as Policies,k as SessionStatus,G as SessionTimeIndicator,L as UserProfileDisplay,N as useGlobalNotification};
|
package/dist/hooks.d.mts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export { d as SessionState, j as UseAuthReturn, l as UseDataReturn, U as UseSessionOptions, g as UseUserDataOptions, f as UseUserDataReturn, h as UserData, i as useAuth, n as useCrudifyWithNotifications, k as useData, u as useSession, e as useUserData, m as useUserProfile } from './index-
|
|
1
|
+
export { d as SessionState, j as UseAuthReturn, l as UseDataReturn, U as UseSessionOptions, g as UseUserDataOptions, f as UseUserDataReturn, h as UserData, i as useAuth, n as useCrudifyWithNotifications, k as useData, u as useSession, e as useUserData, m as useUserProfile } from './index-4MK_rZUi.mjs';
|
|
2
2
|
import './api-Djqihi4n.mjs';
|
|
3
3
|
import './GlobalNotificationProvider-C3iWgM1z.mjs';
|
|
4
4
|
import 'react';
|
package/dist/hooks.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export { d as SessionState, j as UseAuthReturn, l as UseDataReturn, U as UseSessionOptions, g as UseUserDataOptions, f as UseUserDataReturn, h as UserData, i as useAuth, n as useCrudifyWithNotifications, k as useData, u as useSession, e as useUserData, m as useUserProfile } from './index-
|
|
1
|
+
export { d as SessionState, j as UseAuthReturn, l as UseDataReturn, U as UseSessionOptions, g as UseUserDataOptions, f as UseUserDataReturn, h as UserData, i as useAuth, n as useCrudifyWithNotifications, k as useData, u as useSession, e as useUserData, m as useUserProfile } from './index-Dpy6dlER.js';
|
|
2
2
|
import './api-Djqihi4n.js';
|
|
3
3
|
import './GlobalNotificationProvider-C3iWgM1z.js';
|
|
4
4
|
import 'react';
|
package/dist/hooks.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports, "__esModule", {value: true});var
|
|
1
|
+
"use strict";Object.defineProperty(exports, "__esModule", {value: true});var _chunk4UBPYCICjs = require('./chunk-4UBPYCIC.js');var _chunkHWFUFWVTjs = require('./chunk-HWFUFWVT.js');require('./chunk-AT74WV5W.js');exports.useAuth = _chunk4UBPYCICjs.b; exports.useCrudifyWithNotifications = _chunk4UBPYCICjs.d; exports.useData = _chunk4UBPYCICjs.c; exports.useSession = _chunkHWFUFWVTjs.f; exports.useUserData = _chunk4UBPYCICjs.a; exports.useUserProfile = _chunkHWFUFWVTjs.l;
|
package/dist/hooks.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as s,b as r,c as o,d as a}from"./chunk-
|
|
1
|
+
import{a as s,b as r,c as o,d as a}from"./chunk-YHZZCCX4.mjs";import{f as e,l as t}from"./chunk-52QAU7WN.mjs";import"./chunk-5JKS55SE.mjs";export{r as useAuth,a as useCrudifyWithNotifications,o as useData,e as useSession,s as useUserData,t as useUserProfile};
|
|
@@ -96,6 +96,8 @@ type SessionConfig = {
|
|
|
96
96
|
translateFn?: (key: string) => string;
|
|
97
97
|
apiEndpointAdmin?: string;
|
|
98
98
|
apiKeyEndpointAdmin?: string;
|
|
99
|
+
publicApiKey?: string;
|
|
100
|
+
env?: "dev" | "stg" | "api" | "prod";
|
|
99
101
|
};
|
|
100
102
|
type LoginResult = {
|
|
101
103
|
success: boolean;
|
|
@@ -108,6 +110,7 @@ declare class SessionManager {
|
|
|
108
110
|
private static instance;
|
|
109
111
|
private config;
|
|
110
112
|
private initialized;
|
|
113
|
+
private crudifyInitialized;
|
|
111
114
|
private lastActivityTime;
|
|
112
115
|
private isRefreshingLocally;
|
|
113
116
|
private refreshPromise;
|
|
@@ -176,6 +179,11 @@ declare class SessionManager {
|
|
|
176
179
|
* El interceptor NO debe hacer await, solo detectar y emitir eventos
|
|
177
180
|
*/
|
|
178
181
|
setupResponseInterceptor(): void;
|
|
182
|
+
/**
|
|
183
|
+
* Ensure crudify SDK is initialized
|
|
184
|
+
* Thread-safe: multiple calls will wait for the same initialization
|
|
185
|
+
*/
|
|
186
|
+
private ensureCrudifyInitialized;
|
|
179
187
|
/**
|
|
180
188
|
* ✅ FASE 3.1: Detectar errores de autorización en todos los formatos posibles (mejorado)
|
|
181
189
|
*/
|
|
@@ -222,6 +230,8 @@ type UseSessionOptions = {
|
|
|
222
230
|
translateFn?: (key: string) => string;
|
|
223
231
|
apiEndpointAdmin?: string;
|
|
224
232
|
apiKeyEndpointAdmin?: string;
|
|
233
|
+
publicApiKey?: string;
|
|
234
|
+
env?: "dev" | "stg" | "api" | "prod";
|
|
225
235
|
};
|
|
226
236
|
declare function useSession(options?: UseSessionOptions): {
|
|
227
237
|
login: (email: string, password: string) => Promise<LoginResult>;
|
|
@@ -96,6 +96,8 @@ type SessionConfig = {
|
|
|
96
96
|
translateFn?: (key: string) => string;
|
|
97
97
|
apiEndpointAdmin?: string;
|
|
98
98
|
apiKeyEndpointAdmin?: string;
|
|
99
|
+
publicApiKey?: string;
|
|
100
|
+
env?: "dev" | "stg" | "api" | "prod";
|
|
99
101
|
};
|
|
100
102
|
type LoginResult = {
|
|
101
103
|
success: boolean;
|
|
@@ -108,6 +110,7 @@ declare class SessionManager {
|
|
|
108
110
|
private static instance;
|
|
109
111
|
private config;
|
|
110
112
|
private initialized;
|
|
113
|
+
private crudifyInitialized;
|
|
111
114
|
private lastActivityTime;
|
|
112
115
|
private isRefreshingLocally;
|
|
113
116
|
private refreshPromise;
|
|
@@ -176,6 +179,11 @@ declare class SessionManager {
|
|
|
176
179
|
* El interceptor NO debe hacer await, solo detectar y emitir eventos
|
|
177
180
|
*/
|
|
178
181
|
setupResponseInterceptor(): void;
|
|
182
|
+
/**
|
|
183
|
+
* Ensure crudify SDK is initialized
|
|
184
|
+
* Thread-safe: multiple calls will wait for the same initialization
|
|
185
|
+
*/
|
|
186
|
+
private ensureCrudifyInitialized;
|
|
179
187
|
/**
|
|
180
188
|
* ✅ FASE 3.1: Detectar errores de autorización en todos los formatos posibles (mejorado)
|
|
181
189
|
*/
|
|
@@ -222,6 +230,8 @@ type UseSessionOptions = {
|
|
|
222
230
|
translateFn?: (key: string) => string;
|
|
223
231
|
apiEndpointAdmin?: string;
|
|
224
232
|
apiKeyEndpointAdmin?: string;
|
|
233
|
+
publicApiKey?: string;
|
|
234
|
+
env?: "dev" | "stg" | "api" | "prod";
|
|
225
235
|
};
|
|
226
236
|
declare function useSession(options?: UseSessionOptions): {
|
|
227
237
|
login: (email: string, password: string) => Promise<LoginResult>;
|