@nocios/crudify-ui 4.4.30 → 4.4.32
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-P4SZ3U4U.mjs → chunk-3OZPBGVW.mjs} +1 -1
- package/dist/{chunk-M2BIAQ3V.js → chunk-5T4X67GW.js} +1 -1
- package/dist/{chunk-ZSP7TBON.mjs → chunk-R4PHVWCE.mjs} +1 -1
- package/dist/{chunk-IZD5WNI4.mjs → chunk-SOGHYUM2.mjs} +1 -1
- package/dist/{chunk-PSZ2DSVH.js → chunk-VHWM5MV6.js} +1 -1
- package/dist/{chunk-MMFYNCPI.js → chunk-WIWNROEA.js} +1 -1
- package/dist/components.js +1 -1
- package/dist/components.mjs +1 -1
- package/dist/hooks.js +1 -1
- package/dist/hooks.mjs +1 -1
- package/dist/index.js +2 -2
- package/dist/index.mjs +1 -1
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
import{h as $,j as D}from"./chunk-ZSP7TBON.mjs";import{useState as K,useEffect as z,useCallback as j,useRef as v}from"react";import Q from"@nocios/crudify-browser";var G=(S={})=>{let{autoFetch:a=!0,retryOnError:N=!1,maxRetries:g=3}=S,{isAuthenticated:T,isInitialized:I,sessionData:c,tokens:R}=D(),[E,d]=K(null),[y,A]=K(a&&T),[_,p]=K(null),u=v(null),o=v(!0),m=v(0),l=v(0),x=j(()=>c&&(c.email||c["cognito:username"])||null,[c]),P=j(()=>{d(null),p(null),A(!1),l.current=0},[]),w=j(async()=>{let F=x();if(!F){o.current&&(p("No user email available from session data"),A(!1));return}if(!I){o.current&&(p("Session not initialized"),A(!1));return}u.current&&u.current.abort();let e=new AbortController;u.current=e;let i=++m.current;try{o.current&&(A(!0),p(null));let r=await Q.readItems("users",{filter:{email:F},pagination:{limit:1}});if(i===m.current&&o.current&&!e.signal.aborted){let t=null;if(r.success){if(Array.isArray(r.data)&&r.data.length>0)t=r.data[0];else if(r.data?.response?.data)try{let n=r.data.response.data,s=typeof n=="string"?JSON.parse(n):n;s&&s.items&&Array.isArray(s.items)&&s.items.length>0&&(t=s.items[0])}catch{}else if(r.data&&typeof r.data=="object")r.data.items&&Array.isArray(r.data.items)&&r.data.items.length>0&&(t=r.data.items[0]);else if(r.data?.data?.response?.data)try{let n=r.data.data.response.data,s=typeof n=="string"?JSON.parse(n):n;s&&s.items&&Array.isArray(s.items)&&s.items.length>0&&(t=s.items[0])}catch{}}t?(d(t),p(null),l.current=0):(p("User profile not found in database"),d(null))}}catch(r){if(i===m.current&&o.current){let t=r;if(t.name==="AbortError")return;N&&l.current<g&&(t.message?.includes("Network Error")||t.message?.includes("Failed to fetch"))?(l.current++,setTimeout(()=>{o.current&&w()},1e3*l.current)):(p("Failed to load user profile from database"),d(null))}}finally{i===m.current&&o.current&&A(!1),u.current===e&&(u.current=null)}},[I,x,N,g]);return z(()=>{a&&T&&I?w():T||P()},[a,T,I,w,P]),z(()=>(o.current=!0,()=>{o.current=!1,u.current&&(u.current.abort(),u.current=null)}),[]),{user:{session:c,data:E},loading:y,error:_,refreshProfile:w,clearProfile:P}};import{useCallback as W}from"react";var ee=()=>{let{isAuthenticated:S,isLoading:a,isInitialized:N,tokens:g,error:T,sessionData:I,login:c,logout:R,refreshTokens:E,clearError:d,getTokenInfo:y,isExpiringSoon:A,expiresIn:_,refreshExpiresIn:p}=D(),u=W(m=>{m?console.warn("useAuth.setToken() is deprecated. Use login() method instead for better security."):R()},[R]),o=g?.expiresAt?new Date(g.expiresAt):null;return{isAuthenticated:S,loading:a,error:T,token:g?.accessToken||null,user:I,tokenExpiration:o,setToken:u,logout:R,refreshToken:E,login:c,isExpiringSoon:A,expiresIn:_,refreshExpiresIn:p,getTokenInfo:y,clearError:d}};import{useCallback as h}from"react";import U from"@nocios/crudify-browser";var oe=()=>{let{isInitialized:S,isLoading:a,error:N,isAuthenticated:g,login:T}=D(),I=h(()=>S&&!a&&!N,[S,a,N]),c=h(async()=>new Promise((o,m)=>{let l=()=>{I()?o():N?m(new Error(N)):setTimeout(l,100)};l()}),[I,N]),R=h(async()=>{if(!I())throw new Error("System not ready. Check isInitialized, isLoading, and error states.")},[I]),E=h(async(o,m,l)=>(await R(),await U.readItems(o,m||{},l)),[R]),d=h(async(o,m,l)=>(await R(),await U.readItem(o,m,l)),[R]),y=h(async(o,m,l)=>(await R(),await U.createItem(o,m,l)),[R]),A=h(async(o,m,l)=>(await R(),await U.updateItem(o,m,l)),[R]),_=h(async(o,m,l)=>(await R(),await U.deleteItem(o,m,l)),[R]),p=h(async(o,m)=>(await R(),await U.transaction(o,m)),[R]),u=h(async(o,m)=>{try{let l=await T(o,m);return l.success?{success:!0,data:l.tokens}:{success:!1,errors:l.error||"Login failed"}}catch(l){return{success:!1,errors:l instanceof Error?l.message:"Login failed"}}},[T]);return{readItems:E,readItem:d,createItem:y,updateItem:A,deleteItem:_,transaction:p,login:u,isInitialized:S,isInitializing:a,initializationError:N,isReady:I,waitForReady:c}};import{useCallback as C}from"react";import b from"@nocios/crudify-browser";var Y={INVALID_CREDENTIALS:"warning",UNAUTHORIZED:"warning",INVALID_API_KEY:"error",USER_NOT_FOUND:"warning",USER_NOT_ACTIVE:"warning",NO_PERMISSION:"warning",ITEM_NOT_FOUND:"info",NOT_FOUND:"info",IN_USE:"warning",FIELD_ERROR:"warning",BAD_REQUEST:"warning",INTERNAL_SERVER_ERROR:"error",DATABASE_CONNECTION_ERROR:"error",INVALID_CONFIGURATION:"error",UNKNOWN_OPERATION:"error",TOO_MANY_REQUESTS:"warning"},M={INVALID_CREDENTIALS:"errors.auth.INVALID_CREDENTIALS",UNAUTHORIZED:"errors.auth.UNAUTHORIZED",INVALID_API_KEY:"errors.auth.INVALID_API_KEY",USER_NOT_FOUND:"errors.auth.USER_NOT_FOUND",USER_NOT_ACTIVE:"errors.auth.USER_NOT_ACTIVE",NO_PERMISSION:"errors.auth.NO_PERMISSION",ITEM_NOT_FOUND:"errors.data.ITEM_NOT_FOUND",NOT_FOUND:"errors.data.NOT_FOUND",IN_USE:"errors.data.IN_USE",FIELD_ERROR:"errors.data.FIELD_ERROR",BAD_REQUEST:"errors.data.BAD_REQUEST",INTERNAL_SERVER_ERROR:"errors.system.INTERNAL_SERVER_ERROR",DATABASE_CONNECTION_ERROR:"errors.system.DATABASE_CONNECTION_ERROR",INVALID_CONFIGURATION:"errors.system.INVALID_CONFIGURATION",UNKNOWN_OPERATION:"errors.system.UNKNOWN_OPERATION",TOO_MANY_REQUESTS:"errors.system.TOO_MANY_REQUESTS"},le=(S={})=>{let{showNotification:a}=$(),{showSuccessNotifications:N=!1,showErrorNotifications:g=!0,customErrorMessages:T={},defaultErrorMessage:I="Ha ocurrido un error inesperado",autoHideDuration:c=6e3,appStructure:R=[],translateFn:E=e=>e}=S,d=C(e=>!(!e.success&&e.errors&&(Object.keys(e.errors).some(r=>r!=="_error"&&r!=="_graphql"&&r!=="_transaction")||e.errors._transaction?.includes("ONE_OR_MORE_OPERATIONS_FAILED")||e.errors._error?.includes("TOO_MANY_REQUESTS"))||!e.success&&e.data?.response?.status==="TOO_MANY_REQUESTS"),[]),y=C((e,i)=>{let r=E(e);return r===e?i||E("error.unknown"):r},[E]),A=C(e=>["create","update","delete"].includes(e),[]),_=C((e,i)=>N?A(e)&&i?!0:R.some(r=>r.key===e):!1,[N,R,A]),p=C((e,i,r)=>{let t=r?.key&&typeof r.key=="string"?r.key:e,n=`action.onSuccess.${t}`,s=y(n);if(s!==E("error.unknown")){if(A(t)&&i){let f=`action.${i}Singular`,O=y(f);if(O!==E("error.unknown"))return E(n,{item:O});{let k=`action.onSuccess.${t}WithoutItem`,L=y(k);return L!==E("error.unknown")?L:s}}return s}return E("success.transaction")},[y,E,A]),u=C(e=>{if(e.errorCode&&T[e.errorCode])return T[e.errorCode];if(e.errorCode&&M[e.errorCode])return y(M[e.errorCode]);if(e.errorCode){let i=[`errors.auth.${e.errorCode}`,`errors.data.${e.errorCode}`,`errors.system.${e.errorCode}`,`errors.${e.errorCode}`];for(let r of i){let t=y(r);if(t!==E("error.unknown"))return t}}if(typeof e.data=="string"&&e.data.startsWith("errors.")){let i=y(e.data);if(i!==E("error.unknown"))return i}if(e.errors&&Object.keys(e.errors).length>0){let i=Object.keys(e.errors);if(i.length===1&&i[0]==="_transaction"){let r=e.errors._transaction;if(r?.includes("ONE_OR_MORE_OPERATIONS_FAILED"))return"";if(Array.isArray(r)&&r.length>0){let t=r[0];if(typeof t=="string"&&t!=="ONE_OR_MORE_OPERATIONS_FAILED")try{let n=JSON.parse(t);if(Array.isArray(n)&&n.length>0){let s=n[0];if(s?.response?.errorCode){let f=s.response.errorCode;if(M[f])return y(M[f]);let O=[`errors.auth.${f}`,`errors.data.${f}`,`errors.system.${f}`,`errors.${f}`];for(let k of O){let L=y(k);if(L!==y("error.unknown"))return L}}if(s?.response?.data)return s.response.data}if(n?.response?.message){let s=n.response.message.toLowerCase();return s.includes("expired")?y("resetPassword.linkExpired","El enlace ha expirado"):s.includes("invalid")?y("resetPassword.invalidCode","C\xF3digo inv\xE1lido"):n.response.message}}catch{return t.toLowerCase().includes("expired")?y("resetPassword.linkExpired","El enlace ha expirado"):t.toLowerCase().includes("invalid")?y("resetPassword.invalidCode","C\xF3digo inv\xE1lido"):t}}return y("error.transaction","Error en la operaci\xF3n")}if(i.length===1&&i[0]==="_error"){let r=e.errors._error;return Array.isArray(r)?r[0]:String(r)}return i.length===1&&i[0]==="_graphql"?y("errors.system.DATABASE_CONNECTION_ERROR"):`${y("errors.data.FIELD_ERROR")}: ${i.join(", ")}`}return I||E("error.unknown")},[T,I,E,y]),o=C(e=>e.errorCode&&Y[e.errorCode]?Y[e.errorCode]:"error",[]),m=C(async(e,i,r)=>{let t=await b.createItem(e,i,r);if(!t.success&&g&&d(t)){let n=u(t),s=o(t);a(n,s,{autoHideDuration:c})}else if(t.success){let n=r?.actionConfig,s=n?.key||"create",f=n?.moduleKey||e;if(_(s,f)){let O=p(s,f,n);a(O,"success",{autoHideDuration:c})}}return t},[g,_,a,u,o,p,c,d]),l=C(async(e,i,r)=>{let t=await b.updateItem(e,i,r),n=r?.skipNotifications===!0;if(!n&&!t.success&&g&&d(t)){let s=u(t),f=o(t);a(s,f,{autoHideDuration:c})}else if(!n&&t.success){let s=r?.actionConfig,f=s?.key||"update",O=s?.moduleKey||e;if(_(f,O)){let k=p(f,O,s);a(k,"success",{autoHideDuration:c})}}return t},[g,_,a,u,o,p,c,d]),x=C(async(e,i,r)=>{let t=await b.deleteItem(e,i,r);if(!t.success&&g&&d(t)){let n=u(t),s=o(t);a(n,s,{autoHideDuration:c})}else if(t.success){let n=r?.actionConfig,s=n?.key||"delete",f=n?.moduleKey||e;if(_(s,f)){let O=p(s,f,n);a(O,"success",{autoHideDuration:c})}}return t},[g,_,a,u,o,p,c,d]),P=C(async(e,i,r)=>{let t=await b.readItem(e,i,r);if(!t.success&&g&&d(t)){let n=u(t),s=o(t);a(n,s,{autoHideDuration:c})}return t},[g,a,u,o,c,d]),w=C(async(e,i,r)=>{let t=await b.readItems(e,i,r);if(!t.success&&g&&d(t)){let n=u(t),s=o(t);a(n,s,{autoHideDuration:c})}return t},[g,a,u,o,c,d]),V=C(async(e,i)=>{let r=await b.transaction(e,i),t=i?.skipNotifications===!0;if(!t&&!r.success&&g&&d(r)){let n=u(r),s=o(r);a(n,s,{autoHideDuration:c})}else if(!t&&r.success){let n="transaction",s,f=null;if(i?.actionConfig?(f=i.actionConfig,n=f.key,s=f.moduleKey):Array.isArray(e)&&e.length>0&&e[0].operation&&(n=e[0].operation,f=R.find(O=>O.key===n),f&&(s=f.moduleKey)),_(n,s)){let O=p(n,s,f);a(O,"success",{autoHideDuration:c})}}return r},[g,_,a,u,o,p,c,d,R]),F=C((e,i)=>{if(!e.success&&g&&d(e)){let r=u(e),t=o(e);a(r,t,{autoHideDuration:c})}else e.success&&N&&i&&a(i,"success",{autoHideDuration:c});return e},[g,N,a,u,o,c,d,E]);return{createItem:m,updateItem:l,deleteItem:x,readItem:P,readItems:w,transaction:V,handleResponse:F,getErrorMessage:u,getErrorSeverity:o,shouldShowNotification:d}};export{G as a,ee as b,oe as c,le as d};
|
|
1
|
+
import{h as $,j as D}from"./chunk-R4PHVWCE.mjs";import{useState as K,useEffect as z,useCallback as j,useRef as v}from"react";import Q from"@nocios/crudify-browser";var G=(S={})=>{let{autoFetch:a=!0,retryOnError:N=!1,maxRetries:g=3}=S,{isAuthenticated:T,isInitialized:I,sessionData:c,tokens:R}=D(),[E,d]=K(null),[y,A]=K(a&&T),[_,p]=K(null),u=v(null),o=v(!0),m=v(0),l=v(0),x=j(()=>c&&(c.email||c["cognito:username"])||null,[c]),P=j(()=>{d(null),p(null),A(!1),l.current=0},[]),w=j(async()=>{let F=x();if(!F){o.current&&(p("No user email available from session data"),A(!1));return}if(!I){o.current&&(p("Session not initialized"),A(!1));return}u.current&&u.current.abort();let e=new AbortController;u.current=e;let i=++m.current;try{o.current&&(A(!0),p(null));let r=await Q.readItems("users",{filter:{email:F},pagination:{limit:1}});if(i===m.current&&o.current&&!e.signal.aborted){let t=null;if(r.success){if(Array.isArray(r.data)&&r.data.length>0)t=r.data[0];else if(r.data?.response?.data)try{let n=r.data.response.data,s=typeof n=="string"?JSON.parse(n):n;s&&s.items&&Array.isArray(s.items)&&s.items.length>0&&(t=s.items[0])}catch{}else if(r.data&&typeof r.data=="object")r.data.items&&Array.isArray(r.data.items)&&r.data.items.length>0&&(t=r.data.items[0]);else if(r.data?.data?.response?.data)try{let n=r.data.data.response.data,s=typeof n=="string"?JSON.parse(n):n;s&&s.items&&Array.isArray(s.items)&&s.items.length>0&&(t=s.items[0])}catch{}}t?(d(t),p(null),l.current=0):(p("User profile not found in database"),d(null))}}catch(r){if(i===m.current&&o.current){let t=r;if(t.name==="AbortError")return;N&&l.current<g&&(t.message?.includes("Network Error")||t.message?.includes("Failed to fetch"))?(l.current++,setTimeout(()=>{o.current&&w()},1e3*l.current)):(p("Failed to load user profile from database"),d(null))}}finally{i===m.current&&o.current&&A(!1),u.current===e&&(u.current=null)}},[I,x,N,g]);return z(()=>{a&&T&&I?w():T||P()},[a,T,I,w,P]),z(()=>(o.current=!0,()=>{o.current=!1,u.current&&(u.current.abort(),u.current=null)}),[]),{user:{session:c,data:E},loading:y,error:_,refreshProfile:w,clearProfile:P}};import{useCallback as W}from"react";var ee=()=>{let{isAuthenticated:S,isLoading:a,isInitialized:N,tokens:g,error:T,sessionData:I,login:c,logout:R,refreshTokens:E,clearError:d,getTokenInfo:y,isExpiringSoon:A,expiresIn:_,refreshExpiresIn:p}=D(),u=W(m=>{m?console.warn("useAuth.setToken() is deprecated. Use login() method instead for better security."):R()},[R]),o=g?.expiresAt?new Date(g.expiresAt):null;return{isAuthenticated:S,loading:a,error:T,token:g?.accessToken||null,user:I,tokenExpiration:o,setToken:u,logout:R,refreshToken:E,login:c,isExpiringSoon:A,expiresIn:_,refreshExpiresIn:p,getTokenInfo:y,clearError:d}};import{useCallback as h}from"react";import U from"@nocios/crudify-browser";var oe=()=>{let{isInitialized:S,isLoading:a,error:N,isAuthenticated:g,login:T}=D(),I=h(()=>S&&!a&&!N,[S,a,N]),c=h(async()=>new Promise((o,m)=>{let l=()=>{I()?o():N?m(new Error(N)):setTimeout(l,100)};l()}),[I,N]),R=h(async()=>{if(!I())throw new Error("System not ready. Check isInitialized, isLoading, and error states.")},[I]),E=h(async(o,m,l)=>(await R(),await U.readItems(o,m||{},l)),[R]),d=h(async(o,m,l)=>(await R(),await U.readItem(o,m,l)),[R]),y=h(async(o,m,l)=>(await R(),await U.createItem(o,m,l)),[R]),A=h(async(o,m,l)=>(await R(),await U.updateItem(o,m,l)),[R]),_=h(async(o,m,l)=>(await R(),await U.deleteItem(o,m,l)),[R]),p=h(async(o,m)=>(await R(),await U.transaction(o,m)),[R]),u=h(async(o,m)=>{try{let l=await T(o,m);return l.success?{success:!0,data:l.tokens}:{success:!1,errors:l.error||"Login failed"}}catch(l){return{success:!1,errors:l instanceof Error?l.message:"Login failed"}}},[T]);return{readItems:E,readItem:d,createItem:y,updateItem:A,deleteItem:_,transaction:p,login:u,isInitialized:S,isInitializing:a,initializationError:N,isReady:I,waitForReady:c}};import{useCallback as C}from"react";import b from"@nocios/crudify-browser";var Y={INVALID_CREDENTIALS:"warning",UNAUTHORIZED:"warning",INVALID_API_KEY:"error",USER_NOT_FOUND:"warning",USER_NOT_ACTIVE:"warning",NO_PERMISSION:"warning",ITEM_NOT_FOUND:"info",NOT_FOUND:"info",IN_USE:"warning",FIELD_ERROR:"warning",BAD_REQUEST:"warning",INTERNAL_SERVER_ERROR:"error",DATABASE_CONNECTION_ERROR:"error",INVALID_CONFIGURATION:"error",UNKNOWN_OPERATION:"error",TOO_MANY_REQUESTS:"warning"},M={INVALID_CREDENTIALS:"errors.auth.INVALID_CREDENTIALS",UNAUTHORIZED:"errors.auth.UNAUTHORIZED",INVALID_API_KEY:"errors.auth.INVALID_API_KEY",USER_NOT_FOUND:"errors.auth.USER_NOT_FOUND",USER_NOT_ACTIVE:"errors.auth.USER_NOT_ACTIVE",NO_PERMISSION:"errors.auth.NO_PERMISSION",ITEM_NOT_FOUND:"errors.data.ITEM_NOT_FOUND",NOT_FOUND:"errors.data.NOT_FOUND",IN_USE:"errors.data.IN_USE",FIELD_ERROR:"errors.data.FIELD_ERROR",BAD_REQUEST:"errors.data.BAD_REQUEST",INTERNAL_SERVER_ERROR:"errors.system.INTERNAL_SERVER_ERROR",DATABASE_CONNECTION_ERROR:"errors.system.DATABASE_CONNECTION_ERROR",INVALID_CONFIGURATION:"errors.system.INVALID_CONFIGURATION",UNKNOWN_OPERATION:"errors.system.UNKNOWN_OPERATION",TOO_MANY_REQUESTS:"errors.system.TOO_MANY_REQUESTS"},le=(S={})=>{let{showNotification:a}=$(),{showSuccessNotifications:N=!1,showErrorNotifications:g=!0,customErrorMessages:T={},defaultErrorMessage:I="Ha ocurrido un error inesperado",autoHideDuration:c=6e3,appStructure:R=[],translateFn:E=e=>e}=S,d=C(e=>!(!e.success&&e.errors&&(Object.keys(e.errors).some(r=>r!=="_error"&&r!=="_graphql"&&r!=="_transaction")||e.errors._transaction?.includes("ONE_OR_MORE_OPERATIONS_FAILED")||e.errors._error?.includes("TOO_MANY_REQUESTS"))||!e.success&&e.data?.response?.status==="TOO_MANY_REQUESTS"),[]),y=C((e,i)=>{let r=E(e);return r===e?i||E("error.unknown"):r},[E]),A=C(e=>["create","update","delete"].includes(e),[]),_=C((e,i)=>N?A(e)&&i?!0:R.some(r=>r.key===e):!1,[N,R,A]),p=C((e,i,r)=>{let t=r?.key&&typeof r.key=="string"?r.key:e,n=`action.onSuccess.${t}`,s=y(n);if(s!==E("error.unknown")){if(A(t)&&i){let f=`action.${i}Singular`,O=y(f);if(O!==E("error.unknown"))return E(n,{item:O});{let k=`action.onSuccess.${t}WithoutItem`,L=y(k);return L!==E("error.unknown")?L:s}}return s}return E("success.transaction")},[y,E,A]),u=C(e=>{if(e.errorCode&&T[e.errorCode])return T[e.errorCode];if(e.errorCode&&M[e.errorCode])return y(M[e.errorCode]);if(e.errorCode){let i=[`errors.auth.${e.errorCode}`,`errors.data.${e.errorCode}`,`errors.system.${e.errorCode}`,`errors.${e.errorCode}`];for(let r of i){let t=y(r);if(t!==E("error.unknown"))return t}}if(typeof e.data=="string"&&e.data.startsWith("errors.")){let i=y(e.data);if(i!==E("error.unknown"))return i}if(e.errors&&Object.keys(e.errors).length>0){let i=Object.keys(e.errors);if(i.length===1&&i[0]==="_transaction"){let r=e.errors._transaction;if(r?.includes("ONE_OR_MORE_OPERATIONS_FAILED"))return"";if(Array.isArray(r)&&r.length>0){let t=r[0];if(typeof t=="string"&&t!=="ONE_OR_MORE_OPERATIONS_FAILED")try{let n=JSON.parse(t);if(Array.isArray(n)&&n.length>0){let s=n[0];if(s?.response?.errorCode){let f=s.response.errorCode;if(M[f])return y(M[f]);let O=[`errors.auth.${f}`,`errors.data.${f}`,`errors.system.${f}`,`errors.${f}`];for(let k of O){let L=y(k);if(L!==y("error.unknown"))return L}}if(s?.response?.data)return s.response.data}if(n?.response?.message){let s=n.response.message.toLowerCase();return s.includes("expired")?y("resetPassword.linkExpired","El enlace ha expirado"):s.includes("invalid")?y("resetPassword.invalidCode","C\xF3digo inv\xE1lido"):n.response.message}}catch{return t.toLowerCase().includes("expired")?y("resetPassword.linkExpired","El enlace ha expirado"):t.toLowerCase().includes("invalid")?y("resetPassword.invalidCode","C\xF3digo inv\xE1lido"):t}}return y("error.transaction","Error en la operaci\xF3n")}if(i.length===1&&i[0]==="_error"){let r=e.errors._error;return Array.isArray(r)?r[0]:String(r)}return i.length===1&&i[0]==="_graphql"?y("errors.system.DATABASE_CONNECTION_ERROR"):`${y("errors.data.FIELD_ERROR")}: ${i.join(", ")}`}return I||E("error.unknown")},[T,I,E,y]),o=C(e=>e.errorCode&&Y[e.errorCode]?Y[e.errorCode]:"error",[]),m=C(async(e,i,r)=>{let t=await b.createItem(e,i,r);if(!t.success&&g&&d(t)){let n=u(t),s=o(t);a(n,s,{autoHideDuration:c})}else if(t.success){let n=r?.actionConfig,s=n?.key||"create",f=n?.moduleKey||e;if(_(s,f)){let O=p(s,f,n);a(O,"success",{autoHideDuration:c})}}return t},[g,_,a,u,o,p,c,d]),l=C(async(e,i,r)=>{let t=await b.updateItem(e,i,r),n=r?.skipNotifications===!0;if(!n&&!t.success&&g&&d(t)){let s=u(t),f=o(t);a(s,f,{autoHideDuration:c})}else if(!n&&t.success){let s=r?.actionConfig,f=s?.key||"update",O=s?.moduleKey||e;if(_(f,O)){let k=p(f,O,s);a(k,"success",{autoHideDuration:c})}}return t},[g,_,a,u,o,p,c,d]),x=C(async(e,i,r)=>{let t=await b.deleteItem(e,i,r);if(!t.success&&g&&d(t)){let n=u(t),s=o(t);a(n,s,{autoHideDuration:c})}else if(t.success){let n=r?.actionConfig,s=n?.key||"delete",f=n?.moduleKey||e;if(_(s,f)){let O=p(s,f,n);a(O,"success",{autoHideDuration:c})}}return t},[g,_,a,u,o,p,c,d]),P=C(async(e,i,r)=>{let t=await b.readItem(e,i,r);if(!t.success&&g&&d(t)){let n=u(t),s=o(t);a(n,s,{autoHideDuration:c})}return t},[g,a,u,o,c,d]),w=C(async(e,i,r)=>{let t=await b.readItems(e,i,r);if(!t.success&&g&&d(t)){let n=u(t),s=o(t);a(n,s,{autoHideDuration:c})}return t},[g,a,u,o,c,d]),V=C(async(e,i)=>{let r=await b.transaction(e,i),t=i?.skipNotifications===!0;if(!t&&!r.success&&g&&d(r)){let n=u(r),s=o(r);a(n,s,{autoHideDuration:c})}else if(!t&&r.success){let n="transaction",s,f=null;if(i?.actionConfig?(f=i.actionConfig,n=f.key,s=f.moduleKey):Array.isArray(e)&&e.length>0&&e[0].operation&&(n=e[0].operation,f=R.find(O=>O.key===n),f&&(s=f.moduleKey)),_(n,s)){let O=p(n,s,f);a(O,"success",{autoHideDuration:c})}}return r},[g,_,a,u,o,p,c,d,R]),F=C((e,i)=>{if(!e.success&&g&&d(e)){let r=u(e),t=o(e);a(r,t,{autoHideDuration:c})}else e.success&&N&&i&&a(i,"success",{autoHideDuration:c});return e},[g,N,a,u,o,c,d,E]);return{createItem:m,updateItem:l,deleteItem:x,readItem:P,readItems:w,transaction:V,handleResponse:F,getErrorMessage:u,getErrorSeverity:o,shouldShowNotification:d}};export{G as a,ee as b,oe as c,le as d};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }var _chunkMMFYNCPIjs = require('./chunk-MMFYNCPI.js');var _react = require('react');var _crudifybrowser = require('@nocios/crudify-browser'); var _crudifybrowser2 = _interopRequireDefault(_crudifybrowser);var G=(S={})=>{let{autoFetch:a=!0,retryOnError:N=!1,maxRetries:g=3}=S,{isAuthenticated:T,isInitialized:I,sessionData:c,tokens:R}=_chunkMMFYNCPIjs.j.call(void 0, ),[E,d]=_react.useState.call(void 0, null),[y,A]=_react.useState.call(void 0, a&&T),[_,p]=_react.useState.call(void 0, null),u=_react.useRef.call(void 0, null),o=_react.useRef.call(void 0, !0),m=_react.useRef.call(void 0, 0),l=_react.useRef.call(void 0, 0),x=_react.useCallback.call(void 0, ()=>c&&(c.email||c["cognito:username"])||null,[c]),P=_react.useCallback.call(void 0, ()=>{d(null),p(null),A(!1),l.current=0},[]),w=_react.useCallback.call(void 0, async()=>{let F=x();if(!F){o.current&&(p("No user email available from session data"),A(!1));return}if(!I){o.current&&(p("Session not initialized"),A(!1));return}u.current&&u.current.abort();let e=new AbortController;u.current=e;let i=++m.current;try{o.current&&(A(!0),p(null));let r=await _crudifybrowser2.default.readItems("users",{filter:{email:F},pagination:{limit:1}});if(i===m.current&&o.current&&!e.signal.aborted){let t=null;if(r.success){if(Array.isArray(r.data)&&r.data.length>0)t=r.data[0];else if(_optionalChain([r, 'access', _2 => _2.data, 'optionalAccess', _3 => _3.response, 'optionalAccess', _4 => _4.data]))try{let n=r.data.response.data,s=typeof n=="string"?JSON.parse(n):n;s&&s.items&&Array.isArray(s.items)&&s.items.length>0&&(t=s.items[0])}catch (e2){}else if(r.data&&typeof r.data=="object")r.data.items&&Array.isArray(r.data.items)&&r.data.items.length>0&&(t=r.data.items[0]);else if(_optionalChain([r, 'access', _5 => _5.data, 'optionalAccess', _6 => _6.data, 'optionalAccess', _7 => _7.response, 'optionalAccess', _8 => _8.data]))try{let n=r.data.data.response.data,s=typeof n=="string"?JSON.parse(n):n;s&&s.items&&Array.isArray(s.items)&&s.items.length>0&&(t=s.items[0])}catch (e3){}}t?(d(t),p(null),l.current=0):(p("User profile not found in database"),d(null))}}catch(r){if(i===m.current&&o.current){let t=r;if(t.name==="AbortError")return;N&&l.current<g&&(_optionalChain([t, 'access', _9 => _9.message, 'optionalAccess', _10 => _10.includes, 'call', _11 => _11("Network Error")])||_optionalChain([t, 'access', _12 => _12.message, 'optionalAccess', _13 => _13.includes, 'call', _14 => _14("Failed to fetch")]))?(l.current++,setTimeout(()=>{o.current&&w()},1e3*l.current)):(p("Failed to load user profile from database"),d(null))}}finally{i===m.current&&o.current&&A(!1),u.current===e&&(u.current=null)}},[I,x,N,g]);return _react.useEffect.call(void 0, ()=>{a&&T&&I?w():T||P()},[a,T,I,w,P]),_react.useEffect.call(void 0, ()=>(o.current=!0,()=>{o.current=!1,u.current&&(u.current.abort(),u.current=null)}),[]),{user:{session:c,data:E},loading:y,error:_,refreshProfile:w,clearProfile:P}};var ee=()=>{let{isAuthenticated:S,isLoading:a,isInitialized:N,tokens:g,error:T,sessionData:I,login:c,logout:R,refreshTokens:E,clearError:d,getTokenInfo:y,isExpiringSoon:A,expiresIn:_,refreshExpiresIn:p}=_chunkMMFYNCPIjs.j.call(void 0, ),u=_react.useCallback.call(void 0, m=>{m?console.warn("useAuth.setToken() is deprecated. Use login() method instead for better security."):R()},[R]),o=_optionalChain([g, 'optionalAccess', _15 => _15.expiresAt])?new Date(g.expiresAt):null;return{isAuthenticated:S,loading:a,error:T,token:_optionalChain([g, 'optionalAccess', _16 => _16.accessToken])||null,user:I,tokenExpiration:o,setToken:u,logout:R,refreshToken:E,login:c,isExpiringSoon:A,expiresIn:_,refreshExpiresIn:p,getTokenInfo:y,clearError:d}};var oe=()=>{let{isInitialized:S,isLoading:a,error:N,isAuthenticated:g,login:T}=_chunkMMFYNCPIjs.j.call(void 0, ),I=_react.useCallback.call(void 0, ()=>S&&!a&&!N,[S,a,N]),c=_react.useCallback.call(void 0, async()=>new Promise((o,m)=>{let l=()=>{I()?o():N?m(new Error(N)):setTimeout(l,100)};l()}),[I,N]),R=_react.useCallback.call(void 0, async()=>{if(!I())throw new Error("System not ready. Check isInitialized, isLoading, and error states.")},[I]),E=_react.useCallback.call(void 0, async(o,m,l)=>(await R(),await _crudifybrowser2.default.readItems(o,m||{},l)),[R]),d=_react.useCallback.call(void 0, async(o,m,l)=>(await R(),await _crudifybrowser2.default.readItem(o,m,l)),[R]),y=_react.useCallback.call(void 0, async(o,m,l)=>(await R(),await _crudifybrowser2.default.createItem(o,m,l)),[R]),A=_react.useCallback.call(void 0, async(o,m,l)=>(await R(),await _crudifybrowser2.default.updateItem(o,m,l)),[R]),_=_react.useCallback.call(void 0, async(o,m,l)=>(await R(),await _crudifybrowser2.default.deleteItem(o,m,l)),[R]),p=_react.useCallback.call(void 0, async(o,m)=>(await R(),await _crudifybrowser2.default.transaction(o,m)),[R]),u=_react.useCallback.call(void 0, async(o,m)=>{try{let l=await T(o,m);return l.success?{success:!0,data:l.tokens}:{success:!1,errors:l.error||"Login failed"}}catch(l){return{success:!1,errors:l instanceof Error?l.message:"Login failed"}}},[T]);return{readItems:E,readItem:d,createItem:y,updateItem:A,deleteItem:_,transaction:p,login:u,isInitialized:S,isInitializing:a,initializationError:N,isReady:I,waitForReady:c}};var Y={INVALID_CREDENTIALS:"warning",UNAUTHORIZED:"warning",INVALID_API_KEY:"error",USER_NOT_FOUND:"warning",USER_NOT_ACTIVE:"warning",NO_PERMISSION:"warning",ITEM_NOT_FOUND:"info",NOT_FOUND:"info",IN_USE:"warning",FIELD_ERROR:"warning",BAD_REQUEST:"warning",INTERNAL_SERVER_ERROR:"error",DATABASE_CONNECTION_ERROR:"error",INVALID_CONFIGURATION:"error",UNKNOWN_OPERATION:"error",TOO_MANY_REQUESTS:"warning"},M={INVALID_CREDENTIALS:"errors.auth.INVALID_CREDENTIALS",UNAUTHORIZED:"errors.auth.UNAUTHORIZED",INVALID_API_KEY:"errors.auth.INVALID_API_KEY",USER_NOT_FOUND:"errors.auth.USER_NOT_FOUND",USER_NOT_ACTIVE:"errors.auth.USER_NOT_ACTIVE",NO_PERMISSION:"errors.auth.NO_PERMISSION",ITEM_NOT_FOUND:"errors.data.ITEM_NOT_FOUND",NOT_FOUND:"errors.data.NOT_FOUND",IN_USE:"errors.data.IN_USE",FIELD_ERROR:"errors.data.FIELD_ERROR",BAD_REQUEST:"errors.data.BAD_REQUEST",INTERNAL_SERVER_ERROR:"errors.system.INTERNAL_SERVER_ERROR",DATABASE_CONNECTION_ERROR:"errors.system.DATABASE_CONNECTION_ERROR",INVALID_CONFIGURATION:"errors.system.INVALID_CONFIGURATION",UNKNOWN_OPERATION:"errors.system.UNKNOWN_OPERATION",TOO_MANY_REQUESTS:"errors.system.TOO_MANY_REQUESTS"},le= exports.d =(S={})=>{let{showNotification:a}=_chunkMMFYNCPIjs.h.call(void 0, ),{showSuccessNotifications:N=!1,showErrorNotifications:g=!0,customErrorMessages:T={},defaultErrorMessage:I="Ha ocurrido un error inesperado",autoHideDuration:c=6e3,appStructure:R=[],translateFn:E=e=>e}=S,d=_react.useCallback.call(void 0, e=>!(!e.success&&e.errors&&(Object.keys(e.errors).some(r=>r!=="_error"&&r!=="_graphql"&&r!=="_transaction")||_optionalChain([e, 'access', _17 => _17.errors, 'access', _18 => _18._transaction, 'optionalAccess', _19 => _19.includes, 'call', _20 => _20("ONE_OR_MORE_OPERATIONS_FAILED")])||_optionalChain([e, 'access', _21 => _21.errors, 'access', _22 => _22._error, 'optionalAccess', _23 => _23.includes, 'call', _24 => _24("TOO_MANY_REQUESTS")]))||!e.success&&_optionalChain([e, 'access', _25 => _25.data, 'optionalAccess', _26 => _26.response, 'optionalAccess', _27 => _27.status])==="TOO_MANY_REQUESTS"),[]),y=_react.useCallback.call(void 0, (e,i)=>{let r=E(e);return r===e?i||E("error.unknown"):r},[E]),A=_react.useCallback.call(void 0, e=>["create","update","delete"].includes(e),[]),_=_react.useCallback.call(void 0, (e,i)=>N?A(e)&&i?!0:R.some(r=>r.key===e):!1,[N,R,A]),p=_react.useCallback.call(void 0, (e,i,r)=>{let t=_optionalChain([r, 'optionalAccess', _28 => _28.key])&&typeof r.key=="string"?r.key:e,n=`action.onSuccess.${t}`,s=y(n);if(s!==E("error.unknown")){if(A(t)&&i){let f=`action.${i}Singular`,O=y(f);if(O!==E("error.unknown"))return E(n,{item:O});{let k=`action.onSuccess.${t}WithoutItem`,L=y(k);return L!==E("error.unknown")?L:s}}return s}return E("success.transaction")},[y,E,A]),u=_react.useCallback.call(void 0, e=>{if(e.errorCode&&T[e.errorCode])return T[e.errorCode];if(e.errorCode&&M[e.errorCode])return y(M[e.errorCode]);if(e.errorCode){let i=[`errors.auth.${e.errorCode}`,`errors.data.${e.errorCode}`,`errors.system.${e.errorCode}`,`errors.${e.errorCode}`];for(let r of i){let t=y(r);if(t!==E("error.unknown"))return t}}if(typeof e.data=="string"&&e.data.startsWith("errors.")){let i=y(e.data);if(i!==E("error.unknown"))return i}if(e.errors&&Object.keys(e.errors).length>0){let i=Object.keys(e.errors);if(i.length===1&&i[0]==="_transaction"){let r=e.errors._transaction;if(_optionalChain([r, 'optionalAccess', _29 => _29.includes, 'call', _30 => _30("ONE_OR_MORE_OPERATIONS_FAILED")]))return"";if(Array.isArray(r)&&r.length>0){let t=r[0];if(typeof t=="string"&&t!=="ONE_OR_MORE_OPERATIONS_FAILED")try{let n=JSON.parse(t);if(Array.isArray(n)&&n.length>0){let s=n[0];if(_optionalChain([s, 'optionalAccess', _31 => _31.response, 'optionalAccess', _32 => _32.errorCode])){let f=s.response.errorCode;if(M[f])return y(M[f]);let O=[`errors.auth.${f}`,`errors.data.${f}`,`errors.system.${f}`,`errors.${f}`];for(let k of O){let L=y(k);if(L!==y("error.unknown"))return L}}if(_optionalChain([s, 'optionalAccess', _33 => _33.response, 'optionalAccess', _34 => _34.data]))return s.response.data}if(_optionalChain([n, 'optionalAccess', _35 => _35.response, 'optionalAccess', _36 => _36.message])){let s=n.response.message.toLowerCase();return s.includes("expired")?y("resetPassword.linkExpired","El enlace ha expirado"):s.includes("invalid")?y("resetPassword.invalidCode","C\xF3digo inv\xE1lido"):n.response.message}}catch (e4){return t.toLowerCase().includes("expired")?y("resetPassword.linkExpired","El enlace ha expirado"):t.toLowerCase().includes("invalid")?y("resetPassword.invalidCode","C\xF3digo inv\xE1lido"):t}}return y("error.transaction","Error en la operaci\xF3n")}if(i.length===1&&i[0]==="_error"){let r=e.errors._error;return Array.isArray(r)?r[0]:String(r)}return i.length===1&&i[0]==="_graphql"?y("errors.system.DATABASE_CONNECTION_ERROR"):`${y("errors.data.FIELD_ERROR")}: ${i.join(", ")}`}return I||E("error.unknown")},[T,I,E,y]),o=_react.useCallback.call(void 0, e=>e.errorCode&&Y[e.errorCode]?Y[e.errorCode]:"error",[]),m=_react.useCallback.call(void 0, async(e,i,r)=>{let t=await _crudifybrowser2.default.createItem(e,i,r);if(!t.success&&g&&d(t)){let n=u(t),s=o(t);a(n,s,{autoHideDuration:c})}else if(t.success){let n=_optionalChain([r, 'optionalAccess', _37 => _37.actionConfig]),s=_optionalChain([n, 'optionalAccess', _38 => _38.key])||"create",f=_optionalChain([n, 'optionalAccess', _39 => _39.moduleKey])||e;if(_(s,f)){let O=p(s,f,n);a(O,"success",{autoHideDuration:c})}}return t},[g,_,a,u,o,p,c,d]),l=_react.useCallback.call(void 0, async(e,i,r)=>{let t=await _crudifybrowser2.default.updateItem(e,i,r),n=_optionalChain([r, 'optionalAccess', _40 => _40.skipNotifications])===!0;if(!n&&!t.success&&g&&d(t)){let s=u(t),f=o(t);a(s,f,{autoHideDuration:c})}else if(!n&&t.success){let s=_optionalChain([r, 'optionalAccess', _41 => _41.actionConfig]),f=_optionalChain([s, 'optionalAccess', _42 => _42.key])||"update",O=_optionalChain([s, 'optionalAccess', _43 => _43.moduleKey])||e;if(_(f,O)){let k=p(f,O,s);a(k,"success",{autoHideDuration:c})}}return t},[g,_,a,u,o,p,c,d]),x=_react.useCallback.call(void 0, async(e,i,r)=>{let t=await _crudifybrowser2.default.deleteItem(e,i,r);if(!t.success&&g&&d(t)){let n=u(t),s=o(t);a(n,s,{autoHideDuration:c})}else if(t.success){let n=_optionalChain([r, 'optionalAccess', _44 => _44.actionConfig]),s=_optionalChain([n, 'optionalAccess', _45 => _45.key])||"delete",f=_optionalChain([n, 'optionalAccess', _46 => _46.moduleKey])||e;if(_(s,f)){let O=p(s,f,n);a(O,"success",{autoHideDuration:c})}}return t},[g,_,a,u,o,p,c,d]),P=_react.useCallback.call(void 0, async(e,i,r)=>{let t=await _crudifybrowser2.default.readItem(e,i,r);if(!t.success&&g&&d(t)){let n=u(t),s=o(t);a(n,s,{autoHideDuration:c})}return t},[g,a,u,o,c,d]),w=_react.useCallback.call(void 0, async(e,i,r)=>{let t=await _crudifybrowser2.default.readItems(e,i,r);if(!t.success&&g&&d(t)){let n=u(t),s=o(t);a(n,s,{autoHideDuration:c})}return t},[g,a,u,o,c,d]),V=_react.useCallback.call(void 0, async(e,i)=>{let r=await _crudifybrowser2.default.transaction(e,i),t=_optionalChain([i, 'optionalAccess', _47 => _47.skipNotifications])===!0;if(!t&&!r.success&&g&&d(r)){let n=u(r),s=o(r);a(n,s,{autoHideDuration:c})}else if(!t&&r.success){let n="transaction",s,f=null;if(_optionalChain([i, 'optionalAccess', _48 => _48.actionConfig])?(f=i.actionConfig,n=f.key,s=f.moduleKey):Array.isArray(e)&&e.length>0&&e[0].operation&&(n=e[0].operation,f=R.find(O=>O.key===n),f&&(s=f.moduleKey)),_(n,s)){let O=p(n,s,f);a(O,"success",{autoHideDuration:c})}}return r},[g,_,a,u,o,p,c,d,R]),F=_react.useCallback.call(void 0, (e,i)=>{if(!e.success&&g&&d(e)){let r=u(e),t=o(e);a(r,t,{autoHideDuration:c})}else e.success&&N&&i&&a(i,"success",{autoHideDuration:c});return e},[g,N,a,u,o,c,d,E]);return{createItem:m,updateItem:l,deleteItem:x,readItem:P,readItems:w,transaction:V,handleResponse:F,getErrorMessage:u,getErrorSeverity:o,shouldShowNotification:d}};exports.a = G; exports.b = ee; exports.c = oe; exports.d = le;
|
|
1
|
+
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }var _chunkWIWNROEAjs = require('./chunk-WIWNROEA.js');var _react = require('react');var _crudifybrowser = require('@nocios/crudify-browser'); var _crudifybrowser2 = _interopRequireDefault(_crudifybrowser);var G=(S={})=>{let{autoFetch:a=!0,retryOnError:N=!1,maxRetries:g=3}=S,{isAuthenticated:T,isInitialized:I,sessionData:c,tokens:R}=_chunkWIWNROEAjs.j.call(void 0, ),[E,d]=_react.useState.call(void 0, null),[y,A]=_react.useState.call(void 0, a&&T),[_,p]=_react.useState.call(void 0, null),u=_react.useRef.call(void 0, null),o=_react.useRef.call(void 0, !0),m=_react.useRef.call(void 0, 0),l=_react.useRef.call(void 0, 0),x=_react.useCallback.call(void 0, ()=>c&&(c.email||c["cognito:username"])||null,[c]),P=_react.useCallback.call(void 0, ()=>{d(null),p(null),A(!1),l.current=0},[]),w=_react.useCallback.call(void 0, async()=>{let F=x();if(!F){o.current&&(p("No user email available from session data"),A(!1));return}if(!I){o.current&&(p("Session not initialized"),A(!1));return}u.current&&u.current.abort();let e=new AbortController;u.current=e;let i=++m.current;try{o.current&&(A(!0),p(null));let r=await _crudifybrowser2.default.readItems("users",{filter:{email:F},pagination:{limit:1}});if(i===m.current&&o.current&&!e.signal.aborted){let t=null;if(r.success){if(Array.isArray(r.data)&&r.data.length>0)t=r.data[0];else if(_optionalChain([r, 'access', _2 => _2.data, 'optionalAccess', _3 => _3.response, 'optionalAccess', _4 => _4.data]))try{let n=r.data.response.data,s=typeof n=="string"?JSON.parse(n):n;s&&s.items&&Array.isArray(s.items)&&s.items.length>0&&(t=s.items[0])}catch (e2){}else if(r.data&&typeof r.data=="object")r.data.items&&Array.isArray(r.data.items)&&r.data.items.length>0&&(t=r.data.items[0]);else if(_optionalChain([r, 'access', _5 => _5.data, 'optionalAccess', _6 => _6.data, 'optionalAccess', _7 => _7.response, 'optionalAccess', _8 => _8.data]))try{let n=r.data.data.response.data,s=typeof n=="string"?JSON.parse(n):n;s&&s.items&&Array.isArray(s.items)&&s.items.length>0&&(t=s.items[0])}catch (e3){}}t?(d(t),p(null),l.current=0):(p("User profile not found in database"),d(null))}}catch(r){if(i===m.current&&o.current){let t=r;if(t.name==="AbortError")return;N&&l.current<g&&(_optionalChain([t, 'access', _9 => _9.message, 'optionalAccess', _10 => _10.includes, 'call', _11 => _11("Network Error")])||_optionalChain([t, 'access', _12 => _12.message, 'optionalAccess', _13 => _13.includes, 'call', _14 => _14("Failed to fetch")]))?(l.current++,setTimeout(()=>{o.current&&w()},1e3*l.current)):(p("Failed to load user profile from database"),d(null))}}finally{i===m.current&&o.current&&A(!1),u.current===e&&(u.current=null)}},[I,x,N,g]);return _react.useEffect.call(void 0, ()=>{a&&T&&I?w():T||P()},[a,T,I,w,P]),_react.useEffect.call(void 0, ()=>(o.current=!0,()=>{o.current=!1,u.current&&(u.current.abort(),u.current=null)}),[]),{user:{session:c,data:E},loading:y,error:_,refreshProfile:w,clearProfile:P}};var ee=()=>{let{isAuthenticated:S,isLoading:a,isInitialized:N,tokens:g,error:T,sessionData:I,login:c,logout:R,refreshTokens:E,clearError:d,getTokenInfo:y,isExpiringSoon:A,expiresIn:_,refreshExpiresIn:p}=_chunkWIWNROEAjs.j.call(void 0, ),u=_react.useCallback.call(void 0, m=>{m?console.warn("useAuth.setToken() is deprecated. Use login() method instead for better security."):R()},[R]),o=_optionalChain([g, 'optionalAccess', _15 => _15.expiresAt])?new Date(g.expiresAt):null;return{isAuthenticated:S,loading:a,error:T,token:_optionalChain([g, 'optionalAccess', _16 => _16.accessToken])||null,user:I,tokenExpiration:o,setToken:u,logout:R,refreshToken:E,login:c,isExpiringSoon:A,expiresIn:_,refreshExpiresIn:p,getTokenInfo:y,clearError:d}};var oe=()=>{let{isInitialized:S,isLoading:a,error:N,isAuthenticated:g,login:T}=_chunkWIWNROEAjs.j.call(void 0, ),I=_react.useCallback.call(void 0, ()=>S&&!a&&!N,[S,a,N]),c=_react.useCallback.call(void 0, async()=>new Promise((o,m)=>{let l=()=>{I()?o():N?m(new Error(N)):setTimeout(l,100)};l()}),[I,N]),R=_react.useCallback.call(void 0, async()=>{if(!I())throw new Error("System not ready. Check isInitialized, isLoading, and error states.")},[I]),E=_react.useCallback.call(void 0, async(o,m,l)=>(await R(),await _crudifybrowser2.default.readItems(o,m||{},l)),[R]),d=_react.useCallback.call(void 0, async(o,m,l)=>(await R(),await _crudifybrowser2.default.readItem(o,m,l)),[R]),y=_react.useCallback.call(void 0, async(o,m,l)=>(await R(),await _crudifybrowser2.default.createItem(o,m,l)),[R]),A=_react.useCallback.call(void 0, async(o,m,l)=>(await R(),await _crudifybrowser2.default.updateItem(o,m,l)),[R]),_=_react.useCallback.call(void 0, async(o,m,l)=>(await R(),await _crudifybrowser2.default.deleteItem(o,m,l)),[R]),p=_react.useCallback.call(void 0, async(o,m)=>(await R(),await _crudifybrowser2.default.transaction(o,m)),[R]),u=_react.useCallback.call(void 0, async(o,m)=>{try{let l=await T(o,m);return l.success?{success:!0,data:l.tokens}:{success:!1,errors:l.error||"Login failed"}}catch(l){return{success:!1,errors:l instanceof Error?l.message:"Login failed"}}},[T]);return{readItems:E,readItem:d,createItem:y,updateItem:A,deleteItem:_,transaction:p,login:u,isInitialized:S,isInitializing:a,initializationError:N,isReady:I,waitForReady:c}};var Y={INVALID_CREDENTIALS:"warning",UNAUTHORIZED:"warning",INVALID_API_KEY:"error",USER_NOT_FOUND:"warning",USER_NOT_ACTIVE:"warning",NO_PERMISSION:"warning",ITEM_NOT_FOUND:"info",NOT_FOUND:"info",IN_USE:"warning",FIELD_ERROR:"warning",BAD_REQUEST:"warning",INTERNAL_SERVER_ERROR:"error",DATABASE_CONNECTION_ERROR:"error",INVALID_CONFIGURATION:"error",UNKNOWN_OPERATION:"error",TOO_MANY_REQUESTS:"warning"},M={INVALID_CREDENTIALS:"errors.auth.INVALID_CREDENTIALS",UNAUTHORIZED:"errors.auth.UNAUTHORIZED",INVALID_API_KEY:"errors.auth.INVALID_API_KEY",USER_NOT_FOUND:"errors.auth.USER_NOT_FOUND",USER_NOT_ACTIVE:"errors.auth.USER_NOT_ACTIVE",NO_PERMISSION:"errors.auth.NO_PERMISSION",ITEM_NOT_FOUND:"errors.data.ITEM_NOT_FOUND",NOT_FOUND:"errors.data.NOT_FOUND",IN_USE:"errors.data.IN_USE",FIELD_ERROR:"errors.data.FIELD_ERROR",BAD_REQUEST:"errors.data.BAD_REQUEST",INTERNAL_SERVER_ERROR:"errors.system.INTERNAL_SERVER_ERROR",DATABASE_CONNECTION_ERROR:"errors.system.DATABASE_CONNECTION_ERROR",INVALID_CONFIGURATION:"errors.system.INVALID_CONFIGURATION",UNKNOWN_OPERATION:"errors.system.UNKNOWN_OPERATION",TOO_MANY_REQUESTS:"errors.system.TOO_MANY_REQUESTS"},le= exports.d =(S={})=>{let{showNotification:a}=_chunkWIWNROEAjs.h.call(void 0, ),{showSuccessNotifications:N=!1,showErrorNotifications:g=!0,customErrorMessages:T={},defaultErrorMessage:I="Ha ocurrido un error inesperado",autoHideDuration:c=6e3,appStructure:R=[],translateFn:E=e=>e}=S,d=_react.useCallback.call(void 0, e=>!(!e.success&&e.errors&&(Object.keys(e.errors).some(r=>r!=="_error"&&r!=="_graphql"&&r!=="_transaction")||_optionalChain([e, 'access', _17 => _17.errors, 'access', _18 => _18._transaction, 'optionalAccess', _19 => _19.includes, 'call', _20 => _20("ONE_OR_MORE_OPERATIONS_FAILED")])||_optionalChain([e, 'access', _21 => _21.errors, 'access', _22 => _22._error, 'optionalAccess', _23 => _23.includes, 'call', _24 => _24("TOO_MANY_REQUESTS")]))||!e.success&&_optionalChain([e, 'access', _25 => _25.data, 'optionalAccess', _26 => _26.response, 'optionalAccess', _27 => _27.status])==="TOO_MANY_REQUESTS"),[]),y=_react.useCallback.call(void 0, (e,i)=>{let r=E(e);return r===e?i||E("error.unknown"):r},[E]),A=_react.useCallback.call(void 0, e=>["create","update","delete"].includes(e),[]),_=_react.useCallback.call(void 0, (e,i)=>N?A(e)&&i?!0:R.some(r=>r.key===e):!1,[N,R,A]),p=_react.useCallback.call(void 0, (e,i,r)=>{let t=_optionalChain([r, 'optionalAccess', _28 => _28.key])&&typeof r.key=="string"?r.key:e,n=`action.onSuccess.${t}`,s=y(n);if(s!==E("error.unknown")){if(A(t)&&i){let f=`action.${i}Singular`,O=y(f);if(O!==E("error.unknown"))return E(n,{item:O});{let k=`action.onSuccess.${t}WithoutItem`,L=y(k);return L!==E("error.unknown")?L:s}}return s}return E("success.transaction")},[y,E,A]),u=_react.useCallback.call(void 0, e=>{if(e.errorCode&&T[e.errorCode])return T[e.errorCode];if(e.errorCode&&M[e.errorCode])return y(M[e.errorCode]);if(e.errorCode){let i=[`errors.auth.${e.errorCode}`,`errors.data.${e.errorCode}`,`errors.system.${e.errorCode}`,`errors.${e.errorCode}`];for(let r of i){let t=y(r);if(t!==E("error.unknown"))return t}}if(typeof e.data=="string"&&e.data.startsWith("errors.")){let i=y(e.data);if(i!==E("error.unknown"))return i}if(e.errors&&Object.keys(e.errors).length>0){let i=Object.keys(e.errors);if(i.length===1&&i[0]==="_transaction"){let r=e.errors._transaction;if(_optionalChain([r, 'optionalAccess', _29 => _29.includes, 'call', _30 => _30("ONE_OR_MORE_OPERATIONS_FAILED")]))return"";if(Array.isArray(r)&&r.length>0){let t=r[0];if(typeof t=="string"&&t!=="ONE_OR_MORE_OPERATIONS_FAILED")try{let n=JSON.parse(t);if(Array.isArray(n)&&n.length>0){let s=n[0];if(_optionalChain([s, 'optionalAccess', _31 => _31.response, 'optionalAccess', _32 => _32.errorCode])){let f=s.response.errorCode;if(M[f])return y(M[f]);let O=[`errors.auth.${f}`,`errors.data.${f}`,`errors.system.${f}`,`errors.${f}`];for(let k of O){let L=y(k);if(L!==y("error.unknown"))return L}}if(_optionalChain([s, 'optionalAccess', _33 => _33.response, 'optionalAccess', _34 => _34.data]))return s.response.data}if(_optionalChain([n, 'optionalAccess', _35 => _35.response, 'optionalAccess', _36 => _36.message])){let s=n.response.message.toLowerCase();return s.includes("expired")?y("resetPassword.linkExpired","El enlace ha expirado"):s.includes("invalid")?y("resetPassword.invalidCode","C\xF3digo inv\xE1lido"):n.response.message}}catch (e4){return t.toLowerCase().includes("expired")?y("resetPassword.linkExpired","El enlace ha expirado"):t.toLowerCase().includes("invalid")?y("resetPassword.invalidCode","C\xF3digo inv\xE1lido"):t}}return y("error.transaction","Error en la operaci\xF3n")}if(i.length===1&&i[0]==="_error"){let r=e.errors._error;return Array.isArray(r)?r[0]:String(r)}return i.length===1&&i[0]==="_graphql"?y("errors.system.DATABASE_CONNECTION_ERROR"):`${y("errors.data.FIELD_ERROR")}: ${i.join(", ")}`}return I||E("error.unknown")},[T,I,E,y]),o=_react.useCallback.call(void 0, e=>e.errorCode&&Y[e.errorCode]?Y[e.errorCode]:"error",[]),m=_react.useCallback.call(void 0, async(e,i,r)=>{let t=await _crudifybrowser2.default.createItem(e,i,r);if(!t.success&&g&&d(t)){let n=u(t),s=o(t);a(n,s,{autoHideDuration:c})}else if(t.success){let n=_optionalChain([r, 'optionalAccess', _37 => _37.actionConfig]),s=_optionalChain([n, 'optionalAccess', _38 => _38.key])||"create",f=_optionalChain([n, 'optionalAccess', _39 => _39.moduleKey])||e;if(_(s,f)){let O=p(s,f,n);a(O,"success",{autoHideDuration:c})}}return t},[g,_,a,u,o,p,c,d]),l=_react.useCallback.call(void 0, async(e,i,r)=>{let t=await _crudifybrowser2.default.updateItem(e,i,r),n=_optionalChain([r, 'optionalAccess', _40 => _40.skipNotifications])===!0;if(!n&&!t.success&&g&&d(t)){let s=u(t),f=o(t);a(s,f,{autoHideDuration:c})}else if(!n&&t.success){let s=_optionalChain([r, 'optionalAccess', _41 => _41.actionConfig]),f=_optionalChain([s, 'optionalAccess', _42 => _42.key])||"update",O=_optionalChain([s, 'optionalAccess', _43 => _43.moduleKey])||e;if(_(f,O)){let k=p(f,O,s);a(k,"success",{autoHideDuration:c})}}return t},[g,_,a,u,o,p,c,d]),x=_react.useCallback.call(void 0, async(e,i,r)=>{let t=await _crudifybrowser2.default.deleteItem(e,i,r);if(!t.success&&g&&d(t)){let n=u(t),s=o(t);a(n,s,{autoHideDuration:c})}else if(t.success){let n=_optionalChain([r, 'optionalAccess', _44 => _44.actionConfig]),s=_optionalChain([n, 'optionalAccess', _45 => _45.key])||"delete",f=_optionalChain([n, 'optionalAccess', _46 => _46.moduleKey])||e;if(_(s,f)){let O=p(s,f,n);a(O,"success",{autoHideDuration:c})}}return t},[g,_,a,u,o,p,c,d]),P=_react.useCallback.call(void 0, async(e,i,r)=>{let t=await _crudifybrowser2.default.readItem(e,i,r);if(!t.success&&g&&d(t)){let n=u(t),s=o(t);a(n,s,{autoHideDuration:c})}return t},[g,a,u,o,c,d]),w=_react.useCallback.call(void 0, async(e,i,r)=>{let t=await _crudifybrowser2.default.readItems(e,i,r);if(!t.success&&g&&d(t)){let n=u(t),s=o(t);a(n,s,{autoHideDuration:c})}return t},[g,a,u,o,c,d]),V=_react.useCallback.call(void 0, async(e,i)=>{let r=await _crudifybrowser2.default.transaction(e,i),t=_optionalChain([i, 'optionalAccess', _47 => _47.skipNotifications])===!0;if(!t&&!r.success&&g&&d(r)){let n=u(r),s=o(r);a(n,s,{autoHideDuration:c})}else if(!t&&r.success){let n="transaction",s,f=null;if(_optionalChain([i, 'optionalAccess', _48 => _48.actionConfig])?(f=i.actionConfig,n=f.key,s=f.moduleKey):Array.isArray(e)&&e.length>0&&e[0].operation&&(n=e[0].operation,f=R.find(O=>O.key===n),f&&(s=f.moduleKey)),_(n,s)){let O=p(n,s,f);a(O,"success",{autoHideDuration:c})}}return r},[g,_,a,u,o,p,c,d,R]),F=_react.useCallback.call(void 0, (e,i)=>{if(!e.success&&g&&d(e)){let r=u(e),t=o(e);a(r,t,{autoHideDuration:c})}else e.success&&N&&i&&a(i,"success",{autoHideDuration:c});return e},[g,N,a,u,o,c,d,E]);return{createItem:m,updateItem:l,deleteItem:x,readItem:P,readItems:w,transaction:V,handleResponse:F,getErrorMessage:u,getErrorSeverity:o,shouldShowNotification:d}};exports.a = G; exports.b = ee; exports.c = oe; exports.d = le;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{b as oe,d as ye,h as K,i as he,j as me,k as Te}from"./chunk-6GPSBDW6.mjs";import{createContext as Ue,useContext as He,useEffect as Me,useState as Y}from"react";import B from"@nocios/crudify-browser";var se=class r{constructor(){this.listeners=[];this.credentials=null;this.isReady=!1}static getInstance(){return r.instance||(r.instance=new r),r.instance}notifyCredentialsReady(i){this.credentials=i,this.isReady=!0,this.listeners.forEach(e=>{try{e(i)}catch(t){console.error("[CredentialsEventBus] Error in listener:",t)}}),this.listeners=[]}waitForCredentials(){return this.isReady&&this.credentials?Promise.resolve(this.credentials):new Promise(i=>{this.listeners.push(i)})}reset(){this.credentials=null,this.isReady=!1,this.listeners=[]}areCredentialsReady(){return this.isReady&&this.credentials!==null}},ve=se.getInstance();import{jsx as Ge}from"react/jsx-runtime";var Ee=Ue(void 0),Ae=({config:r,children:i})=>{let[e,t]=Y(!0),[o,s]=Y(null),[f,h]=Y(!1),[S,I]=Y(""),[v,c]=Y();Me(()=>{if(!r.publicApiKey){s("No publicApiKey provided"),t(!1),h(!1);return}let l=`${r.publicApiKey}-${r.env}`;if(l===S&&f){t(!1);return}(async()=>{t(!0),s(null),h(!1);try{B.config(r.env||"prod");let p=await B.init(r.publicApiKey,"none");if(c(p),typeof B.transaction=="function"&&typeof B.login=="function")h(!0),I(l),p.apiEndpointAdmin&&p.apiKeyEndpointAdmin&&ve.notifyCredentialsReady({apiUrl:p.apiEndpointAdmin,apiKey:p.apiKeyEndpointAdmin});else throw new Error("Crudify methods not properly initialized")}catch(p){let T=p instanceof Error?p.message:"Failed to initialize Crudify";console.error("[CrudifyProvider] Initialization error:",p),s(T),h(!1)}finally{t(!1)}})()},[r.publicApiKey,r.env,S,f]);let a={crudify:f?B:null,isLoading:e,error:o,isInitialized:f,adminCredentials:v};return Ge(Ee.Provider,{value:a,children:i})},Ie=()=>{let r=He(Ee);if(r===void 0)throw new Error("useCrudify must be used within a CrudifyProvider");return r};import Z from"crypto-js";var d=class d{static setStorageType(i){d.storageType=i}static generateEncryptionKey(){let i=[navigator.userAgent,navigator.language,navigator.platform,screen.width,screen.height,Date.now().toString(),Math.random().toString(36)].join("|");return Z.SHA256(i).toString()}static getEncryptionKey(){if(d.encryptionKey)return d.encryptionKey;let i=window.localStorage;if(!i)return d.encryptionKey=d.generateEncryptionKey(),d.encryptionKey;try{let e=i.getItem(d.ENCRYPTION_KEY_STORAGE);return(!e||e.length<32)&&(e=d.generateEncryptionKey(),i.setItem(d.ENCRYPTION_KEY_STORAGE,e)),d.encryptionKey=e,e}catch{return console.warn("Crudify: Cannot persist encryption key, using temporary key"),d.encryptionKey=d.generateEncryptionKey(),d.encryptionKey}}static isStorageAvailable(i){try{let e=window[i],t="__storage_test__";return e.setItem(t,"test"),e.removeItem(t),!0}catch{return!1}}static getStorage(){return d.storageType==="none"?null:d.isStorageAvailable(d.storageType)?window[d.storageType]:(console.warn(`Crudify: ${d.storageType} not available, tokens won't persist`),null)}static encrypt(i){try{let e=d.getEncryptionKey();return Z.AES.encrypt(i,e).toString()}catch(e){return console.error("Crudify: Encryption failed",e),i}}static decrypt(i){try{let e=d.getEncryptionKey();return Z.AES.decrypt(i,e).toString(Z.enc.Utf8)||i}catch(e){return console.error("Crudify: Decryption failed",e),i}}static saveTokens(i){let e=d.getStorage();if(e)try{let t={accessToken:i.accessToken,refreshToken:i.refreshToken,expiresAt:i.expiresAt,refreshExpiresAt:i.refreshExpiresAt,savedAt:Date.now()},o=d.encrypt(JSON.stringify(t));e.setItem(d.TOKEN_KEY,o),console.debug("Crudify: Tokens saved successfully")}catch(t){console.error("Crudify: Failed to save tokens",t)}}static getTokens(){let i=d.getStorage();if(!i)return null;try{let e=i.getItem(d.TOKEN_KEY);if(!e)return null;let t=d.decrypt(e),o=JSON.parse(t);return!o.accessToken||!o.refreshToken||!o.expiresAt||!o.refreshExpiresAt?(console.warn("Crudify: Incomplete token data found, clearing storage"),d.clearTokens(),null):Date.now()>=o.refreshExpiresAt?(console.info("Crudify: Refresh token expired, clearing storage"),d.clearTokens(),null):{accessToken:o.accessToken,refreshToken:o.refreshToken,expiresAt:o.expiresAt,refreshExpiresAt:o.refreshExpiresAt}}catch(e){return console.error("Crudify: Failed to retrieve tokens",e),d.clearTokens(),null}}static clearTokens(){let i=d.getStorage();if(i)try{i.removeItem(d.TOKEN_KEY),console.debug("Crudify: Tokens cleared from storage")}catch(e){console.error("Crudify: Failed to clear tokens",e)}}static rotateEncryptionKey(){try{d.clearTokens(),d.encryptionKey=null;let i=window.localStorage;i&&i.removeItem(d.ENCRYPTION_KEY_STORAGE),console.info("Crudify: Encryption key rotated successfully")}catch(i){console.error("Crudify: Failed to rotate encryption key",i)}}static hasValidTokens(){return d.getTokens()!==null}static getExpirationInfo(){let i=d.getTokens();if(!i)return null;let e=Date.now();return{accessExpired:e>=i.expiresAt,refreshExpired:e>=i.refreshExpiresAt,accessExpiresIn:Math.max(0,i.expiresAt-e),refreshExpiresIn:Math.max(0,i.refreshExpiresAt-e)}}static updateAccessToken(i,e){let t=d.getTokens();if(!t){console.warn("Crudify: Cannot update access token, no existing tokens found");return}d.saveTokens({...t,accessToken:i,expiresAt:e})}static subscribeToChanges(i){let e=t=>{if(t.key===d.TOKEN_KEY){if(t.newValue===null){console.debug("Crudify: Tokens removed in another tab"),i(null);return}if(t.newValue){console.debug("Crudify: Tokens updated in another tab");let o=d.getTokens();i(o)}}};return window.addEventListener("storage",e),()=>{window.removeEventListener("storage",e)}}};d.TOKEN_KEY="crudify_tokens",d.ENCRYPTION_KEY_STORAGE="crudify_enc_key",d.encryptionKey=null,d.storageType="localStorage";var A=d;import w from"@nocios/crudify-browser";var W=class r{constructor(){this.config={};this.initialized=!1;this.crudifyInitialized=!1;this.lastActivityTime=0;this.isRefreshingLocally=!1;this.refreshPromise=null}static getInstance(){return r.instance||(r.instance=new r),r.instance}async initialize(i={}){if(!this.initialized){if(this.config={storageType:"localStorage",autoRestore:!0,enableLogging:!1,env:"stg",...i},A.setStorageType(this.config.storageType||"localStorage"),this.config.publicApiKey&&!this.crudifyInitialized&&await this.ensureCrudifyInitialized(),w.setTokenInvalidationCallback(()=>{this.log("Tokens invalidated by crudify-core"),K.emit("SESSION_EXPIRED",{message:"Your session has expired. Please log in again.",source:"crudify-core.clearTokensAndRefreshState"})}),this.config.apiEndpointAdmin&&this.config.apiKeyEndpointAdmin){let e=A.getTokens();e?A.saveTokens({...e,apiEndpointAdmin:this.config.apiEndpointAdmin,apiKeyEndpointAdmin:this.config.apiKeyEndpointAdmin}):A.saveTokens({accessToken:"",refreshToken:"",expiresAt:0,refreshExpiresAt:0,apiEndpointAdmin:this.config.apiEndpointAdmin,apiKeyEndpointAdmin:this.config.apiKeyEndpointAdmin})}this.config.autoRestore&&await this.restoreSession(),this.initialized=!0}}async login(i,e){try{let t=await w.login(i,e);if(!t.success)return{success:!1,error:this.formatError(t.errors),rawResponse:t};let o=A.getTokens(),s={accessToken:t.data.token,refreshToken:t.data.refreshToken,expiresAt:t.data.expiresAt,refreshExpiresAt:t.data.refreshExpiresAt,apiEndpointAdmin:o?.apiEndpointAdmin||this.config.apiEndpointAdmin,apiKeyEndpointAdmin:o?.apiKeyEndpointAdmin||this.config.apiKeyEndpointAdmin};return A.saveTokens(s),this.lastActivityTime=Date.now(),this.config.onLoginSuccess?.(s),{success:!0,tokens:s,data:t.data}}catch(t){return console.error("[SessionManager] Login error:",t),{success:!1,error:t instanceof Error?t.message:"Unknown error"}}}async logout(){try{this.log("Logging out..."),await w.logout(),A.clearTokens(),this.log("Logout successful"),this.config.onLogout?.()}catch(i){this.log("Logout error:",i),A.clearTokens()}}async restoreSession(){try{this.log("Attempting to restore session...");let i=A.getTokens();if(!i)return this.log("No valid tokens found in storage"),!1;if(Date.now()>=i.refreshExpiresAt)return this.log("Refresh token expired, clearing storage"),A.clearTokens(),!1;if(w.setTokens({accessToken:i.accessToken,refreshToken:i.refreshToken,expiresAt:i.expiresAt,refreshExpiresAt:i.refreshExpiresAt}),w.getTokenData().isValid===!1){if(this.log("Restored access token is invalid or expired"),Date.now()<i.refreshExpiresAt&&(this.log("Access token expired but refresh is valid, attempting refresh..."),await this.refreshTokens())){this.log("Session restored successfully via token refresh");let o=A.getTokens();return o&&this.config.onSessionRestored?.(o),!0}return A.clearTokens(),await w.logout(),!1}return this.log("Session restored successfully"),this.lastActivityTime=Date.now(),this.config.onSessionRestored?.(i),!0}catch(i){return this.log("Session restore error:",i),A.clearTokens(),await w.logout(),!1}}isAuthenticated(){return w.isLogin()||A.hasValidTokens()}getTokenInfo(){let i=w.getTokenData(),e=A.getExpirationInfo(),t=A.getTokens();return{isLoggedIn:this.isAuthenticated(),crudifyTokens:i,storageInfo:e,hasValidTokens:A.hasValidTokens(),apiEndpointAdmin:t?.apiEndpointAdmin,apiKeyEndpointAdmin:t?.apiKeyEndpointAdmin}}async refreshTokens(){if(this.isRefreshingLocally&&this.refreshPromise)return this.log("Refresh already in progress, waiting for existing promise..."),this.refreshPromise;this.isRefreshingLocally=!0,this.refreshPromise=this._performRefresh();try{return await this.refreshPromise}finally{this.isRefreshingLocally=!1,this.refreshPromise=null}}async _performRefresh(){try{this.log("Starting token refresh...");let i=await w.refreshAccessToken();if(!i.success)return this.log("Token refresh failed:",i.errors),A.clearTokens(),this.config.showNotification?.(this.getSessionExpiredMessage(),"warning"),this.config.onSessionExpired?.(),!1;let e={accessToken:i.data.token,refreshToken:i.data.refreshToken,expiresAt:i.data.expiresAt,refreshExpiresAt:i.data.refreshExpiresAt};return A.saveTokens(e),this.log("Tokens refreshed and saved successfully"),this.lastActivityTime=Date.now(),!0}catch(i){return this.log("Token refresh error:",i),A.clearTokens(),this.config.showNotification?.(this.getSessionExpiredMessage(),"warning"),this.config.onSessionExpired?.(),!1}}isRefreshing(){return this.isRefreshingLocally}setupResponseInterceptor(){w.setResponseInterceptor(async i=>{this.updateLastActivity();let e=this.detectAuthorizationError(i);if(e.isAuthError){if(this.log("\u{1F6A8} Authorization error detected:",{errorType:e.errorType,shouldLogout:e.shouldTriggerLogout}),e.isRefreshTokenInvalid||e.isTokenRefreshFailed)return this.log("Refresh token invalid, emitting TOKEN_REFRESH_FAILED event"),K.emit("TOKEN_REFRESH_FAILED",{message:e.userFriendlyMessage,error:e.errorDetails,source:"SessionManager.setupResponseInterceptor"}),i;e.shouldTriggerLogout&&(A.hasValidTokens()&&!e.isIrrecoverable?(this.log("Access token expired, emitting TOKEN_EXPIRED event"),K.emit("TOKEN_EXPIRED",{message:"Access token expired, refresh needed",error:e.errorDetails,source:"SessionManager.setupResponseInterceptor"})):(this.log("No valid tokens or irrecoverable error, emitting SESSION_EXPIRED event"),K.emit("SESSION_EXPIRED",{message:e.userFriendlyMessage,error:e.errorDetails,source:"SessionManager.setupResponseInterceptor"})))}return i}),this.log("Response interceptor configured (non-blocking mode)")}async ensureCrudifyInitialized(){if(!this.crudifyInitialized)try{this.log("Initializing crudify SDK...");let i=w.getTokenData();if(i&&i.endpoint){this.log("Crudify already initialized by another service"),this.crudifyInitialized=!0;return}let e=this.config.env||"stg";w.config(e);let t=this.config.publicApiKey,o=this.config.enableLogging?"debug":"none",s=await w.init(t,o);if(s&&s.success===!1&&s.errors)throw new Error(`Failed to initialize crudify: ${JSON.stringify(s.errors)}`);this.crudifyInitialized=!0,this.log("Crudify SDK initialized successfully")}catch(i){throw console.error("[SessionManager] Failed to initialize crudify:",i),i}}detectAuthorizationError(i){let e={isAuthError:!1,isRefreshTokenInvalid:!1,isTokenRefreshFailed:!1,isTokenExpired:!1,isUnauthorized:!1,isIrrecoverable:!1,shouldTriggerLogout:!1,errorType:"",errorDetails:null,userFriendlyMessage:""};if(i.errors&&Array.isArray(i.errors)){let t=i.errors.find(o=>o.errorType==="Unauthorized"||o.message?.includes("Unauthorized")||o.message?.includes("Not Authorized")||o.message?.includes("NOT_AUTHORIZED")||o.message?.includes("Token")||o.message?.includes("TOKEN")||o.message?.includes("Authentication")||o.message?.includes("UNAUTHENTICATED")||o.extensions?.code==="UNAUTHENTICATED"||o.extensions?.code==="FORBIDDEN");t&&(e.isAuthError=!0,e.errorType="GraphQL Array",e.errorDetails=t,e.shouldTriggerLogout=!0,e.userFriendlyMessage="Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente.",(t.message?.includes("TOKEN")||t.message?.includes("Token"))&&(e.isTokenExpired=!0),t.extensions?.code==="UNAUTHENTICATED"&&(e.isUnauthorized=!0))}if(!e.isAuthError&&i.errors&&typeof i.errors=="object"&&!Array.isArray(i.errors)){let o=Object.values(i.errors).flat().find(s=>typeof s=="string"&&(s.includes("NOT_AUTHORIZED")||s.includes("TOKEN_REFRESH_FAILED")||s.includes("TOKEN_HAS_EXPIRED")||s.includes("PLEASE_LOGIN")||s.includes("Unauthorized")||s.includes("UNAUTHENTICATED")||s.includes("SESSION_EXPIRED")||s.includes("INVALID_TOKEN")));o&&typeof o=="string"&&(e.isAuthError=!0,e.errorType="GraphQL Object",e.errorDetails=i.errors,e.shouldTriggerLogout=!0,o.includes("TOKEN_REFRESH_FAILED")?(e.isTokenRefreshFailed=!0,e.isRefreshTokenInvalid=!0,e.isIrrecoverable=!0,e.userFriendlyMessage="Tu sesi\xF3n ha caducado. Por favor, inicia sesi\xF3n nuevamente."):o.includes("TOKEN_HAS_EXPIRED")||o.includes("SESSION_EXPIRED")?(e.isTokenExpired=!0,e.userFriendlyMessage="Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente."):o.includes("INVALID_TOKEN")?(e.isTokenExpired=!0,e.isIrrecoverable=!0,e.userFriendlyMessage="Token inv\xE1lido. Por favor, inicia sesi\xF3n nuevamente."):e.userFriendlyMessage="Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente.")}if(!e.isAuthError&&i.data?.response?.status){let t=i.data.response.status.toUpperCase();(t==="UNAUTHORIZED"||t==="UNAUTHENTICATED")&&(e.isAuthError=!0,e.errorType="Status",e.errorDetails=i.data.response,e.isUnauthorized=!0,e.shouldTriggerLogout=!0,e.isIrrecoverable=!0,e.userFriendlyMessage="Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente.")}if(!e.isAuthError&&i.data?.response?.data)try{let t=typeof i.data.response.data=="string"?JSON.parse(i.data.response.data):i.data.response.data;(t.error==="REFRESH_TOKEN_INVALID"||t.error==="TOKEN_EXPIRED"||t.error==="INVALID_TOKEN")&&(e.isAuthError=!0,e.errorType="Parsed Data",e.errorDetails=t,e.shouldTriggerLogout=!0,e.isIrrecoverable=!0,t.error==="REFRESH_TOKEN_INVALID"?(e.isRefreshTokenInvalid=!0,e.isTokenRefreshFailed=!0,e.userFriendlyMessage="Tu sesi\xF3n ha caducado. Por favor, inicia sesi\xF3n nuevamente."):(e.isTokenExpired=!0,e.userFriendlyMessage="Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente."))}catch{}if(!e.isAuthError&&i.errorCode){let t=i.errorCode.toUpperCase();(t==="UNAUTHORIZED"||t==="UNAUTHENTICATED"||t==="TOKEN_EXPIRED"||t==="INVALID_TOKEN")&&(e.isAuthError=!0,e.errorType="Error Code",e.errorDetails={errorCode:t},e.shouldTriggerLogout=!0,t==="TOKEN_EXPIRED"?e.isTokenExpired=!0:e.isUnauthorized=!0,e.userFriendlyMessage="Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente.")}return e}updateLastActivity(){this.lastActivityTime=Date.now(),this.log("Last activity updated")}getTimeSinceLastActivity(){return this.lastActivityTime===0?0:Date.now()-this.lastActivityTime}checkInactivity(){let i=this.getTimeSinceLastActivity();if(this.lastActivityTime===0)return"none";let e=1800*1e3;return i>e?(this.log(`Inactivity timeout: ${Math.floor(i/6e4)} minutes since last activity`),"logout"):"none"}clearSession(){A.clearTokens(),w.logout(),this.lastActivityTime=0,this.log("Session cleared completely")}getSessionExpiredMessage(){return this.config.translateFn?ye("SESSION_EXPIRED",{translateFn:this.config.translateFn,enableDebug:this.config.enableLogging}):"Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente."}log(i,...e){this.config.enableLogging&&console.log(`[SessionManager] ${i}`,...e)}formatError(i){return i?typeof i=="string"?i:typeof i=="object"?Object.values(i).flat().join(", "):"Authentication failed":"Unknown error"}};import{useState as _e,useEffect as q,useCallback as M}from"react";function be(r={}){let[i,e]=_e({isAuthenticated:!1,isLoading:!0,isInitialized:!1,tokens:null,error:null}),t=W.getInstance(),o=M(async()=>{console.log("\u{1F535} [useSession] initialize() CALLED"),console.log("\u{1F50D} [useSession] options received:",{autoRestore:r.autoRestore,enableLogging:r.enableLogging,apiEndpointAdmin:r.apiEndpointAdmin,apiKeyEndpointAdmin:r.apiKeyEndpointAdmin});try{e(n=>({...n,isLoading:!0,error:null}));let c={autoRestore:r.autoRestore??!0,enableLogging:r.enableLogging??!1,showNotification:r.showNotification,translateFn:r.translateFn,apiEndpointAdmin:r.apiEndpointAdmin,apiKeyEndpointAdmin:r.apiKeyEndpointAdmin,publicApiKey:r.publicApiKey,env:r.env||"stg",onSessionExpired:()=>{e(n=>({...n,isAuthenticated:!1,tokens:null,error:"Session expired"})),r.onSessionExpired?.()},onSessionRestored:n=>{e(p=>({...p,isAuthenticated:!0,tokens:n,error:null})),r.onSessionRestored?.(n)},onLoginSuccess:n=>{e(p=>({...p,isAuthenticated:!0,tokens:n,error:null}))},onLogout:()=>{e(n=>({...n,isAuthenticated:!1,tokens:null,error:null}))}};console.log("\u{1F50D} [useSession] Calling sessionManager.initialize() with config:",c),await t.initialize(c),console.log("\u2705 [useSession] sessionManager.initialize() completed"),t.setupResponseInterceptor();let a=t.isAuthenticated(),l=t.getTokenInfo();console.log("\u{1F50D} [useSession] After initialize, isAuth:",a),console.log("\u{1F50D} [useSession] After initialize, tokenInfo:",l),e(n=>({...n,isAuthenticated:a,isInitialized:!0,isLoading:!1,tokens:l.crudifyTokens.accessToken?{accessToken:l.crudifyTokens.accessToken,refreshToken:l.crudifyTokens.refreshToken,expiresAt:l.crudifyTokens.expiresAt,refreshExpiresAt:l.crudifyTokens.refreshExpiresAt}:null}))}catch(c){let a=c instanceof Error?c.message:"Initialization failed";e(l=>({...l,isLoading:!1,isInitialized:!0,error:a}))}},[r.autoRestore,r.enableLogging,r.onSessionExpired,r.onSessionRestored]),s=M(async(c,a)=>{e(l=>({...l,isLoading:!0,error:null}));try{let l=await t.login(c,a);return l.success&&l.tokens?e(n=>({...n,isAuthenticated:!0,tokens:l.tokens,isLoading:!1,error:null})):e(n=>({...n,isAuthenticated:!1,tokens:null,isLoading:!1,error:null})),l}catch(l){let n=l instanceof Error?l.message:"Login failed",p=n.includes("INVALID_CREDENTIALS")||n.includes("Invalid email")||n.includes("Invalid password")||n.includes("credentials");return e(T=>({...T,isAuthenticated:!1,tokens:null,isLoading:!1,error:p?null:n})),{success:!1,error:n}}},[t]),f=M(async()=>{e(c=>({...c,isLoading:!0}));try{await t.logout(),e(c=>({...c,isAuthenticated:!1,tokens:null,isLoading:!1,error:null}))}catch(c){e(a=>({...a,isAuthenticated:!1,tokens:null,isLoading:!1,error:c instanceof Error?c.message:"Logout error"}))}},[t]),h=M(async()=>{try{let c=await t.refreshTokens();if(c){let a=t.getTokenInfo();e(l=>({...l,tokens:a.crudifyTokens.accessToken?{accessToken:a.crudifyTokens.accessToken,refreshToken:a.crudifyTokens.refreshToken,expiresAt:a.crudifyTokens.expiresAt,refreshExpiresAt:a.crudifyTokens.refreshExpiresAt}:null,error:null}))}else e(a=>({...a,isAuthenticated:!1,tokens:null,error:"Token refresh failed"}));return c}catch(c){return e(a=>({...a,isAuthenticated:!1,tokens:null,error:c instanceof Error?c.message:"Token refresh failed"})),!1}},[t]),S=M(()=>{e(c=>({...c,error:null}))},[]),I=M(()=>t.getTokenInfo(),[t]);q(()=>{o()},[o]),q(()=>{if(!i.isAuthenticated||!i.tokens)return;let c=he.getInstance(),a=()=>{t.updateLastActivity(),r.enableLogging&&console.log("\u{1F4CD} User navigating - activity updated")},l=c.subscribe(a);window.addEventListener("popstate",a);let n=()=>{let C=t.getTokenInfo().crudifyTokens.expiresIn||0;return C<300*1e3?30*1e3:C<1800*1e3?60*1e3:120*1e3},p,T=()=>{let k=n();p=setTimeout(async()=>{if(t.isRefreshing()){r.enableLogging&&console.log("\u23F8\uFE0F Refresh in progress, rescheduling check"),T();return}let C=t.getTokenInfo(),b=C.crudifyTokens.expiresIn||0,z=(C.crudifyTokens.expiresAt||0)-(Date.now()-b),E=z*.5;if(b>0&&b<=E){let $=Math.round(b/z*100);if(r.enableLogging&&console.log(`\u{1F504} Token at ${$}% of TTL (${Math.round(b/6e4)}min remaining), refreshing...`),e(F=>({...F,isLoading:!0})),await t.refreshTokens()){let F=t.getTokenInfo();e(re=>({...re,isLoading:!1,tokens:F.crudifyTokens.accessToken?{accessToken:F.crudifyTokens.accessToken,refreshToken:F.crudifyTokens.refreshToken,expiresAt:F.crudifyTokens.expiresAt,refreshExpiresAt:F.crudifyTokens.refreshExpiresAt}:null}))}else e(F=>({...F,isLoading:!1,isAuthenticated:!1,tokens:null}))}let _=t.getTimeSinceLastActivity(),H=1800*1e3;_>H?(r.enableLogging&&console.log("\u23F1\uFE0F Inactivity timeout (30min) - logging out"),await f()):T()},k)};return T(),()=>{clearTimeout(p),window.removeEventListener("popstate",a),l()}},[i.isAuthenticated,i.tokens,t,r.enableLogging,f]),q(()=>{let c=K.subscribe(async a=>{if(r.enableLogging&&console.log(`\u{1F4E2} useSession: Received auth event: ${a.type}`),a.type==="TOKEN_EXPIRED"){if(t.isRefreshing()){r.enableLogging&&console.log("\u23F8\uFE0F Refresh already in progress, skipping TOKEN_EXPIRED handler");return}r.enableLogging&&console.log("\u{1F504} Token expired, attempting refresh..."),e(l=>({...l,isLoading:!0}));try{if(await t.refreshTokens()){r.enableLogging&&console.log("\u2705 Token refreshed successfully");let n=t.getTokenInfo();e(p=>({...p,isLoading:!1,tokens:n.crudifyTokens.accessToken?{accessToken:n.crudifyTokens.accessToken,refreshToken:n.crudifyTokens.refreshToken,expiresAt:n.crudifyTokens.expiresAt,refreshExpiresAt:n.crudifyTokens.refreshExpiresAt}:null}))}else r.enableLogging&&console.log("\u274C Token refresh failed, session expired"),K.emit("SESSION_EXPIRED",{message:"Failed to refresh token after detecting expiration",source:"useSession.TOKEN_EXPIRED handler"})}catch(l){r.enableLogging&&console.error("\u274C Error during token refresh:",l),K.emit("SESSION_EXPIRED",{message:l instanceof Error?l.message:"Unknown error during refresh",source:"useSession.TOKEN_EXPIRED handler (error)"})}}(a.type==="SESSION_EXPIRED"||a.type==="TOKEN_REFRESH_FAILED")&&(r.enableLogging&&console.log(`\u{1F534} Session expired (${a.type}), logging out...`),e(l=>({...l,isAuthenticated:!1,tokens:null,isLoading:!1,error:a.details?.message||"Session expired"})),r.onSessionExpired?.())});return()=>c()},[r.enableLogging,r.onSessionExpired,t]),q(()=>{let c=A.subscribeToChanges(a=>{a?(r.enableLogging&&console.log("\u{1F504} Tokens updated in another tab"),e(l=>({...l,tokens:a,isAuthenticated:!0}))):(r.enableLogging&&console.log("\u{1F504} Logout detected in another tab"),e(l=>({...l,isAuthenticated:!1,tokens:null})),K.emit("SESSION_EXPIRED",{message:"Sesi\xF3n cerrada en otra pesta\xF1a",source:"CrossTabSync"}))});return()=>c()},[r.enableLogging]);let v=M(()=>{t.updateLastActivity()},[t]);return{...i,login:s,logout:f,refreshTokens:h,clearError:S,getTokenInfo:I,updateActivity:v,isExpiringSoon:i.tokens?i.tokens.expiresAt-Date.now()<300*1e3:!1,expiresIn:i.tokens?Math.max(0,i.tokens.expiresAt-Date.now()):0,refreshExpiresIn:i.tokens?Math.max(0,i.tokens.refreshExpiresAt-Date.now()):0}}import{useState as ke,createContext as $e,useContext as Ve,useCallback as J,useEffect as Ye}from"react";import{Snackbar as Be,Alert as Xe,Box as Ze,Portal as We}from"@mui/material";import{v4 as qe}from"uuid";import Je from"dompurify";import{jsx as G,jsxs as ei}from"react/jsx-runtime";var xe=$e(null),je=r=>Je.sanitize(r,{ALLOWED_TAGS:["b","i","em","strong","br","span"],ALLOWED_ATTR:["class"],FORBID_TAGS:["script","iframe","object","embed"],FORBID_ATTR:["onload","onerror","onclick","onmouseover","onfocus","onblur"],WHOLE_DOCUMENT:!1,RETURN_DOM:!1,RETURN_DOM_FRAGMENT:!1,RETURN_TRUSTED_TYPE:!1}),ae=({children:r,maxNotifications:i=5,defaultAutoHideDuration:e=6e3,position:t={vertical:"top",horizontal:"right"},enabled:o=!1,allowHtml:s=!1})=>{let[f,h]=ke([]),S=J((a,l="info",n)=>{if(!o)return"";if(!a||typeof a!="string")return console.warn("\u26A0\uFE0F GlobalNotificationProvider: Invalid message provided"),"";a.length>1e3&&(console.warn("\u26A0\uFE0F GlobalNotificationProvider: Message too long, truncating"),a=a.substring(0,1e3)+"...");let p=qe(),T={id:p,message:a,severity:l,autoHideDuration:n?.autoHideDuration??e,persistent:n?.persistent??!1,allowHtml:n?.allowHtml??s};return h(k=>[...k.length>=i?k.slice(-(i-1)):k,T]),p},[i,e,o,s]),I=J(a=>{h(l=>l.filter(n=>n.id!==a))},[]),v=J(()=>{h([])},[]),c={showNotification:S,hideNotification:I,clearAllNotifications:v};return ei(xe.Provider,{value:c,children:[r,o&&G(We,{children:G(Ze,{sx:{position:"fixed",zIndex:9999,[t.vertical]:(t.vertical==="top",24),[t.horizontal]:t.horizontal==="right"||t.horizontal==="left"?24:"50%",...t.horizontal==="center"&&{transform:"translateX(-50%)"},display:"flex",flexDirection:t.vertical==="top"?"column":"column-reverse",gap:1,maxWidth:"400px",width:"auto"},children:f.map(a=>G(Qe,{notification:a,onClose:()=>I(a.id)},a.id))})})]})},Qe=({notification:r,onClose:i})=>{let[e,t]=ke(!0),o=J((s,f)=>{f!=="clickaway"&&(t(!1),setTimeout(i,300))},[i]);return Ye(()=>{if(!r.persistent&&r.autoHideDuration){let s=setTimeout(()=>{o()},r.autoHideDuration);return()=>clearTimeout(s)}},[r.autoHideDuration,r.persistent,o]),G(Be,{open:e,onClose:o,sx:{position:"relative","& .MuiSnackbarContent-root":{minWidth:"auto"}},TransitionProps:{enter:!0,exit:!0},children:G(Xe,{variant:"filled",severity:r.severity,onClose:o,sx:{width:"100%",minWidth:"280px",maxWidth:"400px",wordBreak:"break-word"},children:r.allowHtml?G("span",{dangerouslySetInnerHTML:{__html:je(r.message)}}):G("span",{children:r.message})})})},Se=()=>{let r=Ve(xe);if(!r)throw new Error("useGlobalNotification debe ser usado dentro de un GlobalNotificationProvider");return r};import ii,{createContext as ti,useContext as ri,useMemo as le}from"react";import{Fragment as oi,jsx as N,jsxs as O}from"react/jsx-runtime";var Ne=ti(void 0);function Pe({children:r,options:i={},config:e,showNotifications:t=!1,notificationOptions:o={}}){let s;try{let{showNotification:n}=Se();s=n}catch{}let f={};try{let n=Ie();n.isInitialized&&n.adminCredentials&&(f=n.adminCredentials)}catch{}let h=le(()=>{let n=oe({publicApiKey:e?.publicApiKey,env:e?.env,enableDebug:i?.enableLogging});return{publicApiKey:n.publicApiKey,env:n.env||"prod"}},[e,i?.enableLogging]),S=ii.useMemo(()=>({...i,showNotification:s,apiEndpointAdmin:f.apiEndpointAdmin,apiKeyEndpointAdmin:f.apiKeyEndpointAdmin,publicApiKey:h.publicApiKey,env:h.env,onSessionExpired:()=>{i.onSessionExpired?.()}}),[i,s,f.apiEndpointAdmin,f.apiKeyEndpointAdmin,h]),I=be(S),v=le(()=>{let n=oe({publicApiKey:e?.publicApiKey,env:e?.env,appName:e?.appName,logo:e?.logo,loginActions:e?.loginActions,enableDebug:i?.enableLogging});return{publicApiKey:n.publicApiKey,env:n.env,appName:n.appName,loginActions:n.loginActions,logo:n.logo}},[e,i?.enableLogging]),c=le(()=>{if(!I.tokens?.accessToken||!I.isAuthenticated)return null;try{let n=me(I.tokens.accessToken);if(n&&n.sub&&n.email&&n.subscriber){let p={_id:n.sub,email:n.email,subscriberKey:n.subscriber};return Object.keys(n).forEach(T=>{["sub","email","subscriber"].includes(T)||(p[T]=n[T])}),p}}catch(n){console.error("Error decoding JWT token for sessionData:",n)}return null},[I.tokens?.accessToken,I.isAuthenticated]),a={...I,sessionData:c,config:v},l={enabled:t,maxNotifications:o.maxNotifications||5,defaultAutoHideDuration:o.defaultAutoHideDuration||6e3,position:o.position||{vertical:"top",horizontal:"right"}};return N(Ne.Provider,{value:a,children:r})}function ji(r){let i={enabled:r.showNotifications,maxNotifications:r.notificationOptions?.maxNotifications||5,defaultAutoHideDuration:r.notificationOptions?.defaultAutoHideDuration||6e3,position:r.notificationOptions?.position||{vertical:"top",horizontal:"right"},allowHtml:r.notificationOptions?.allowHtml||!1};return r.config?.publicApiKey?N(Ae,{config:{publicApiKey:r.config.publicApiKey,env:r.config.env||"prod",appName:r.config.appName,loginActions:r.config.loginActions,logo:r.config.logo},children:N(ae,{...i,children:N(Pe,{...r})})}):N(ae,{...i,children:N(Pe,{...r})})}function ni(){let r=ri(Ne);if(r===void 0)throw new Error("useSessionContext must be used within a SessionProvider");return r}function Qi(){let r=ni();return r.isInitialized?O("div",{style:{padding:"10px",margin:"10px",border:"1px solid #ccc",borderRadius:"4px",fontSize:"12px",fontFamily:"monospace"},children:[N("h4",{children:"Session Debug Info"}),O("div",{children:[N("strong",{children:"Authenticated:"})," ",r.isAuthenticated?"Yes":"No"]}),O("div",{children:[N("strong",{children:"Loading:"})," ",r.isLoading?"Yes":"No"]}),O("div",{children:[N("strong",{children:"Error:"})," ",r.error||"None"]}),r.tokens&&O(oi,{children:[O("div",{children:[N("strong",{children:"Access Token:"})," ",r.tokens.accessToken.substring(0,20),"..."]}),O("div",{children:[N("strong",{children:"Refresh Token:"})," ",r.tokens.refreshToken.substring(0,20),"..."]}),O("div",{children:[N("strong",{children:"Access Expires In:"})," ",Math.round(r.expiresIn/1e3/60)," minutes"]}),O("div",{children:[N("strong",{children:"Refresh Expires In:"})," ",Math.round(r.refreshExpiresIn/1e3/60/60)," hours"]}),O("div",{children:[N("strong",{children:"Expiring Soon:"})," ",r.isExpiringSoon?"Yes":"No"]})]})]}):N("div",{children:"Session not initialized"})}import{useState as j,useEffect as Re,useCallback as we,useRef as Q}from"react";import si from"@nocios/crudify-browser";var ot=(r={})=>{let{autoFetch:i=!0,retryOnError:e=!1,maxRetries:t=3}=r,[o,s]=j(null),[f,h]=j(!1),[S,I]=j(null),[v,c]=j({}),a=Q(null),l=Q(!0),n=Q(0),p=Q(0),T=we(()=>{s(null),I(null),h(!1),c({})},[]),k=we(async()=>{let C=Te();if(!C){l.current&&(I("No user email available"),h(!1));return}a.current&&a.current.abort();let b=new AbortController;a.current=b;let P=++n.current;try{l.current&&(h(!0),I(null));let z=await si.readItems("users",{filter:{email:C},pagination:{limit:1}});if(P===n.current&&l.current&&!b.signal.aborted)if(z.success&&z.data&&z.data.length>0){let E=z.data[0];s(E);let _={fullProfile:E,totalFields:Object.keys(E).length,displayData:{id:E.id,email:E.email,username:E.username,firstName:E.firstName,lastName:E.lastName,fullName:E.fullName||`${E.firstName||""} ${E.lastName||""}`.trim(),role:E.role,permissions:E.permissions||[],isActive:E.isActive,lastLogin:E.lastLogin,createdAt:E.createdAt,updatedAt:E.updatedAt,...Object.keys(E).filter(H=>!["id","email","username","firstName","lastName","fullName","role","permissions","isActive","lastLogin","createdAt","updatedAt"].includes(H)).reduce((H,$)=>({...H,[$]:E[$]}),{})}};c(_),I(null),p.current=0}else I("User profile not found"),s(null),c({})}catch(z){if(P===n.current&&l.current){let E=z;if(E.name==="AbortError")return;e&&p.current<t&&(E.message?.includes("Network Error")||E.message?.includes("Failed to fetch"))?(p.current++,setTimeout(()=>{l.current&&k()},1e3*p.current)):(I("Failed to load user profile"),s(null),c({}))}}finally{P===n.current&&l.current&&h(!1),a.current===b&&(a.current=null)}},[e,t]);return Re(()=>{i&&k()},[i,k]),Re(()=>(l.current=!0,()=>{l.current=!1,a.current&&(a.current.abort(),a.current=null)}),[]),{userProfile:o,loading:f,error:S,extendedData:v,refreshProfile:k,clearProfile:T}};import{useState as ce,useEffect as ai,useCallback as ee,useRef as li}from"react";import ci from"@nocios/crudify-browser";var ct=(r,i={})=>{let{autoFetch:e=!0,onSuccess:t,onError:o}=i,{prefix:s,padding:f=0,separator:h=""}=r,[S,I]=ce(""),[v,c]=ce(!1),[a,l]=ce(null),n=li(!1),p=ee(b=>{let P=String(b).padStart(f,"0");return`${s}${h}${P}`},[s,f,h]),T=ee(async()=>{c(!0),l(null);try{let b=await ci.getNextSequence(s);if(b.success&&b.data?.value){let P=p(b.data.value);I(P),t?.(P)}else{let P=b.errors?._error?.[0]||"Failed to generate code";l(P),o?.(P)}}catch(b){let P=b instanceof Error?b.message:"Unknown error";l(P),o?.(P)}finally{c(!1)}},[s,p,t,o]),k=ee(async()=>{await T()},[T]),C=ee(()=>{l(null)},[]);return ai(()=>{e&&!S&&!n.current&&(n.current=!0,T())},[e,S,T]),{value:S,loading:v,error:a,regenerate:k,clearError:C}};import ue from"@nocios/crudify-browser";var de=class r{constructor(){this.state={status:"UNINITIALIZED",priority:null,publicApiKey:null,env:null,error:null,initializedBy:null};this.initializationPromise=null;this.highPriorityInitializerPresent=!1;this.waitingForHighPriority=new Set;this.HIGH_PRIORITY_WAIT_TIMEOUT=100}static getInstance(){return r.instance||(r.instance=new r),r.instance}registerHighPriorityInitializer(){this.highPriorityInitializerPresent=!0}isHighPriorityInitializerPresent(){return this.highPriorityInitializerPresent}getState(){return{...this.state}}async initialize(i){let{priority:e,publicApiKey:t,env:o,enableLogging:s,requestedBy:f}=i;if(this.state.status==="INITIALIZED"){this.state.publicApiKey!==t&&console.warn(`[CrudifyInitialization] ${f} attempted to initialize with different key. Already initialized with key: ${this.state.publicApiKey?.slice(0,10)}... by ${this.state.initializedBy}`);return}if(this.initializationPromise)return s&&console.log(`[CrudifyInitialization] ${f} waiting for ongoing initialization...`),this.initializationPromise;if(e==="LOW"&&this.highPriorityInitializerPresent&&this.state.status==="UNINITIALIZED"){if(s&&console.log(`[CrudifyInitialization] ${f} (LOW priority) waiting for HIGH priority initializer...`),this.waitingForHighPriority.add(f),await this.waitForHighPriorityOrTimeout(s),this.waitingForHighPriority.delete(f),this.getState().status==="INITIALIZED"){s&&console.log(`[CrudifyInitialization] ${f} found initialization completed by HIGH priority`);return}s&&console.warn(`[CrudifyInitialization] ${f} timeout waiting for HIGH priority, initializing with LOW priority`)}e==="HIGH"&&this.state.status==="INITIALIZING"&&this.state.priority==="LOW"&&(console.warn(`[CrudifyInitialization] HIGH priority request from ${f} interrupting LOW priority initialization by ${this.state.initializedBy}`),this.state.status="UNINITIALIZED",this.initializationPromise=null),s&&console.log(`[CrudifyInitialization] ${f} starting initialization (${e} priority)...`),this.state.status="INITIALIZING",this.state.priority=e,this.state.initializedBy=f,this.initializationPromise=this.performInitialization(t,o,s);try{await this.initializationPromise,this.state.status="INITIALIZED",this.state.publicApiKey=t,this.state.env=o,this.state.error=null,s&&console.log(`[CrudifyInitialization] \u2705 Successfully initialized by ${f} (${e} priority)`)}catch(h){throw this.state.status="ERROR",this.state.error=h instanceof Error?h:new Error(String(h)),this.initializationPromise=null,console.error(`[CrudifyInitialization] \u274C Initialization failed for ${f}:`,h),h}}async waitForHighPriorityOrTimeout(i){return new Promise(e=>{let o=0,s=setInterval(()=>{if(o+=10,this.state.status==="INITIALIZED"&&this.state.priority==="HIGH"){clearInterval(s),e();return}if(this.state.status==="INITIALIZING"&&this.state.priority==="HIGH"){o=0;return}o>=this.HIGH_PRIORITY_WAIT_TIMEOUT&&(clearInterval(s),i&&console.log(`[CrudifyInitialization] Timeout waiting for HIGH priority (${this.HIGH_PRIORITY_WAIT_TIMEOUT}ms)`),e())},10)})}async performInitialization(i,e,t){let o=ue.getTokenData();if(o&&o.endpoint){t&&console.log("[CrudifyInitialization] SDK already initialized externally");return}ue.config(e);let s=t?"debug":"none",f=await ue.init(i,s);if(f.success===!1)throw new Error(`Crudify initialization failed: ${JSON.stringify(f.errors||"Unknown error")}`)}reset(){this.state={status:"UNINITIALIZED",priority:null,publicApiKey:null,env:null,error:null,initializedBy:null},this.initializationPromise=null,this.highPriorityInitializerPresent=!1,this.waitingForHighPriority.clear()}isInitialized(){return this.state.status==="INITIALIZED"}getDiagnostics(){return{...this.state,waitingCount:this.waitingForHighPriority.size,waitingComponents:Array.from(this.waitingForHighPriority),hasActivePromise:this.initializationPromise!==null}}},ie=de.getInstance();import{useState as Ce,useCallback as D,useRef as ui,useMemo as te}from"react";import fe from"@nocios/crudify-browser";var Le=()=>`file_${Date.now()}_${Math.random().toString(36).substring(2,9)}`,ht=(r={})=>{let{acceptedTypes:i,maxFileSize:e=10*1024*1024,maxFiles:t,minFiles:o=0,visibility:s="private",onUploadComplete:f,onUploadError:h,onFileRemoved:S,onFilesChange:I}=r,[v,c]=Ce([]),[a,l]=Ce(!1),n=ui(new Map),p=D(()=>{l(!0)},[]),T=D((u,y)=>{c(g=>g.map(m=>m.id===u?{...m,...y}:m))},[]),k=D(u=>{I?.(u)},[I]),C=D(u=>i&&i.length>0&&!i.includes(u.type)?{valid:!1,error:`Tipo de archivo no permitido: ${u.type}`}:u.size>e?{valid:!1,error:`El archivo excede el tama\xF1o m\xE1ximo de ${(e/1048576).toFixed(1)}MB`}:{valid:!0},[i,e]),b=D(async(u,y)=>{try{if(!ie.isInitialized())throw new Error("Crudify no est\xE1 inicializado. Por favor espere a que la aplicaci\xF3n termine de cargar.");let g=await fe.generateSignedUrl({fileName:y.name,contentType:y.type,visibility:s});if(!g.success||!g.data)throw new Error("No se pudo obtener URL de upload");let{uploadUrl:R,s3Key:m,publicUrl:x}=g.data;if(!R||!m)throw new Error("Respuesta de signed URL incompleta");let U=m.indexOf("/"),Ke=U>0?m.substring(U+1):m;T(u.id,{status:"uploading",progress:0}),await new Promise((X,V)=>{let L=new XMLHttpRequest;L.upload.addEventListener("progress",ne=>{if(ne.lengthComputable){let Oe=Math.round(ne.loaded/ne.total*100);T(u.id,{progress:Oe})}}),L.addEventListener("load",()=>{L.status>=200&&L.status<300?X():V(new Error(`Upload fall\xF3 con status ${L.status}`))}),L.addEventListener("error",()=>{V(new Error("Error de red durante el upload"))}),L.addEventListener("abort",()=>{V(new Error("Upload cancelado"))}),L.open("PUT",R),L.setRequestHeader("Content-Type",y.type),L.send(y)});let pe={status:"completed",progress:100,filePath:Ke,visibility:s,publicUrl:s==="public"?x:void 0,file:void 0};T(u.id,pe),c(X=>{let V=X.find(L=>L.id===u.id);return V&&f?.({...V,...pe}),X})}catch(g){let R=g instanceof Error?g.message:"Error desconocido";T(u.id,{status:"error",progress:0,errorMessage:R}),c(m=>{let x=m.find(U=>U.id===u.id);return x&&h?.(x,R),m})}},[T,f,h,s]),P=D(async u=>{let y=Array.from(u);if(t!==void 0){let m=v.filter(U=>U.status!=="error").length,x=t-m;if(x<=0){console.warn(`Ya se alcanz\xF3 el l\xEDmite de ${t} archivos`);return}y.length>x&&(y.splice(x),console.warn(`Solo se agregar\xE1n ${x} archivos para no exceder el l\xEDmite`))}let g=[];for(let m of y){let x=C(m),U={id:Le(),name:m.name,size:m.size,contentType:m.type,status:x.valid?"pending":"error",progress:0,createdAt:Date.now(),file:x.valid?m:void 0,errorMessage:x.error};g.push(U)}c(m=>{let x=[...m,...g];return k(x),x});let R=g.filter(m=>m.status==="pending"&&m.file);for(let m of R)if(m.file){let x=b(m,m.file);n.current.set(m.id,x),x.finally(()=>{n.current.delete(m.id)})}},[v,t,C,b,k]),z=D(async u=>{let y=v.find(g=>g.id===u);if(!y)return!1;T(u,{status:"removing"});try{if(y.filePath){if(!ie.isInitialized())throw new Error("Crudify no est\xE1 inicializado. Por favor espere a que la aplicaci\xF3n termine de cargar.");if(!(await fe.disableFile({filePath:y.filePath})).success)throw new Error("No se pudo eliminar el archivo del servidor")}return c(g=>{let R=g.filter(m=>m.id!==u);return k(R),R}),S?.(y),!0}catch(g){return T(u,{status:y.filePath?"completed":"error",errorMessage:g instanceof Error?g.message:"Error al eliminar"}),!1}},[v,T,k,S]),E=D(()=>{c([]),k([])},[k]),_=D(async u=>{let y=v.find(R=>R.id===u);if(!y||y.status!=="error"||!y.file){console.warn("No se puede reintentar: archivo no encontrado o sin archivo original");return}T(u,{status:"pending",progress:0,errorMessage:void 0});let g=b(y,y.file);n.current.set(u,g),g.finally(()=>{n.current.delete(u)})},[v,T,b]),H=D(async()=>{let u=Array.from(n.current.values());u.length>0&&await Promise.allSettled(u)},[]),$=D(u=>{let y=u.map(g=>{let R=g.filePath.startsWith("public/")?"public":"private";return{id:Le(),name:g.name,size:g.size||0,contentType:g.contentType||"application/octet-stream",status:"completed",progress:100,filePath:g.filePath,visibility:R,createdAt:Date.now()}});c(y),k(y)},[k]),ge=D(async u=>{let y=v.find(g=>g.id===u);if(!y||!y.filePath)return null;if(y.visibility==="public"&&y.publicUrl)return y.publicUrl;try{if(!ie.isInitialized())return null;let g=await fe.getFileUrl({filePath:y.filePath,expiresIn:3600});return g.success&&g.data?.url?g.data.url:null}catch{return null}},[v]),F=te(()=>v.some(u=>u.status==="uploading"||u.status==="pending"),[v]),re=te(()=>v.filter(u=>u.status==="uploading"||u.status==="pending").length,[v]),De=te(()=>v.filter(u=>u.status==="completed"&&u.filePath).map(u=>u.filePath),[v]),{isValid:ze,validationError:Fe}=te(()=>{let u=v.filter(g=>g.status==="completed").length;return u<o?{isValid:!1,validationError:o===1?"Se requiere al menos un archivo":`Se requieren al menos ${o} archivos`}:t!==void 0&&u>t?{isValid:!1,validationError:`M\xE1ximo ${t} archivos permitidos`}:v.some(g=>g.status==="error")?{isValid:!1,validationError:"Algunos archivos tienen errores"}:{isValid:!0,validationError:null}},[v,o,t]);return{files:v,isUploading:F,pendingCount:re,addFiles:P,removeFile:z,clearFiles:E,retryUpload:_,isValid:ze,validationError:Fe,waitForUploads:H,completedFilePaths:De,initializeFiles:$,isTouched:a,markAsTouched:p,getPreviewUrl:ge}};export{ve as a,Ae as b,Ie as c,A as d,W as e,be as f,ae as g,Se as h,ji as i,ni as j,Qi as k,ot as l,ct as m,de as n,ie as o,ht as p};
|
|
1
|
+
import{b as oe,d as ye,h as K,i as he,j as me,k as ve}from"./chunk-6GPSBDW6.mjs";import{createContext as He,useContext as Me,useEffect as Ge,useState as B}from"react";import X from"@nocios/crudify-browser";var se=class r{constructor(){this.listeners=[];this.credentials=null;this.isReady=!1}static getInstance(){return r.instance||(r.instance=new r),r.instance}notifyCredentialsReady(i){this.credentials=i,this.isReady=!0,this.listeners.forEach(e=>{try{e(i)}catch(t){console.error("[CredentialsEventBus] Error in listener:",t)}}),this.listeners=[]}waitForCredentials(){return this.isReady&&this.credentials?Promise.resolve(this.credentials):new Promise(i=>{this.listeners.push(i)})}reset(){this.credentials=null,this.isReady=!1,this.listeners=[]}areCredentialsReady(){return this.isReady&&this.credentials!==null}},Te=se.getInstance();import{jsx as $e}from"react/jsx-runtime";var Ee=He(void 0),Ae=({config:r,children:i})=>{let[e,t]=B(!0),[n,s]=B(null),[f,h]=B(!1),[S,I]=B(""),[m,c]=B();Ge(()=>{if(!r.publicApiKey){s("No publicApiKey provided"),t(!1),h(!1);return}let l=`${r.publicApiKey}-${r.env}`;if(l===S&&f){t(!1);return}(async()=>{t(!0),s(null),h(!1);try{X.config(r.env||"prod");let p=await X.init(r.publicApiKey,"none");if(c(p),typeof X.transaction=="function"&&typeof X.login=="function")h(!0),I(l),p.apiEndpointAdmin&&p.apiKeyEndpointAdmin&&Te.notifyCredentialsReady({apiUrl:p.apiEndpointAdmin,apiKey:p.apiKeyEndpointAdmin});else throw new Error("Crudify methods not properly initialized")}catch(p){let v=p instanceof Error?p.message:"Failed to initialize Crudify";console.error("[CrudifyProvider] Initialization error:",p),s(v),h(!1)}finally{t(!1)}})()},[r.publicApiKey,r.env,S,f]);let a={crudify:f?X:null,isLoading:e,error:n,isInitialized:f,adminCredentials:m};return $e(Ee.Provider,{value:a,children:i})},Ie=()=>{let r=Me(Ee);if(r===void 0)throw new Error("useCrudify must be used within a CrudifyProvider");return r};import Z from"crypto-js";var d=class d{static setStorageType(i){d.storageType=i}static generateEncryptionKey(){let i=[navigator.userAgent,navigator.language,navigator.platform,screen.width,screen.height,Date.now().toString(),Math.random().toString(36)].join("|");return Z.SHA256(i).toString()}static getEncryptionKey(){if(d.encryptionKey)return d.encryptionKey;let i=window.localStorage;if(!i)return d.encryptionKey=d.generateEncryptionKey(),d.encryptionKey;try{let e=i.getItem(d.ENCRYPTION_KEY_STORAGE);return(!e||e.length<32)&&(e=d.generateEncryptionKey(),i.setItem(d.ENCRYPTION_KEY_STORAGE,e)),d.encryptionKey=e,e}catch{return console.warn("Crudify: Cannot persist encryption key, using temporary key"),d.encryptionKey=d.generateEncryptionKey(),d.encryptionKey}}static isStorageAvailable(i){try{let e=window[i],t="__storage_test__";return e.setItem(t,"test"),e.removeItem(t),!0}catch{return!1}}static getStorage(){return d.storageType==="none"?null:d.isStorageAvailable(d.storageType)?window[d.storageType]:(console.warn(`Crudify: ${d.storageType} not available, tokens won't persist`),null)}static encrypt(i){try{let e=d.getEncryptionKey();return Z.AES.encrypt(i,e).toString()}catch(e){return console.error("Crudify: Encryption failed",e),i}}static decrypt(i){try{let e=d.getEncryptionKey();return Z.AES.decrypt(i,e).toString(Z.enc.Utf8)||i}catch(e){return console.error("Crudify: Decryption failed",e),i}}static saveTokens(i){let e=d.getStorage();if(e)try{let t={accessToken:i.accessToken,refreshToken:i.refreshToken,expiresAt:i.expiresAt,refreshExpiresAt:i.refreshExpiresAt,savedAt:Date.now()},n=d.encrypt(JSON.stringify(t));e.setItem(d.TOKEN_KEY,n),console.debug("Crudify: Tokens saved successfully")}catch(t){console.error("Crudify: Failed to save tokens",t)}}static getTokens(){let i=d.getStorage();if(!i)return null;try{let e=i.getItem(d.TOKEN_KEY);if(!e)return null;let t=d.decrypt(e),n=JSON.parse(t);return!n.accessToken||!n.refreshToken||!n.expiresAt||!n.refreshExpiresAt?(console.warn("Crudify: Incomplete token data found, clearing storage"),d.clearTokens(),null):Date.now()>=n.refreshExpiresAt?(console.info("Crudify: Refresh token expired, clearing storage"),d.clearTokens(),null):{accessToken:n.accessToken,refreshToken:n.refreshToken,expiresAt:n.expiresAt,refreshExpiresAt:n.refreshExpiresAt}}catch(e){return console.error("Crudify: Failed to retrieve tokens",e),d.clearTokens(),null}}static clearTokens(){let i=d.getStorage();if(i)try{i.removeItem(d.TOKEN_KEY),console.debug("Crudify: Tokens cleared from storage")}catch(e){console.error("Crudify: Failed to clear tokens",e)}}static rotateEncryptionKey(){try{d.clearTokens(),d.encryptionKey=null;let i=window.localStorage;i&&i.removeItem(d.ENCRYPTION_KEY_STORAGE),console.info("Crudify: Encryption key rotated successfully")}catch(i){console.error("Crudify: Failed to rotate encryption key",i)}}static hasValidTokens(){return d.getTokens()!==null}static getExpirationInfo(){let i=d.getTokens();if(!i)return null;let e=Date.now();return{accessExpired:e>=i.expiresAt,refreshExpired:e>=i.refreshExpiresAt,accessExpiresIn:Math.max(0,i.expiresAt-e),refreshExpiresIn:Math.max(0,i.refreshExpiresAt-e)}}static updateAccessToken(i,e){let t=d.getTokens();if(!t){console.warn("Crudify: Cannot update access token, no existing tokens found");return}d.saveTokens({...t,accessToken:i,expiresAt:e})}static subscribeToChanges(i){let e=t=>{if(t.key===d.TOKEN_KEY){if(t.newValue===null){console.debug("Crudify: Tokens removed in another tab"),i(null);return}if(t.newValue){console.debug("Crudify: Tokens updated in another tab");let n=d.getTokens();i(n)}}};return window.addEventListener("storage",e),()=>{window.removeEventListener("storage",e)}}};d.TOKEN_KEY="crudify_tokens",d.ENCRYPTION_KEY_STORAGE="crudify_enc_key",d.encryptionKey=null,d.storageType="localStorage";var A=d;import w from"@nocios/crudify-browser";var W=class r{constructor(){this.config={};this.initialized=!1;this.crudifyInitialized=!1;this.lastActivityTime=0;this.isRefreshingLocally=!1;this.refreshPromise=null}static getInstance(){return r.instance||(r.instance=new r),r.instance}async initialize(i={}){if(!this.initialized){if(this.config={storageType:"localStorage",autoRestore:!0,enableLogging:!1,env:"stg",...i},A.setStorageType(this.config.storageType||"localStorage"),this.config.publicApiKey&&!this.crudifyInitialized&&await this.ensureCrudifyInitialized(),w.setTokenInvalidationCallback(()=>{this.log("Tokens invalidated by crudify-core"),K.emit("SESSION_EXPIRED",{message:"Your session has expired. Please log in again.",source:"crudify-core.clearTokensAndRefreshState"})}),this.config.apiEndpointAdmin&&this.config.apiKeyEndpointAdmin){let e=A.getTokens();e?A.saveTokens({...e,apiEndpointAdmin:this.config.apiEndpointAdmin,apiKeyEndpointAdmin:this.config.apiKeyEndpointAdmin}):A.saveTokens({accessToken:"",refreshToken:"",expiresAt:0,refreshExpiresAt:0,apiEndpointAdmin:this.config.apiEndpointAdmin,apiKeyEndpointAdmin:this.config.apiKeyEndpointAdmin})}this.config.autoRestore&&await this.restoreSession(),this.initialized=!0}}async login(i,e){try{let t=await w.login(i,e);if(!t.success)return{success:!1,error:this.formatError(t.errors),rawResponse:t};let n=A.getTokens(),s={accessToken:t.data.token,refreshToken:t.data.refreshToken,expiresAt:t.data.expiresAt,refreshExpiresAt:t.data.refreshExpiresAt,apiEndpointAdmin:n?.apiEndpointAdmin||this.config.apiEndpointAdmin,apiKeyEndpointAdmin:n?.apiKeyEndpointAdmin||this.config.apiKeyEndpointAdmin};return A.saveTokens(s),this.lastActivityTime=Date.now(),this.config.onLoginSuccess?.(s),{success:!0,tokens:s,data:t.data}}catch(t){return console.error("[SessionManager] Login error:",t),{success:!1,error:t instanceof Error?t.message:"Unknown error"}}}async logout(){try{this.log("Logging out..."),await w.logout(),A.clearTokens(),this.log("Logout successful"),this.config.onLogout?.()}catch(i){this.log("Logout error:",i),A.clearTokens()}}async restoreSession(){try{this.log("Attempting to restore session...");let i=A.getTokens();if(!i)return this.log("No valid tokens found in storage"),!1;if(Date.now()>=i.refreshExpiresAt)return this.log("Refresh token expired, clearing storage"),A.clearTokens(),!1;if(w.setTokens({accessToken:i.accessToken,refreshToken:i.refreshToken,expiresAt:i.expiresAt,refreshExpiresAt:i.refreshExpiresAt}),w.getTokenData().isValid===!1){if(this.log("Restored access token is invalid or expired"),Date.now()<i.refreshExpiresAt&&(this.log("Access token expired but refresh is valid, attempting refresh..."),await this.refreshTokens())){this.log("Session restored successfully via token refresh");let n=A.getTokens();return n&&this.config.onSessionRestored?.(n),!0}return A.clearTokens(),await w.logout(),!1}return this.log("Session restored successfully"),this.lastActivityTime=Date.now(),this.config.onSessionRestored?.(i),!0}catch(i){return this.log("Session restore error:",i),A.clearTokens(),await w.logout(),!1}}isAuthenticated(){return w.isLogin()||A.hasValidTokens()}getTokenInfo(){let i=w.getTokenData(),e=A.getExpirationInfo(),t=A.getTokens();return{isLoggedIn:this.isAuthenticated(),crudifyTokens:i,storageInfo:e,hasValidTokens:A.hasValidTokens(),apiEndpointAdmin:t?.apiEndpointAdmin,apiKeyEndpointAdmin:t?.apiKeyEndpointAdmin}}async refreshTokens(){if(this.isRefreshingLocally&&this.refreshPromise)return this.log("Refresh already in progress, waiting for existing promise..."),this.refreshPromise;this.isRefreshingLocally=!0,this.refreshPromise=this._performRefresh();try{return await this.refreshPromise}finally{this.isRefreshingLocally=!1,this.refreshPromise=null}}async _performRefresh(){try{this.log("Starting token refresh...");let i=await w.refreshAccessToken();if(!i.success)return this.log("Token refresh failed:",i.errors),A.clearTokens(),this.config.showNotification?.(this.getSessionExpiredMessage(),"warning"),this.config.onSessionExpired?.(),!1;let e={accessToken:i.data.token,refreshToken:i.data.refreshToken,expiresAt:i.data.expiresAt,refreshExpiresAt:i.data.refreshExpiresAt};return A.saveTokens(e),this.log("Tokens refreshed and saved successfully"),this.lastActivityTime=Date.now(),!0}catch(i){return this.log("Token refresh error:",i),A.clearTokens(),this.config.showNotification?.(this.getSessionExpiredMessage(),"warning"),this.config.onSessionExpired?.(),!1}}isRefreshing(){return this.isRefreshingLocally}setupResponseInterceptor(){w.setResponseInterceptor(async i=>{this.updateLastActivity();let e=this.detectAuthorizationError(i);if(e.isAuthError){if(this.log("\u{1F6A8} Authorization error detected:",{errorType:e.errorType,shouldLogout:e.shouldTriggerLogout}),e.isRefreshTokenInvalid||e.isTokenRefreshFailed)return this.log("Refresh token invalid, emitting TOKEN_REFRESH_FAILED event"),K.emit("TOKEN_REFRESH_FAILED",{message:e.userFriendlyMessage,error:e.errorDetails,source:"SessionManager.setupResponseInterceptor"}),i;e.shouldTriggerLogout&&(A.hasValidTokens()&&!e.isIrrecoverable?(this.log("Access token expired, emitting TOKEN_EXPIRED event"),K.emit("TOKEN_EXPIRED",{message:"Access token expired, refresh needed",error:e.errorDetails,source:"SessionManager.setupResponseInterceptor"})):(this.log("No valid tokens or irrecoverable error, emitting SESSION_EXPIRED event"),K.emit("SESSION_EXPIRED",{message:e.userFriendlyMessage,error:e.errorDetails,source:"SessionManager.setupResponseInterceptor"})))}return i}),this.log("Response interceptor configured (non-blocking mode)")}async ensureCrudifyInitialized(){if(!this.crudifyInitialized)try{this.log("Initializing crudify SDK...");let i=w.getTokenData();if(i&&i.endpoint){this.log("Crudify already initialized by another service"),this.crudifyInitialized=!0;return}let e=this.config.env||"stg";w.config(e);let t=this.config.publicApiKey,n=this.config.enableLogging?"debug":"none",s=await w.init(t,n);if(s&&s.success===!1&&s.errors)throw new Error(`Failed to initialize crudify: ${JSON.stringify(s.errors)}`);this.crudifyInitialized=!0,this.log("Crudify SDK initialized successfully")}catch(i){throw console.error("[SessionManager] Failed to initialize crudify:",i),i}}detectAuthorizationError(i){let e={isAuthError:!1,isRefreshTokenInvalid:!1,isTokenRefreshFailed:!1,isTokenExpired:!1,isUnauthorized:!1,isIrrecoverable:!1,shouldTriggerLogout:!1,errorType:"",errorDetails:null,userFriendlyMessage:""};if(i.errors&&Array.isArray(i.errors)){let t=i.errors.find(n=>n.errorType==="Unauthorized"||n.message?.includes("Unauthorized")||n.message?.includes("Not Authorized")||n.message?.includes("NOT_AUTHORIZED")||n.message?.includes("Token")||n.message?.includes("TOKEN")||n.message?.includes("Authentication")||n.message?.includes("UNAUTHENTICATED")||n.extensions?.code==="UNAUTHENTICATED"||n.extensions?.code==="FORBIDDEN");t&&(e.isAuthError=!0,e.errorType="GraphQL Array",e.errorDetails=t,e.shouldTriggerLogout=!0,e.userFriendlyMessage="Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente.",(t.message?.includes("TOKEN")||t.message?.includes("Token"))&&(e.isTokenExpired=!0),t.extensions?.code==="UNAUTHENTICATED"&&(e.isUnauthorized=!0))}if(!e.isAuthError&&i.errors&&typeof i.errors=="object"&&!Array.isArray(i.errors)){let n=Object.values(i.errors).flat().find(s=>typeof s=="string"&&(s.includes("NOT_AUTHORIZED")||s.includes("TOKEN_REFRESH_FAILED")||s.includes("TOKEN_HAS_EXPIRED")||s.includes("PLEASE_LOGIN")||s.includes("Unauthorized")||s.includes("UNAUTHENTICATED")||s.includes("SESSION_EXPIRED")||s.includes("INVALID_TOKEN")));n&&typeof n=="string"&&(e.isAuthError=!0,e.errorType="GraphQL Object",e.errorDetails=i.errors,e.shouldTriggerLogout=!0,n.includes("TOKEN_REFRESH_FAILED")?(e.isTokenRefreshFailed=!0,e.isRefreshTokenInvalid=!0,e.isIrrecoverable=!0,e.userFriendlyMessage="Tu sesi\xF3n ha caducado. Por favor, inicia sesi\xF3n nuevamente."):n.includes("TOKEN_HAS_EXPIRED")||n.includes("SESSION_EXPIRED")?(e.isTokenExpired=!0,e.userFriendlyMessage="Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente."):n.includes("INVALID_TOKEN")?(e.isTokenExpired=!0,e.isIrrecoverable=!0,e.userFriendlyMessage="Token inv\xE1lido. Por favor, inicia sesi\xF3n nuevamente."):e.userFriendlyMessage="Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente.")}if(!e.isAuthError&&i.data?.response?.status){let t=i.data.response.status.toUpperCase();(t==="UNAUTHORIZED"||t==="UNAUTHENTICATED")&&(e.isAuthError=!0,e.errorType="Status",e.errorDetails=i.data.response,e.isUnauthorized=!0,e.shouldTriggerLogout=!0,e.isIrrecoverable=!0,e.userFriendlyMessage="Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente.")}if(!e.isAuthError&&i.data?.response?.data)try{let t=typeof i.data.response.data=="string"?JSON.parse(i.data.response.data):i.data.response.data;(t.error==="REFRESH_TOKEN_INVALID"||t.error==="TOKEN_EXPIRED"||t.error==="INVALID_TOKEN")&&(e.isAuthError=!0,e.errorType="Parsed Data",e.errorDetails=t,e.shouldTriggerLogout=!0,e.isIrrecoverable=!0,t.error==="REFRESH_TOKEN_INVALID"?(e.isRefreshTokenInvalid=!0,e.isTokenRefreshFailed=!0,e.userFriendlyMessage="Tu sesi\xF3n ha caducado. Por favor, inicia sesi\xF3n nuevamente."):(e.isTokenExpired=!0,e.userFriendlyMessage="Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente."))}catch{}if(!e.isAuthError&&i.errorCode){let t=i.errorCode.toUpperCase();(t==="UNAUTHORIZED"||t==="UNAUTHENTICATED"||t==="TOKEN_EXPIRED"||t==="INVALID_TOKEN")&&(e.isAuthError=!0,e.errorType="Error Code",e.errorDetails={errorCode:t},e.shouldTriggerLogout=!0,t==="TOKEN_EXPIRED"?e.isTokenExpired=!0:e.isUnauthorized=!0,e.userFriendlyMessage="Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente.")}return e}updateLastActivity(){this.lastActivityTime=Date.now(),this.log("Last activity updated")}getTimeSinceLastActivity(){return this.lastActivityTime===0?0:Date.now()-this.lastActivityTime}checkInactivity(){let i=this.getTimeSinceLastActivity();if(this.lastActivityTime===0)return"none";let e=1800*1e3;return i>e?(this.log(`Inactivity timeout: ${Math.floor(i/6e4)} minutes since last activity`),"logout"):"none"}clearSession(){A.clearTokens(),w.logout(),this.lastActivityTime=0,this.log("Session cleared completely")}getSessionExpiredMessage(){return this.config.translateFn?ye("SESSION_EXPIRED",{translateFn:this.config.translateFn,enableDebug:this.config.enableLogging}):"Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente."}log(i,...e){this.config.enableLogging&&console.log(`[SessionManager] ${i}`,...e)}formatError(i){return i?typeof i=="string"?i:typeof i=="object"?Object.values(i).flat().join(", "):"Authentication failed":"Unknown error"}};import{useState as _e,useEffect as q,useCallback as $}from"react";function be(r={}){let[i,e]=_e({isAuthenticated:!1,isLoading:!0,isInitialized:!1,tokens:null,error:null}),t=W.getInstance(),n=$(async()=>{console.log("\u{1F535} [useSession] initialize() CALLED"),console.log("\u{1F50D} [useSession] options received:",{autoRestore:r.autoRestore,enableLogging:r.enableLogging,apiEndpointAdmin:r.apiEndpointAdmin,apiKeyEndpointAdmin:r.apiKeyEndpointAdmin});try{e(o=>({...o,isLoading:!0,error:null}));let c={autoRestore:r.autoRestore??!0,enableLogging:r.enableLogging??!1,showNotification:r.showNotification,translateFn:r.translateFn,apiEndpointAdmin:r.apiEndpointAdmin,apiKeyEndpointAdmin:r.apiKeyEndpointAdmin,publicApiKey:r.publicApiKey,env:r.env||"stg",onSessionExpired:()=>{e(o=>({...o,isAuthenticated:!1,tokens:null,error:"Session expired"})),r.onSessionExpired?.()},onSessionRestored:o=>{e(p=>({...p,isAuthenticated:!0,tokens:o,error:null})),r.onSessionRestored?.(o)},onLoginSuccess:o=>{e(p=>({...p,isAuthenticated:!0,tokens:o,error:null}))},onLogout:()=>{e(o=>({...o,isAuthenticated:!1,tokens:null,error:null}))}};console.log("\u{1F50D} [useSession] Calling sessionManager.initialize() with config:",c),await t.initialize(c),console.log("\u2705 [useSession] sessionManager.initialize() completed"),t.setupResponseInterceptor();let a=t.isAuthenticated(),l=t.getTokenInfo();console.log("\u{1F50D} [useSession] After initialize, isAuth:",a),console.log("\u{1F50D} [useSession] After initialize, tokenInfo:",l),e(o=>({...o,isAuthenticated:a,isInitialized:!0,isLoading:!1,tokens:l.crudifyTokens.accessToken?{accessToken:l.crudifyTokens.accessToken,refreshToken:l.crudifyTokens.refreshToken,expiresAt:l.crudifyTokens.expiresAt,refreshExpiresAt:l.crudifyTokens.refreshExpiresAt}:null}))}catch(c){let a=c instanceof Error?c.message:"Initialization failed";e(l=>({...l,isLoading:!1,isInitialized:!0,error:a}))}},[r.autoRestore,r.enableLogging,r.onSessionExpired,r.onSessionRestored]),s=$(async(c,a)=>{e(l=>({...l,isLoading:!0,error:null}));try{let l=await t.login(c,a);return l.success&&l.tokens?e(o=>({...o,isAuthenticated:!0,tokens:l.tokens,isLoading:!1,error:null})):e(o=>({...o,isAuthenticated:!1,tokens:null,isLoading:!1,error:null})),l}catch(l){let o=l instanceof Error?l.message:"Login failed",p=o.includes("INVALID_CREDENTIALS")||o.includes("Invalid email")||o.includes("Invalid password")||o.includes("credentials");return e(v=>({...v,isAuthenticated:!1,tokens:null,isLoading:!1,error:p?null:o})),{success:!1,error:o}}},[t]),f=$(async()=>{e(c=>({...c,isLoading:!0}));try{await t.logout(),e(c=>({...c,isAuthenticated:!1,tokens:null,isLoading:!1,error:null}))}catch(c){e(a=>({...a,isAuthenticated:!1,tokens:null,isLoading:!1,error:c instanceof Error?c.message:"Logout error"}))}},[t]),h=$(async()=>{try{let c=await t.refreshTokens();if(c){let a=t.getTokenInfo();e(l=>({...l,tokens:a.crudifyTokens.accessToken?{accessToken:a.crudifyTokens.accessToken,refreshToken:a.crudifyTokens.refreshToken,expiresAt:a.crudifyTokens.expiresAt,refreshExpiresAt:a.crudifyTokens.refreshExpiresAt}:null,error:null}))}else e(a=>({...a,isAuthenticated:!1,tokens:null,error:"Token refresh failed"}));return c}catch(c){return e(a=>({...a,isAuthenticated:!1,tokens:null,error:c instanceof Error?c.message:"Token refresh failed"})),!1}},[t]),S=$(()=>{e(c=>({...c,error:null}))},[]),I=$(()=>t.getTokenInfo(),[t]);q(()=>{n()},[n]),q(()=>{if(!i.isAuthenticated||!i.tokens)return;let c=he.getInstance(),a=()=>{t.updateLastActivity(),r.enableLogging&&console.log("\u{1F4CD} User navigating - activity updated")},l=c.subscribe(a);window.addEventListener("popstate",a);let o=()=>{let C=t.getTokenInfo().crudifyTokens.expiresIn||0;return C<300*1e3?30*1e3:C<1800*1e3?60*1e3:120*1e3},p,v=()=>{let k=o();p=setTimeout(async()=>{if(t.isRefreshing()){r.enableLogging&&console.log("\u23F8\uFE0F Refresh in progress, rescheduling check"),v();return}let C=t.getTokenInfo(),b=C.crudifyTokens.expiresIn||0,z=(C.crudifyTokens.expiresAt||0)-(Date.now()-b),E=z*.5;if(b>0&&b<=E){let Y=Math.round(b/z*100);if(r.enableLogging&&console.log(`\u{1F504} Token at ${Y}% of TTL (${Math.round(b/6e4)}min remaining), refreshing...`),e(F=>({...F,isLoading:!0})),await t.refreshTokens()){let F=t.getTokenInfo();e(re=>({...re,isLoading:!1,tokens:F.crudifyTokens.accessToken?{accessToken:F.crudifyTokens.accessToken,refreshToken:F.crudifyTokens.refreshToken,expiresAt:F.crudifyTokens.expiresAt,refreshExpiresAt:F.crudifyTokens.refreshExpiresAt}:null}))}else e(F=>({...F,isLoading:!1,isAuthenticated:!1,tokens:null}))}let V=t.getTimeSinceLastActivity(),H=1800*1e3;V>H?(r.enableLogging&&console.log("\u23F1\uFE0F Inactivity timeout (30min) - logging out"),await f()):v()},k)};return v(),()=>{clearTimeout(p),window.removeEventListener("popstate",a),l()}},[i.isAuthenticated,i.tokens,t,r.enableLogging,f]),q(()=>{let c=K.subscribe(async a=>{if(r.enableLogging&&console.log(`\u{1F4E2} useSession: Received auth event: ${a.type}`),a.type==="TOKEN_EXPIRED"){if(t.isRefreshing()){r.enableLogging&&console.log("\u23F8\uFE0F Refresh already in progress, skipping TOKEN_EXPIRED handler");return}r.enableLogging&&console.log("\u{1F504} Token expired, attempting refresh..."),e(l=>({...l,isLoading:!0}));try{if(await t.refreshTokens()){r.enableLogging&&console.log("\u2705 Token refreshed successfully");let o=t.getTokenInfo();e(p=>({...p,isLoading:!1,tokens:o.crudifyTokens.accessToken?{accessToken:o.crudifyTokens.accessToken,refreshToken:o.crudifyTokens.refreshToken,expiresAt:o.crudifyTokens.expiresAt,refreshExpiresAt:o.crudifyTokens.refreshExpiresAt}:null}))}else r.enableLogging&&console.log("\u274C Token refresh failed, session expired"),K.emit("SESSION_EXPIRED",{message:"Failed to refresh token after detecting expiration",source:"useSession.TOKEN_EXPIRED handler"})}catch(l){r.enableLogging&&console.error("\u274C Error during token refresh:",l),K.emit("SESSION_EXPIRED",{message:l instanceof Error?l.message:"Unknown error during refresh",source:"useSession.TOKEN_EXPIRED handler (error)"})}}(a.type==="SESSION_EXPIRED"||a.type==="TOKEN_REFRESH_FAILED")&&(r.enableLogging&&console.log(`\u{1F534} Session expired (${a.type}), logging out...`),e(l=>({...l,isAuthenticated:!1,tokens:null,isLoading:!1,error:a.details?.message||"Session expired"})),r.onSessionExpired?.())});return()=>c()},[r.enableLogging,r.onSessionExpired,t]),q(()=>{let c=A.subscribeToChanges(a=>{a?(r.enableLogging&&console.log("\u{1F504} Tokens updated in another tab"),e(l=>({...l,tokens:a,isAuthenticated:!0}))):(r.enableLogging&&console.log("\u{1F504} Logout detected in another tab"),e(l=>({...l,isAuthenticated:!1,tokens:null})),K.emit("SESSION_EXPIRED",{message:"Sesi\xF3n cerrada en otra pesta\xF1a",source:"CrossTabSync"}))});return()=>c()},[r.enableLogging]);let m=$(()=>{t.updateLastActivity()},[t]);return{...i,login:s,logout:f,refreshTokens:h,clearError:S,getTokenInfo:I,updateActivity:m,isExpiringSoon:i.tokens?i.tokens.expiresAt-Date.now()<300*1e3:!1,expiresIn:i.tokens?Math.max(0,i.tokens.expiresAt-Date.now()):0,refreshExpiresIn:i.tokens?Math.max(0,i.tokens.refreshExpiresAt-Date.now()):0}}import{useState as ke,createContext as Ve,useContext as Ye,useCallback as J,useEffect as Be}from"react";import{Snackbar as Xe,Alert as Ze,Box as We,Portal as qe}from"@mui/material";import{v4 as Je}from"uuid";import je from"dompurify";import{jsx as _,jsxs as ii}from"react/jsx-runtime";var xe=Ve(null),Qe=r=>je.sanitize(r,{ALLOWED_TAGS:["b","i","em","strong","br","span"],ALLOWED_ATTR:["class"],FORBID_TAGS:["script","iframe","object","embed"],FORBID_ATTR:["onload","onerror","onclick","onmouseover","onfocus","onblur"],WHOLE_DOCUMENT:!1,RETURN_DOM:!1,RETURN_DOM_FRAGMENT:!1,RETURN_TRUSTED_TYPE:!1}),ae=({children:r,maxNotifications:i=5,defaultAutoHideDuration:e=6e3,position:t={vertical:"top",horizontal:"right"},enabled:n=!1,allowHtml:s=!1})=>{let[f,h]=ke([]),S=J((a,l="info",o)=>{if(!n)return"";if(!a||typeof a!="string")return console.warn("\u26A0\uFE0F GlobalNotificationProvider: Invalid message provided"),"";a.length>1e3&&(console.warn("\u26A0\uFE0F GlobalNotificationProvider: Message too long, truncating"),a=a.substring(0,1e3)+"...");let p=Je(),v={id:p,message:a,severity:l,autoHideDuration:o?.autoHideDuration??e,persistent:o?.persistent??!1,allowHtml:o?.allowHtml??s};return h(k=>[...k.length>=i?k.slice(-(i-1)):k,v]),p},[i,e,n,s]),I=J(a=>{h(l=>l.filter(o=>o.id!==a))},[]),m=J(()=>{h([])},[]),c={showNotification:S,hideNotification:I,clearAllNotifications:m};return ii(xe.Provider,{value:c,children:[r,n&&_(qe,{children:_(We,{sx:{position:"fixed",zIndex:9999,[t.vertical]:(t.vertical==="top",24),[t.horizontal]:t.horizontal==="right"||t.horizontal==="left"?24:"50%",...t.horizontal==="center"&&{transform:"translateX(-50%)"},display:"flex",flexDirection:t.vertical==="top"?"column":"column-reverse",gap:1,maxWidth:"400px",width:"auto"},children:f.map(a=>_(ei,{notification:a,onClose:()=>I(a.id)},a.id))})})]})},ei=({notification:r,onClose:i})=>{let[e,t]=ke(!0),n=J((s,f)=>{f!=="clickaway"&&(t(!1),setTimeout(i,300))},[i]);return Be(()=>{if(!r.persistent&&r.autoHideDuration){let s=setTimeout(()=>{n()},r.autoHideDuration);return()=>clearTimeout(s)}},[r.autoHideDuration,r.persistent,n]),_(Xe,{open:e,onClose:n,sx:{position:"relative","& .MuiSnackbarContent-root":{minWidth:"auto"}},TransitionProps:{enter:!0,exit:!0},children:_(Ze,{variant:"filled",severity:r.severity,onClose:n,sx:{width:"100%",minWidth:"280px",maxWidth:"400px",wordBreak:"break-word"},children:r.allowHtml?_("span",{dangerouslySetInnerHTML:{__html:Qe(r.message)}}):_("span",{children:r.message})})})},Se=()=>{let r=Ye(xe);if(!r)throw new Error("useGlobalNotification debe ser usado dentro de un GlobalNotificationProvider");return r};import ti,{createContext as ri,useContext as ni,useMemo as le}from"react";import{Fragment as si,jsx as R,jsxs as O}from"react/jsx-runtime";var Ne=ri(void 0);function Pe({children:r,options:i={},config:e,showNotifications:t=!1,notificationOptions:n={}}){let s;try{let{showNotification:o}=Se();s=o}catch{}let f={};try{let o=Ie();o.isInitialized&&o.adminCredentials&&(f=o.adminCredentials)}catch{}let h=le(()=>{let o=oe({publicApiKey:e?.publicApiKey,env:e?.env,enableDebug:i?.enableLogging});return{publicApiKey:o.publicApiKey,env:o.env||"prod"}},[e,i?.enableLogging]),S=ti.useMemo(()=>({...i,showNotification:s,apiEndpointAdmin:f.apiEndpointAdmin,apiKeyEndpointAdmin:f.apiKeyEndpointAdmin,publicApiKey:h.publicApiKey,env:h.env,onSessionExpired:()=>{i.onSessionExpired?.()}}),[i,s,f.apiEndpointAdmin,f.apiKeyEndpointAdmin,h]),I=be(S),m=le(()=>{let o=oe({publicApiKey:e?.publicApiKey,env:e?.env,appName:e?.appName,logo:e?.logo,loginActions:e?.loginActions,enableDebug:i?.enableLogging});return{publicApiKey:o.publicApiKey,env:o.env,appName:o.appName,loginActions:o.loginActions,logo:o.logo}},[e,i?.enableLogging]),c=le(()=>{if(!I.tokens?.accessToken||!I.isAuthenticated)return null;try{let o=me(I.tokens.accessToken);if(o&&o.sub&&o.email&&o.subscriber){let p={_id:o.sub,email:o.email,subscriberKey:o.subscriber};return Object.keys(o).forEach(v=>{["sub","email","subscriber"].includes(v)||(p[v]=o[v])}),p}}catch(o){console.error("Error decoding JWT token for sessionData:",o)}return null},[I.tokens?.accessToken,I.isAuthenticated]),a={...I,sessionData:c,config:m},l={enabled:t,maxNotifications:n.maxNotifications||5,defaultAutoHideDuration:n.defaultAutoHideDuration||6e3,position:n.position||{vertical:"top",horizontal:"right"}};return R(Ne.Provider,{value:a,children:r})}function et(r){let i={enabled:r.showNotifications,maxNotifications:r.notificationOptions?.maxNotifications||5,defaultAutoHideDuration:r.notificationOptions?.defaultAutoHideDuration||6e3,position:r.notificationOptions?.position||{vertical:"top",horizontal:"right"},allowHtml:r.notificationOptions?.allowHtml||!1};return r.config?.publicApiKey?R(Ae,{config:{publicApiKey:r.config.publicApiKey,env:r.config.env||"prod",appName:r.config.appName,loginActions:r.config.loginActions,logo:r.config.logo},children:R(ae,{...i,children:R(Pe,{...r})})}):R(ae,{...i,children:R(Pe,{...r})})}function oi(){let r=ni(Ne);if(r===void 0)throw new Error("useSessionContext must be used within a SessionProvider");return r}function it(){let r=oi();return r.isInitialized?O("div",{style:{padding:"10px",margin:"10px",border:"1px solid #ccc",borderRadius:"4px",fontSize:"12px",fontFamily:"monospace"},children:[R("h4",{children:"Session Debug Info"}),O("div",{children:[R("strong",{children:"Authenticated:"})," ",r.isAuthenticated?"Yes":"No"]}),O("div",{children:[R("strong",{children:"Loading:"})," ",r.isLoading?"Yes":"No"]}),O("div",{children:[R("strong",{children:"Error:"})," ",r.error||"None"]}),r.tokens&&O(si,{children:[O("div",{children:[R("strong",{children:"Access Token:"})," ",r.tokens.accessToken.substring(0,20),"..."]}),O("div",{children:[R("strong",{children:"Refresh Token:"})," ",r.tokens.refreshToken.substring(0,20),"..."]}),O("div",{children:[R("strong",{children:"Access Expires In:"})," ",Math.round(r.expiresIn/1e3/60)," minutes"]}),O("div",{children:[R("strong",{children:"Refresh Expires In:"})," ",Math.round(r.refreshExpiresIn/1e3/60/60)," hours"]}),O("div",{children:[R("strong",{children:"Expiring Soon:"})," ",r.isExpiringSoon?"Yes":"No"]})]})]}):R("div",{children:"Session not initialized"})}import{useState as j,useEffect as Re,useCallback as we,useRef as Q}from"react";import ai from"@nocios/crudify-browser";var at=(r={})=>{let{autoFetch:i=!0,retryOnError:e=!1,maxRetries:t=3}=r,[n,s]=j(null),[f,h]=j(!1),[S,I]=j(null),[m,c]=j({}),a=Q(null),l=Q(!0),o=Q(0),p=Q(0),v=we(()=>{s(null),I(null),h(!1),c({})},[]),k=we(async()=>{let C=ve();if(!C){l.current&&(I("No user email available"),h(!1));return}a.current&&a.current.abort();let b=new AbortController;a.current=b;let P=++o.current;try{l.current&&(h(!0),I(null));let z=await ai.readItems("users",{filter:{email:C},pagination:{limit:1}});if(P===o.current&&l.current&&!b.signal.aborted)if(z.success&&z.data&&z.data.length>0){let E=z.data[0];s(E);let V={fullProfile:E,totalFields:Object.keys(E).length,displayData:{id:E.id,email:E.email,username:E.username,firstName:E.firstName,lastName:E.lastName,fullName:E.fullName||`${E.firstName||""} ${E.lastName||""}`.trim(),role:E.role,permissions:E.permissions||[],isActive:E.isActive,lastLogin:E.lastLogin,createdAt:E.createdAt,updatedAt:E.updatedAt,...Object.keys(E).filter(H=>!["id","email","username","firstName","lastName","fullName","role","permissions","isActive","lastLogin","createdAt","updatedAt"].includes(H)).reduce((H,Y)=>({...H,[Y]:E[Y]}),{})}};c(V),I(null),p.current=0}else I("User profile not found"),s(null),c({})}catch(z){if(P===o.current&&l.current){let E=z;if(E.name==="AbortError")return;e&&p.current<t&&(E.message?.includes("Network Error")||E.message?.includes("Failed to fetch"))?(p.current++,setTimeout(()=>{l.current&&k()},1e3*p.current)):(I("Failed to load user profile"),s(null),c({}))}}finally{P===o.current&&l.current&&h(!1),a.current===b&&(a.current=null)}},[e,t]);return Re(()=>{i&&k()},[i,k]),Re(()=>(l.current=!0,()=>{l.current=!1,a.current&&(a.current.abort(),a.current=null)}),[]),{userProfile:n,loading:f,error:S,extendedData:m,refreshProfile:k,clearProfile:v}};import{useState as ce,useEffect as li,useCallback as ee,useRef as ci}from"react";import ui from"@nocios/crudify-browser";var dt=(r,i={})=>{let{autoFetch:e=!0,onSuccess:t,onError:n}=i,{prefix:s,padding:f=0,separator:h=""}=r,[S,I]=ce(""),[m,c]=ce(!1),[a,l]=ce(null),o=ci(!1),p=ee(b=>{let P=String(b).padStart(f,"0");return`${s}${h}${P}`},[s,f,h]),v=ee(async()=>{c(!0),l(null);try{let b=await ui.getNextSequence(s);if(b.success&&b.data?.value){let P=p(b.data.value);I(P),t?.(P)}else{let P=b.errors?._error?.[0]||"Failed to generate code";l(P),n?.(P)}}catch(b){let P=b instanceof Error?b.message:"Unknown error";l(P),n?.(P)}finally{c(!1)}},[s,p,t,n]),k=ee(async()=>{await v()},[v]),C=ee(()=>{l(null)},[]);return li(()=>{e&&!S&&!o.current&&(o.current=!0,v())},[e,S,v]),{value:S,loading:m,error:a,regenerate:k,clearError:C}};import ue from"@nocios/crudify-browser";var de=class r{constructor(){this.state={status:"UNINITIALIZED",priority:null,publicApiKey:null,env:null,error:null,initializedBy:null};this.initializationPromise=null;this.highPriorityInitializerPresent=!1;this.waitingForHighPriority=new Set;this.HIGH_PRIORITY_WAIT_TIMEOUT=100}static getInstance(){return r.instance||(r.instance=new r),r.instance}registerHighPriorityInitializer(){this.highPriorityInitializerPresent=!0}isHighPriorityInitializerPresent(){return this.highPriorityInitializerPresent}getState(){return{...this.state}}async initialize(i){let{priority:e,publicApiKey:t,env:n,enableLogging:s,requestedBy:f}=i;if(this.state.status==="INITIALIZED"){this.state.publicApiKey!==t&&console.warn(`[CrudifyInitialization] ${f} attempted to initialize with different key. Already initialized with key: ${this.state.publicApiKey?.slice(0,10)}... by ${this.state.initializedBy}`);return}if(this.initializationPromise)return s&&console.log(`[CrudifyInitialization] ${f} waiting for ongoing initialization...`),this.initializationPromise;if(e==="LOW"&&this.highPriorityInitializerPresent&&this.state.status==="UNINITIALIZED"){if(s&&console.log(`[CrudifyInitialization] ${f} (LOW priority) waiting for HIGH priority initializer...`),this.waitingForHighPriority.add(f),await this.waitForHighPriorityOrTimeout(s),this.waitingForHighPriority.delete(f),this.getState().status==="INITIALIZED"){s&&console.log(`[CrudifyInitialization] ${f} found initialization completed by HIGH priority`);return}s&&console.warn(`[CrudifyInitialization] ${f} timeout waiting for HIGH priority, initializing with LOW priority`)}e==="HIGH"&&this.state.status==="INITIALIZING"&&this.state.priority==="LOW"&&(console.warn(`[CrudifyInitialization] HIGH priority request from ${f} interrupting LOW priority initialization by ${this.state.initializedBy}`),this.state.status="UNINITIALIZED",this.initializationPromise=null),s&&console.log(`[CrudifyInitialization] ${f} starting initialization (${e} priority)...`),this.state.status="INITIALIZING",this.state.priority=e,this.state.initializedBy=f,this.initializationPromise=this.performInitialization(t,n,s);try{await this.initializationPromise,this.state.status="INITIALIZED",this.state.publicApiKey=t,this.state.env=n,this.state.error=null,s&&console.log(`[CrudifyInitialization] \u2705 Successfully initialized by ${f} (${e} priority)`)}catch(h){throw this.state.status="ERROR",this.state.error=h instanceof Error?h:new Error(String(h)),this.initializationPromise=null,console.error(`[CrudifyInitialization] \u274C Initialization failed for ${f}:`,h),h}}async waitForHighPriorityOrTimeout(i){return new Promise(e=>{let n=0,s=setInterval(()=>{if(n+=10,this.state.status==="INITIALIZED"&&this.state.priority==="HIGH"){clearInterval(s),e();return}if(this.state.status==="INITIALIZING"&&this.state.priority==="HIGH"){n=0;return}n>=this.HIGH_PRIORITY_WAIT_TIMEOUT&&(clearInterval(s),i&&console.log(`[CrudifyInitialization] Timeout waiting for HIGH priority (${this.HIGH_PRIORITY_WAIT_TIMEOUT}ms)`),e())},10)})}async performInitialization(i,e,t){let n=ue.getTokenData();if(n&&n.endpoint){t&&console.log("[CrudifyInitialization] SDK already initialized externally");return}ue.config(e);let s=t?"debug":"none",f=await ue.init(i,s);if(f.success===!1)throw new Error(`Crudify initialization failed: ${JSON.stringify(f.errors||"Unknown error")}`)}reset(){this.state={status:"UNINITIALIZED",priority:null,publicApiKey:null,env:null,error:null,initializedBy:null},this.initializationPromise=null,this.highPriorityInitializerPresent=!1,this.waitingForHighPriority.clear()}isInitialized(){return this.state.status==="INITIALIZED"}getDiagnostics(){return{...this.state,waitingCount:this.waitingForHighPriority.size,waitingComponents:Array.from(this.waitingForHighPriority),hasActivePromise:this.initializationPromise!==null}}},ie=de.getInstance();import{useState as Ce,useCallback as D,useRef as di,useMemo as te}from"react";import fe from"@nocios/crudify-browser";var Le=()=>`file_${Date.now()}_${Math.random().toString(36).substring(2,9)}`,fi=r=>{let i=r.lastIndexOf("."),e=i>0?r.substring(i):"",t=Date.now(),n=Math.random().toString(36).substring(2,8);return`${t}_${n}${e}`},vt=(r={})=>{let{acceptedTypes:i,maxFileSize:e=10*1024*1024,maxFiles:t,minFiles:n=0,visibility:s="private",onUploadComplete:f,onUploadError:h,onFileRemoved:S,onFilesChange:I}=r,[m,c]=Ce([]),[a,l]=Ce(!1),o=di(new Map),p=D(()=>{l(!0)},[]),v=D((u,y)=>{c(g=>g.map(T=>T.id===u?{...T,...y}:T))},[]),k=D(u=>{I?.(u)},[I]),C=D(u=>i&&i.length>0&&!i.includes(u.type)?{valid:!1,error:`Tipo de archivo no permitido: ${u.type}`}:u.size>e?{valid:!1,error:`El archivo excede el tama\xF1o m\xE1ximo de ${(e/1048576).toFixed(1)}MB`}:{valid:!0},[i,e]),b=D(async(u,y)=>{try{if(!ie.isInitialized())throw new Error("Crudify no est\xE1 inicializado. Por favor espere a que la aplicaci\xF3n termine de cargar.");let g=fi(y.name),N=await fe.generateSignedUrl({fileName:g,contentType:y.type,visibility:s});if(!N.success||!N.data)throw new Error("No se pudo obtener URL de upload");let{uploadUrl:T,s3Key:x,publicUrl:M}=N.data;if(!T||!x)throw new Error("Respuesta de signed URL incompleta");let pe=x.indexOf("/"),Ke=pe>0?x.substring(pe+1):x;v(u.id,{status:"uploading",progress:0}),await new Promise((ne,G)=>{let L=new XMLHttpRequest;L.upload.addEventListener("progress",U=>{if(U.lengthComputable){let Ue=Math.round(U.loaded/U.total*100);v(u.id,{progress:Ue})}}),L.addEventListener("load",()=>{L.status>=200&&L.status<300?ne():G(new Error(`Upload fall\xF3 con status ${L.status}`))}),L.addEventListener("error",()=>{G(new Error("Error de red durante el upload"))}),L.addEventListener("abort",()=>{G(new Error("Upload cancelado"))}),L.open("PUT",T),L.setRequestHeader("Content-Type",y.type),L.send(y)});let Oe={status:"completed",progress:100,filePath:Ke,visibility:s,publicUrl:s==="public"?M:void 0,file:void 0};c(ne=>{let G=ne.map(U=>U.id===u.id?{...U,...Oe}:U);k(G);let L=G.find(U=>U.id===u.id);return L&&f?.(L),G})}catch(g){let N=g instanceof Error?g.message:"Error desconocido";v(u.id,{status:"error",progress:0,errorMessage:N}),c(T=>{let x=T.find(M=>M.id===u.id);return x&&h?.(x,N),T})}},[v,f,h,s]),P=D(async u=>{let y=Array.from(u);if(t!==void 0){let T=m.filter(M=>M.status!=="error").length,x=t-T;if(x<=0){console.warn(`Ya se alcanz\xF3 el l\xEDmite de ${t} archivos`);return}y.length>x&&(y.splice(x),console.warn(`Solo se agregar\xE1n ${x} archivos para no exceder el l\xEDmite`))}let g=[];for(let T of y){let x=C(T),M={id:Le(),name:T.name,size:T.size,contentType:T.type,status:x.valid?"pending":"error",progress:0,createdAt:Date.now(),file:x.valid?T:void 0,errorMessage:x.error};g.push(M)}c(T=>{let x=[...T,...g];return k(x),x});let N=g.filter(T=>T.status==="pending"&&T.file);for(let T of N)if(T.file){let x=b(T,T.file);o.current.set(T.id,x),x.finally(()=>{o.current.delete(T.id)})}},[m,t,C,b,k]),z=D(async u=>{let y=m.find(g=>g.id===u);if(!y)return!1;v(u,{status:"removing"});try{if(y.filePath){if(!ie.isInitialized())throw new Error("Crudify no est\xE1 inicializado. Por favor espere a que la aplicaci\xF3n termine de cargar.");if(!(await fe.disableFile({filePath:y.filePath})).success)throw new Error("No se pudo eliminar el archivo del servidor")}return c(g=>{let N=g.filter(T=>T.id!==u);return k(N),N}),S?.(y),!0}catch(g){return v(u,{status:y.filePath?"completed":"error",errorMessage:g instanceof Error?g.message:"Error al eliminar"}),!1}},[m,v,k,S]),E=D(()=>{c([]),k([])},[k]),V=D(async u=>{let y=m.find(N=>N.id===u);if(!y||y.status!=="error"||!y.file){console.warn("No se puede reintentar: archivo no encontrado o sin archivo original");return}v(u,{status:"pending",progress:0,errorMessage:void 0});let g=b(y,y.file);o.current.set(u,g),g.finally(()=>{o.current.delete(u)})},[m,v,b]),H=D(async()=>{let u=Array.from(o.current.values());u.length>0&&await Promise.allSettled(u)},[]),Y=D(u=>{let y=u.map(g=>{let N=g.filePath.startsWith("public/")?"public":"private";return{id:Le(),name:g.name,size:g.size||0,contentType:g.contentType||"application/octet-stream",status:"completed",progress:100,filePath:g.filePath,visibility:N,createdAt:Date.now()}});c(y),k(y)},[k]),ge=D(async u=>{let y=m.find(g=>g.id===u);if(!y||!y.filePath)return null;if(y.visibility==="public"&&y.publicUrl)return y.publicUrl;try{if(!ie.isInitialized())return null;let g=await fe.getFileUrl({filePath:y.filePath,expiresIn:3600});return g.success&&g.data?.url?g.data.url:null}catch{return null}},[m]),F=te(()=>m.some(u=>u.status==="uploading"||u.status==="pending"),[m]),re=te(()=>m.filter(u=>u.status==="uploading"||u.status==="pending").length,[m]),De=te(()=>m.filter(u=>u.status==="completed"&&u.filePath).map(u=>u.filePath),[m]),{isValid:ze,validationError:Fe}=te(()=>{let u=m.filter(g=>g.status==="completed").length;return u<n?{isValid:!1,validationError:n===1?"Se requiere al menos un archivo":`Se requieren al menos ${n} archivos`}:t!==void 0&&u>t?{isValid:!1,validationError:`M\xE1ximo ${t} archivos permitidos`}:m.some(g=>g.status==="error")?{isValid:!1,validationError:"Algunos archivos tienen errores"}:{isValid:!0,validationError:null}},[m,n,t]);return{files:m,isUploading:F,pendingCount:re,addFiles:P,removeFile:z,clearFiles:E,retryUpload:V,isValid:ze,validationError:Fe,waitForUploads:H,completedFilePaths:De,initializeFiles:Y,isTouched:a,markAsTouched:p,getPreviewUrl:ge}};export{Te as a,Ae as b,Ie as c,A as d,W as e,be as f,ae as g,Se as h,et as i,oi as j,it as k,at as l,dt as m,de as n,ie as o,vt as p};
|