@nocios/crudify-ui 2.0.1 → 3.0.0

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/index.mjs CHANGED
@@ -1,19 +1,3 @@
1
- import {
2
- CrudifyDataProvider,
3
- configurationManager,
4
- crudifyInitializer,
5
- getCookie,
6
- useCrudifyDataContext
7
- } from "./chunk-GY5F6KOF.mjs";
8
- import {
9
- decodeJwtSafely,
10
- getCurrentUserEmail,
11
- isTokenExpired,
12
- secureLocalStorage,
13
- secureSessionStorage,
14
- tokenManager
15
- } from "./chunk-M7V4UGCN.mjs";
16
-
17
1
  // src/index.ts
18
2
  import { default as default2 } from "@nocios/crudify-browser";
19
3
  export * from "@nocios/crudify-browser";
@@ -177,6 +161,14 @@ var useCrudify = () => {
177
161
 
178
162
  // src/components/CrudifyLogin/context/LoginStateProvider.tsx
179
163
  import { createContext as createContext3, useContext as useContext3, useReducer, useEffect as useEffect3 } from "react";
164
+
165
+ // src/components/CrudifyLogin/utils/cookies.ts
166
+ var getCookie = (name) => {
167
+ const match = document.cookie.match(new RegExp("(^|;)\\s*" + name + "=([^;]+)"));
168
+ return match ? match[2] : null;
169
+ };
170
+
171
+ // src/components/CrudifyLogin/context/LoginStateProvider.tsx
180
172
  import { jsx as jsx3 } from "react/jsx-runtime";
181
173
  var initialState = {
182
174
  currentScreen: "login",
@@ -364,8 +356,8 @@ var LoginStateProvider = ({
364
356
  dispatch({ type: "SET_SEARCH_PARAMS", payload: paramsObject });
365
357
  }
366
358
  }, [initialScreen]);
367
- const setScreen = (screen, params) => {
368
- dispatch({ type: "SET_SCREEN", payload: { screen, params } });
359
+ const setScreen = (screen2, params) => {
360
+ dispatch({ type: "SET_SCREEN", payload: { screen: screen2, params } });
369
361
  };
370
362
  const updateFormData = (data) => {
371
363
  dispatch({ type: "UPDATE_FORM_DATA", payload: data });
@@ -672,41 +664,11 @@ function handleCrudifyError(error) {
672
664
  ];
673
665
  }
674
666
 
675
- // src/hooks/useCrudifyAuth.ts
676
- var useCrudifyAuth = () => {
677
- const {
678
- isAuthenticated,
679
- isInitializing,
680
- initializationError,
681
- token,
682
- user,
683
- tokenExpiration,
684
- setToken,
685
- logout
686
- } = useCrudifyDataContext();
687
- return {
688
- // Estado básico
689
- isAuthenticated,
690
- loading: isInitializing,
691
- error: initializationError,
692
- // Datos del token
693
- token,
694
- user,
695
- tokenExpiration,
696
- // Acciones
697
- setToken,
698
- logout,
699
- refreshToken: void 0
700
- // Will be implemented in future versions
701
- };
702
- };
703
-
704
667
  // src/components/CrudifyLogin/Forms/LoginForm.tsx
705
668
  import { Fragment, jsx as jsx4, jsxs } from "react/jsx-runtime";
706
669
  var LoginForm = ({ onScreenChange, onExternalNavigate, onLoginSuccess, onError, redirectUrl = "/" }) => {
707
- const { crudify: crudify9 } = useCrudify();
670
+ const { crudify: crudify7 } = useCrudify();
708
671
  const { state, updateFormData, setFieldError, clearErrors, setLoading } = useLoginState();
709
- const { setToken } = useCrudifyAuth();
710
672
  const { t } = useTranslation();
711
673
  const usernameInputRef = useRef(null);
712
674
  const getRedirectUrl = () => {
@@ -756,25 +718,17 @@ var LoginForm = ({ onScreenChange, onExternalNavigate, onLoginSuccess, onError,
756
718
  clearErrors();
757
719
  setLoading(true);
758
720
  try {
759
- if (!crudify9) {
721
+ if (!crudify7) {
760
722
  throw new Error("Crudify not initialized");
761
723
  }
762
- const response = await crudify9.login(state.formData.username, state.formData.password);
724
+ const response = await crudify7.login(state.formData.username, state.formData.password);
763
725
  setLoading(false);
764
726
  if (response.success) {
765
- console.log("\u{1F510} LoginForm - Login successful, setting tokens");
766
- secureSessionStorage.setToken(response.data.token);
767
- console.log("\u{1F510} LoginForm - Token set in secureSessionStorage");
768
- console.log("\u{1F510} LoginForm - Setting token in CrudifyDataProvider via setToken hook");
769
- setToken(response.data.token);
770
- console.log("\u{1F510} LoginForm - Token set in CrudifyDataProvider");
727
+ console.log("\u{1F510} LoginForm - Login successful, calling onLoginSuccess");
771
728
  const finalRedirectUrl = getRedirectUrl();
772
- setTimeout(() => {
773
- console.log("\u{1F510} LoginForm - Calling onLoginSuccess after delay");
774
- if (onLoginSuccess) {
775
- onLoginSuccess(response.data, finalRedirectUrl);
776
- }
777
- }, 100);
729
+ if (onLoginSuccess) {
730
+ onLoginSuccess(response.data, finalRedirectUrl);
731
+ }
778
732
  } else {
779
733
  handleLoginError(response);
780
734
  }
@@ -922,7 +876,7 @@ import { useState as useState3 } from "react";
922
876
  import { Typography as Typography2, TextField as TextField2, Button as Button2, Box as Box2, CircularProgress as CircularProgress2, Alert as Alert2, Link as Link2 } from "@mui/material";
923
877
  import { Fragment as Fragment2, jsx as jsx5, jsxs as jsxs2 } from "react/jsx-runtime";
924
878
  var ForgotPasswordForm = ({ onScreenChange, onError }) => {
925
- const { crudify: crudify9 } = useCrudify();
879
+ const { crudify: crudify7 } = useCrudify();
926
880
  const [email, setEmail] = useState3("");
927
881
  const [loading, setLoading] = useState3(false);
928
882
  const [errors, setErrors] = useState3([]);
@@ -951,7 +905,7 @@ var ForgotPasswordForm = ({ onScreenChange, onError }) => {
951
905
  return emailRegex.test(email2);
952
906
  };
953
907
  const handleSubmit = async () => {
954
- if (loading || !crudify9) return;
908
+ if (loading || !crudify7) return;
955
909
  setErrors([]);
956
910
  setHelperTextEmail(null);
957
911
  if (!email) {
@@ -965,7 +919,7 @@ var ForgotPasswordForm = ({ onScreenChange, onError }) => {
965
919
  setLoading(true);
966
920
  try {
967
921
  const data = [{ operation: "requestPasswordReset", data: { email } }];
968
- const response = await crudify9.transaction(data);
922
+ const response = await crudify7.transaction(data);
969
923
  if (response.success) {
970
924
  if (response.data && response.data.existingCodeValid) {
971
925
  setCodeAlreadyExists(true);
@@ -1068,7 +1022,7 @@ import { useState as useState4, useEffect as useEffect5 } from "react";
1068
1022
  import { Typography as Typography3, TextField as TextField3, Button as Button3, Box as Box3, CircularProgress as CircularProgress3, Alert as Alert3, Link as Link3 } from "@mui/material";
1069
1023
  import { Fragment as Fragment3, jsx as jsx6, jsxs as jsxs3 } from "react/jsx-runtime";
1070
1024
  var ResetPasswordForm = ({ onScreenChange, onError, searchParams, onResetSuccess }) => {
1071
- const { crudify: crudify9 } = useCrudify();
1025
+ const { crudify: crudify7 } = useCrudify();
1072
1026
  const [newPassword, setNewPassword] = useState4("");
1073
1027
  const [confirmPassword, setConfirmPassword] = useState4("");
1074
1028
  const [loading, setLoading] = useState4(false);
@@ -1148,9 +1102,9 @@ var ResetPasswordForm = ({ onScreenChange, onError, searchParams, onResetSuccess
1148
1102
  setErrors([t("resetPassword.invalidCode")]);
1149
1103
  setValidatingCode(false);
1150
1104
  setTimeout(() => onScreenChange?.("forgotPassword"), 3e3);
1151
- }, [searchParams, crudify9, t, onScreenChange]);
1105
+ }, [searchParams, crudify7, t, onScreenChange]);
1152
1106
  useEffect5(() => {
1153
- if (crudify9 && pendingValidation && !isValidating) {
1107
+ if (crudify7 && pendingValidation && !isValidating) {
1154
1108
  setIsValidating(true);
1155
1109
  const validateCode = async (emailToValidate, codeToValidate) => {
1156
1110
  try {
@@ -1160,7 +1114,7 @@ var ResetPasswordForm = ({ onScreenChange, onError, searchParams, onResetSuccess
1160
1114
  data: { email: emailToValidate, codePassword: codeToValidate }
1161
1115
  }
1162
1116
  ];
1163
- const response = await crudify9.transaction(data);
1117
+ const response = await crudify7.transaction(data);
1164
1118
  if (response.data && Array.isArray(response.data)) {
1165
1119
  const validationResult = response.data[0];
1166
1120
  if (validationResult && validationResult.response && validationResult.response.status === "OK") {
@@ -1189,7 +1143,7 @@ var ResetPasswordForm = ({ onScreenChange, onError, searchParams, onResetSuccess
1189
1143
  };
1190
1144
  validateCode(pendingValidation.email, pendingValidation.code);
1191
1145
  }
1192
- }, [crudify9, pendingValidation, t, onScreenChange]);
1146
+ }, [crudify7, pendingValidation, t, onScreenChange]);
1193
1147
  const validatePassword = (password) => {
1194
1148
  if (password.length < 8) {
1195
1149
  return t("resetPassword.passwordTooShort");
@@ -1197,7 +1151,7 @@ var ResetPasswordForm = ({ onScreenChange, onError, searchParams, onResetSuccess
1197
1151
  return null;
1198
1152
  };
1199
1153
  const handleSubmit = async () => {
1200
- if (loading || !crudify9) return;
1154
+ if (loading || !crudify7) return;
1201
1155
  setErrors([]);
1202
1156
  setHelperTextNewPassword(null);
1203
1157
  setHelperTextConfirmPassword(null);
@@ -1228,7 +1182,7 @@ var ResetPasswordForm = ({ onScreenChange, onError, searchParams, onResetSuccess
1228
1182
  data: { email, codePassword: code, newPassword }
1229
1183
  }
1230
1184
  ];
1231
- const response = await crudify9.transaction(data);
1185
+ const response = await crudify7.transaction(data);
1232
1186
  if (response.success) {
1233
1187
  setErrors([]);
1234
1188
  setTimeout(() => {
@@ -1339,7 +1293,7 @@ import { useState as useState5, useEffect as useEffect6 } from "react";
1339
1293
  import { Typography as Typography4, TextField as TextField4, Button as Button4, Box as Box4, CircularProgress as CircularProgress4, Alert as Alert4, Link as Link4 } from "@mui/material";
1340
1294
  import { Fragment as Fragment4, jsx as jsx7, jsxs as jsxs4 } from "react/jsx-runtime";
1341
1295
  var CheckCodeForm = ({ onScreenChange, onError, searchParams }) => {
1342
- const { crudify: crudify9 } = useCrudify();
1296
+ const { crudify: crudify7 } = useCrudify();
1343
1297
  const [code, setCode] = useState5("");
1344
1298
  const [loading, setLoading] = useState5(false);
1345
1299
  const [errors, setErrors] = useState5([]);
@@ -1378,7 +1332,7 @@ var CheckCodeForm = ({ onScreenChange, onError, searchParams }) => {
1378
1332
  }
1379
1333
  }, [searchParams, onScreenChange]);
1380
1334
  const handleSubmit = async () => {
1381
- if (loading || !crudify9) return;
1335
+ if (loading || !crudify7) return;
1382
1336
  setErrors([]);
1383
1337
  setHelperTextCode(null);
1384
1338
  if (!code) {
@@ -1397,7 +1351,7 @@ var CheckCodeForm = ({ onScreenChange, onError, searchParams }) => {
1397
1351
  data: { email, codePassword: code }
1398
1352
  }
1399
1353
  ];
1400
- const response = await crudify9.transaction(data);
1354
+ const response = await crudify7.transaction(data);
1401
1355
  if (response.success) {
1402
1356
  onScreenChange?.("resetPassword", { email, code, fromCodeVerification: "true" });
1403
1357
  } else {
@@ -1522,49 +1476,32 @@ var CrudifyInitializer = ({ children, fallback }) => {
1522
1476
 
1523
1477
  // src/components/CrudifyLogin/hooks/useCrudifyLogin.ts
1524
1478
  import { useMemo as useMemo2 } from "react";
1525
-
1526
- // src/hooks/useCrudifyConfig.ts
1527
- var useCrudifyConfig = () => {
1528
- const {
1529
- config,
1530
- isConfigured,
1531
- configError,
1532
- configSource,
1533
- refreshConfig,
1534
- getDebugInfo
1535
- } = useCrudifyDataContext();
1536
- return {
1537
- config,
1538
- isConfigured,
1539
- configError,
1540
- configSource,
1541
- rawConfig: config?.rawConfig || {},
1542
- refreshConfig,
1543
- getDebugInfo
1544
- };
1545
- };
1546
-
1547
- // src/components/CrudifyLogin/hooks/useCrudifyLogin.ts
1479
+ import crudify2 from "@nocios/crudify-browser";
1548
1480
  var useCrudifyLogin = (config, _options = {}) => {
1549
- const { config: dataProviderConfig, isConfigured } = useCrudifyConfig();
1550
1481
  console.log("\u{1F50D} useCrudifyLogin - Input config:", config);
1551
- console.log("\u{1F50D} useCrudifyLogin - DataProvider config:", dataProviderConfig);
1552
- console.log("\u{1F50D} useCrudifyLogin - IsConfigured:", isConfigured);
1553
1482
  const finalConfig = useMemo2(() => {
1554
- const publicApiKey = config.publicApiKey || (isConfigured ? dataProviderConfig?.publicApiKey : null) || getCookie("publicApiKey") || null;
1483
+ let crudifyConfig = null;
1484
+ try {
1485
+ if (crudify2 && crudify2.config) {
1486
+ crudifyConfig = crudify2.config;
1487
+ }
1488
+ } catch (error) {
1489
+ console.log("\u{1F50D} useCrudifyLogin - No crudify instance config available:", error);
1490
+ }
1491
+ const publicApiKey = config.publicApiKey || crudifyConfig?.publicApiKey || getCookie("publicApiKey") || null;
1555
1492
  console.log("\u{1F50D} useCrudifyLogin - Resolved publicApiKey:", publicApiKey);
1556
1493
  console.log(
1557
1494
  "\u{1F50D} useCrudifyLogin - Sources - props:",
1558
1495
  config.publicApiKey,
1559
- "dataProvider:",
1560
- dataProviderConfig?.publicApiKey,
1496
+ "crudify:",
1497
+ crudifyConfig?.publicApiKey,
1561
1498
  "cookie:",
1562
1499
  getCookie("publicApiKey")
1563
1500
  );
1564
- const rawEnv = config.env || (isConfigured ? dataProviderConfig?.env : null) || getCookie("environment") || "prod";
1501
+ const rawEnv = config.env || crudifyConfig?.env || getCookie("environment") || "prod";
1565
1502
  const env = ["dev", "stg", "prod"].includes(rawEnv) ? rawEnv : "prod";
1566
- const appName = config.appName || (isConfigured ? dataProviderConfig?.appName : null) || getCookie("appName") || "Crudia";
1567
- const loginActions = config.loginActions || (isConfigured ? dataProviderConfig?.loginActions : null) || (() => {
1503
+ const appName = config.appName || crudifyConfig?.appName || getCookie("appName") || "Crudia";
1504
+ const loginActions = config.loginActions || crudifyConfig?.loginActions || (() => {
1568
1505
  try {
1569
1506
  const cookieValue = getCookie("loginActions");
1570
1507
  return cookieValue ? cookieValue.split(",").map((action) => action.trim()).filter(Boolean) : [];
@@ -1580,7 +1517,7 @@ var useCrudifyLogin = (config, _options = {}) => {
1580
1517
  };
1581
1518
  console.log("\u{1F50D} useCrudifyLogin - Final config result:", finalResult);
1582
1519
  return finalResult;
1583
- }, [config, dataProviderConfig, isConfigured]);
1520
+ }, [config]);
1584
1521
  return { config: finalConfig };
1585
1522
  };
1586
1523
 
@@ -1595,15 +1532,15 @@ var CrudifyLoginInternal = ({
1595
1532
  }) => {
1596
1533
  const { t } = useTranslation();
1597
1534
  const { state, setScreen } = useLoginState();
1598
- const handleScreenChange = (screen, params) => {
1535
+ const handleScreenChange = (screen2, params) => {
1599
1536
  let finalParams = params;
1600
- if (screen === "login") {
1537
+ if (screen2 === "login") {
1601
1538
  finalParams = {};
1602
- } else if (screen === "forgotPassword" && !params) {
1539
+ } else if (screen2 === "forgotPassword" && !params) {
1603
1540
  finalParams = {};
1604
1541
  }
1605
- setScreen(screen, finalParams);
1606
- onScreenChange?.(screen, finalParams);
1542
+ setScreen(screen2, finalParams);
1543
+ onScreenChange?.(screen2, finalParams);
1607
1544
  };
1608
1545
  const renderCurrentForm = () => {
1609
1546
  const commonProps = {
@@ -1711,7 +1648,67 @@ import {
1711
1648
 
1712
1649
  // src/hooks/useUserProfile.ts
1713
1650
  import { useState as useState6, useEffect as useEffect7, useCallback, useRef as useRef2 } from "react";
1714
- import crudify2 from "@nocios/crudify-browser";
1651
+ import crudify3 from "@nocios/crudify-browser";
1652
+
1653
+ // src/utils/jwtUtils.ts
1654
+ var decodeJwtSafely = (token) => {
1655
+ try {
1656
+ const parts = token.split(".");
1657
+ if (parts.length !== 3) {
1658
+ console.warn("Invalid JWT format: token must have 3 parts");
1659
+ return null;
1660
+ }
1661
+ const payload = parts[1];
1662
+ const paddedPayload = payload + "=".repeat((4 - payload.length % 4) % 4);
1663
+ const decodedPayload = JSON.parse(atob(paddedPayload));
1664
+ return decodedPayload;
1665
+ } catch (error) {
1666
+ console.warn("Failed to decode JWT token:", error);
1667
+ return null;
1668
+ }
1669
+ };
1670
+ var getCurrentUserEmail = () => {
1671
+ try {
1672
+ let token = null;
1673
+ token = sessionStorage.getItem("authToken");
1674
+ console.log("\u{1F50D} getCurrentUserEmail - authToken:", token ? `${token.substring(0, 20)}...` : null);
1675
+ if (!token) {
1676
+ token = sessionStorage.getItem("token");
1677
+ console.log("\u{1F50D} getCurrentUserEmail - token:", token ? `${token.substring(0, 20)}...` : null);
1678
+ }
1679
+ if (!token) {
1680
+ token = localStorage.getItem("authToken") || localStorage.getItem("token");
1681
+ console.log("\u{1F50D} getCurrentUserEmail - localStorage:", token ? `${token.substring(0, 20)}...` : null);
1682
+ }
1683
+ if (!token) {
1684
+ console.warn("\u{1F50D} getCurrentUserEmail - No token found in any storage");
1685
+ return null;
1686
+ }
1687
+ const payload = decodeJwtSafely(token);
1688
+ if (!payload) {
1689
+ console.warn("\u{1F50D} getCurrentUserEmail - Failed to decode token");
1690
+ return null;
1691
+ }
1692
+ const email = payload.email || payload["cognito:username"] || null;
1693
+ console.log("\u{1F50D} getCurrentUserEmail - Extracted email:", email);
1694
+ return email;
1695
+ } catch (error) {
1696
+ console.warn("Failed to get current user email:", error);
1697
+ return null;
1698
+ }
1699
+ };
1700
+ var isTokenExpired = (token) => {
1701
+ try {
1702
+ const payload = decodeJwtSafely(token);
1703
+ if (!payload || !payload.exp) return true;
1704
+ const currentTime = Math.floor(Date.now() / 1e3);
1705
+ return payload.exp < currentTime;
1706
+ } catch {
1707
+ return true;
1708
+ }
1709
+ };
1710
+
1711
+ // src/hooks/useUserProfile.ts
1715
1712
  var useUserProfile = (options = {}) => {
1716
1713
  const { autoFetch = true, retryOnError = false, maxRetries = 3 } = options;
1717
1714
  const [userProfile, setUserProfile] = useState6(null);
@@ -1748,7 +1745,7 @@ var useUserProfile = (options = {}) => {
1748
1745
  setLoading(true);
1749
1746
  setError(null);
1750
1747
  }
1751
- const response = await crudify2.readItems("users", {
1748
+ const response = await crudify3.readItems("users", {
1752
1749
  filter: { email: userEmail },
1753
1750
  pagination: { limit: 1 }
1754
1751
  });
@@ -2639,563 +2636,8 @@ var Policies = ({
2639
2636
  };
2640
2637
  var Policies_default = Policies;
2641
2638
 
2642
- // src/hooks/useCrudifyUser.ts
2643
- import { useState as useState9, useEffect as useEffect9, useCallback as useCallback2, useRef as useRef5 } from "react";
2644
- import crudify3 from "@nocios/crudify-browser";
2645
- var useCrudifyUser = (options = {}) => {
2646
- const { autoFetch = true, retryOnError = false, maxRetries = 3 } = options;
2647
- const { isAuthenticated, isInitialized, user: jwtUser, token } = useCrudifyDataContext();
2648
- const [userData, setUserData] = useState9(null);
2649
- const [loading, setLoading] = useState9(false);
2650
- const [error, setError] = useState9(null);
2651
- const abortControllerRef = useRef5(null);
2652
- const mountedRef = useRef5(true);
2653
- const requestIdRef = useRef5(0);
2654
- const retryCountRef = useRef5(0);
2655
- const getUserEmailFromJWT = useCallback2(() => {
2656
- if (!jwtUser) return null;
2657
- return jwtUser.email || jwtUser["cognito:username"] || null;
2658
- }, [jwtUser]);
2659
- const clearProfile = useCallback2(() => {
2660
- setUserData(null);
2661
- setError(null);
2662
- setLoading(false);
2663
- retryCountRef.current = 0;
2664
- }, []);
2665
- const refreshProfile = useCallback2(async () => {
2666
- const userEmail = getUserEmailFromJWT();
2667
- console.log("\u{1F464} useCrudifyUser - Refreshing profile for:", userEmail);
2668
- if (!userEmail) {
2669
- if (mountedRef.current) {
2670
- setError("No user email available from JWT token");
2671
- setLoading(false);
2672
- }
2673
- return;
2674
- }
2675
- if (!isInitialized) {
2676
- if (mountedRef.current) {
2677
- setError("Crudify not initialized");
2678
- setLoading(false);
2679
- }
2680
- return;
2681
- }
2682
- if (abortControllerRef.current) {
2683
- abortControllerRef.current.abort();
2684
- }
2685
- const abortController = new AbortController();
2686
- abortControllerRef.current = abortController;
2687
- const currentRequestId = ++requestIdRef.current;
2688
- try {
2689
- if (mountedRef.current) {
2690
- setLoading(true);
2691
- setError(null);
2692
- }
2693
- console.log("\u{1F464} useCrudifyUser - Fetching profile data from database");
2694
- const response = await crudify3.readItems("users", {
2695
- filter: { email: userEmail },
2696
- pagination: { limit: 1 }
2697
- });
2698
- console.log("\u{1F464} useCrudifyUser - Database response:", response);
2699
- console.log("\u{1F464} useCrudifyUser - response.data:", response.data);
2700
- console.log("\u{1F464} useCrudifyUser - response.data type:", typeof response.data);
2701
- if (currentRequestId === requestIdRef.current && mountedRef.current && !abortController.signal.aborted) {
2702
- let userData2 = null;
2703
- if (response.success) {
2704
- console.log("\u{1F464} useCrudifyUser - Processing successful response:", {
2705
- dataType: typeof response.data,
2706
- isArray: Array.isArray(response.data),
2707
- hasResponse: !!response.data?.response,
2708
- hasResponseData: !!response.data?.response?.data,
2709
- responseDataType: typeof response.data?.response?.data
2710
- });
2711
- if (Array.isArray(response.data) && response.data.length > 0) {
2712
- console.log("\u{1F464} useCrudifyUser - Found direct array format");
2713
- userData2 = response.data[0];
2714
- } else if (response.data?.response?.data) {
2715
- console.log("\u{1F464} useCrudifyUser - Found nested response.data format");
2716
- try {
2717
- const rawData = response.data.response.data;
2718
- console.log("\u{1F464} useCrudifyUser - Raw nested data:", rawData);
2719
- console.log("\u{1F464} useCrudifyUser - Raw data type:", typeof rawData);
2720
- const parsedData = typeof rawData === "string" ? JSON.parse(rawData) : rawData;
2721
- console.log("\u{1F464} useCrudifyUser - Parsed nested data:", parsedData);
2722
- if (parsedData && parsedData.items && Array.isArray(parsedData.items) && parsedData.items.length > 0) {
2723
- userData2 = parsedData.items[0];
2724
- console.log("\u{1F464} useCrudifyUser - Extracted user from nested items:", userData2);
2725
- } else {
2726
- console.log("\u{1F464} useCrudifyUser - No items found in parsed data or items array is empty");
2727
- }
2728
- } catch (parseError) {
2729
- console.error("\u{1F464} useCrudifyUser - Error parsing nested response data:", parseError);
2730
- }
2731
- } else if (response.data && typeof response.data === "object") {
2732
- console.log("\u{1F464} useCrudifyUser - Found object format, checking for items");
2733
- if (response.data.items && Array.isArray(response.data.items) && response.data.items.length > 0) {
2734
- console.log("\u{1F464} useCrudifyUser - Found items in object format");
2735
- userData2 = response.data.items[0];
2736
- } else {
2737
- console.log("\u{1F464} useCrudifyUser - No items found in object format");
2738
- }
2739
- } else if (response.data?.data?.response?.data) {
2740
- console.log("\u{1F464} useCrudifyUser - Found double-nested data.data.response.data format");
2741
- try {
2742
- const rawData = response.data.data.response.data;
2743
- console.log("\u{1F464} useCrudifyUser - Raw double-nested data:", rawData);
2744
- const parsedData = typeof rawData === "string" ? JSON.parse(rawData) : rawData;
2745
- console.log("\u{1F464} useCrudifyUser - Parsed double-nested data:", parsedData);
2746
- if (parsedData && parsedData.items && Array.isArray(parsedData.items) && parsedData.items.length > 0) {
2747
- userData2 = parsedData.items[0];
2748
- console.log("\u{1F464} useCrudifyUser - Extracted user from double-nested items:", userData2);
2749
- }
2750
- } catch (parseError) {
2751
- console.error("\u{1F464} useCrudifyUser - Error parsing double-nested response data:", parseError);
2752
- }
2753
- }
2754
- }
2755
- if (userData2) {
2756
- console.log("\u{1F464} useCrudifyUser - User data found:", userData2);
2757
- setUserData(userData2);
2758
- setError(null);
2759
- retryCountRef.current = 0;
2760
- console.log("\u{1F464} useCrudifyUser - Profile loaded successfully:", userData2);
2761
- } else {
2762
- setError("User profile not found in database");
2763
- setUserData(null);
2764
- console.warn("\u{1F464} useCrudifyUser - User not found for email:", userEmail);
2765
- }
2766
- }
2767
- } catch (err) {
2768
- if (currentRequestId === requestIdRef.current && mountedRef.current) {
2769
- const error2 = err;
2770
- console.error("\u{1F464} useCrudifyUser - Error fetching profile:", error2);
2771
- if (error2.name === "AbortError") {
2772
- return;
2773
- }
2774
- const shouldRetry = retryOnError && retryCountRef.current < maxRetries && (error2.message?.includes("Network Error") || error2.message?.includes("Failed to fetch"));
2775
- if (shouldRetry) {
2776
- retryCountRef.current++;
2777
- console.log(`\u{1F464} useCrudifyUser - Retrying profile fetch (${retryCountRef.current}/${maxRetries})`);
2778
- setTimeout(() => {
2779
- if (mountedRef.current) {
2780
- refreshProfile();
2781
- }
2782
- }, 1e3 * retryCountRef.current);
2783
- } else {
2784
- setError("Failed to load user profile from database");
2785
- setUserData(null);
2786
- }
2787
- }
2788
- } finally {
2789
- if (currentRequestId === requestIdRef.current && mountedRef.current) {
2790
- setLoading(false);
2791
- }
2792
- if (abortControllerRef.current === abortController) {
2793
- abortControllerRef.current = null;
2794
- }
2795
- }
2796
- }, [isInitialized, getUserEmailFromJWT, retryOnError, maxRetries]);
2797
- useEffect9(() => {
2798
- if (autoFetch && isAuthenticated && isInitialized) {
2799
- refreshProfile();
2800
- } else if (!isAuthenticated) {
2801
- clearProfile();
2802
- }
2803
- }, [autoFetch, isAuthenticated, isInitialized, refreshProfile, clearProfile]);
2804
- useEffect9(() => {
2805
- mountedRef.current = true;
2806
- return () => {
2807
- mountedRef.current = false;
2808
- if (abortControllerRef.current) {
2809
- abortControllerRef.current.abort();
2810
- abortControllerRef.current = null;
2811
- }
2812
- };
2813
- }, []);
2814
- const user = {
2815
- session: jwtUser,
2816
- data: userData
2817
- };
2818
- return {
2819
- user,
2820
- loading,
2821
- error,
2822
- refreshProfile,
2823
- clearProfile
2824
- };
2825
- };
2826
-
2827
- // src/hooks/useCrudifyData.ts
2828
- import { useCallback as useCallback3 } from "react";
2829
- import crudify4 from "@nocios/crudify-browser";
2830
- var useCrudifyData = () => {
2831
- const {
2832
- isInitialized,
2833
- isInitializing,
2834
- initializationError
2835
- } = useCrudifyDataContext();
2836
- const isReady = useCallback3(() => {
2837
- return isInitialized && !initializationError && !isInitializing;
2838
- }, [isInitialized, initializationError, isInitializing]);
2839
- const waitForReady = useCallback3(async () => {
2840
- if (isReady()) return;
2841
- if (initializationError) {
2842
- throw new Error(`Crudify initialization failed: ${initializationError}`);
2843
- }
2844
- return new Promise((resolve, reject) => {
2845
- const maxWaitTime = 1e4;
2846
- const checkInterval = 100;
2847
- let elapsed = 0;
2848
- const check = () => {
2849
- if (isReady()) {
2850
- resolve();
2851
- } else if (initializationError) {
2852
- reject(new Error(`Crudify initialization failed: ${initializationError}`));
2853
- } else if (elapsed >= maxWaitTime) {
2854
- reject(new Error("Timeout waiting for crudify initialization"));
2855
- } else {
2856
- elapsed += checkInterval;
2857
- setTimeout(check, checkInterval);
2858
- }
2859
- };
2860
- check();
2861
- });
2862
- }, [isReady, initializationError]);
2863
- const ensureReady = useCallback3((operationName) => {
2864
- if (!isReady()) {
2865
- const error = initializationError ? `Crudify initialization failed: ${initializationError}` : isInitializing ? "Crudify is still initializing. Please wait." : "Crudify is not initialized";
2866
- throw new Error(`Cannot perform ${operationName}: ${error}`);
2867
- }
2868
- }, [isReady, initializationError, isInitializing]);
2869
- const readItems = useCallback3(async (moduleKey, filter, options) => {
2870
- ensureReady("readItems");
2871
- console.log("\u{1F4CA} useCrudifyData - readItems called with:");
2872
- console.log(" - moduleKey:", moduleKey);
2873
- console.log(" - filter:", filter);
2874
- console.log(" - options:", options);
2875
- if (moduleKey === "__test_connection__") {
2876
- console.error("\u{1F6A8} FOUND TEST CONNECTION CALL! Stack trace:");
2877
- console.error(new Error().stack);
2878
- }
2879
- try {
2880
- const response = await crudify4.readItems(moduleKey, filter || {}, options);
2881
- console.log("\u{1F4CA} useCrudifyData - readItems response:", response);
2882
- return response;
2883
- } catch (error) {
2884
- console.error("\u{1F4CA} useCrudifyData - readItems error:", error);
2885
- throw error;
2886
- }
2887
- }, [ensureReady]);
2888
- const readItem = useCallback3(async (moduleKey, filter, options) => {
2889
- ensureReady("readItem");
2890
- console.log("\u{1F4CA} useCrudifyData - readItem:", { moduleKey, filter, options });
2891
- try {
2892
- const response = await crudify4.readItem(moduleKey, filter, options);
2893
- console.log("\u{1F4CA} useCrudifyData - readItem response:", response);
2894
- return response;
2895
- } catch (error) {
2896
- console.error("\u{1F4CA} useCrudifyData - readItem error:", error);
2897
- throw error;
2898
- }
2899
- }, [ensureReady]);
2900
- const createItem = useCallback3(async (moduleKey, data, options) => {
2901
- ensureReady("createItem");
2902
- console.log("\u{1F4CA} useCrudifyData - createItem:", { moduleKey, data, options });
2903
- try {
2904
- const response = await crudify4.createItem(moduleKey, data, options);
2905
- console.log("\u{1F4CA} useCrudifyData - createItem response:", response);
2906
- return response;
2907
- } catch (error) {
2908
- console.error("\u{1F4CA} useCrudifyData - createItem error:", error);
2909
- throw error;
2910
- }
2911
- }, [ensureReady]);
2912
- const updateItem = useCallback3(async (moduleKey, data, options) => {
2913
- ensureReady("updateItem");
2914
- console.log("\u{1F4CA} useCrudifyData - updateItem:", { moduleKey, data, options });
2915
- try {
2916
- const response = await crudify4.updateItem(moduleKey, data, options);
2917
- console.log("\u{1F4CA} useCrudifyData - updateItem response:", response);
2918
- return response;
2919
- } catch (error) {
2920
- console.error("\u{1F4CA} useCrudifyData - updateItem error:", error);
2921
- throw error;
2922
- }
2923
- }, [ensureReady]);
2924
- const deleteItem = useCallback3(async (moduleKey, id, options) => {
2925
- ensureReady("deleteItem");
2926
- console.log("\u{1F4CA} useCrudifyData - deleteItem:", { moduleKey, id, options });
2927
- try {
2928
- const response = await crudify4.deleteItem(moduleKey, id, options);
2929
- console.log("\u{1F4CA} useCrudifyData - deleteItem response:", response);
2930
- return response;
2931
- } catch (error) {
2932
- console.error("\u{1F4CA} useCrudifyData - deleteItem error:", error);
2933
- throw error;
2934
- }
2935
- }, [ensureReady]);
2936
- const transaction = useCallback3(async (operations, options) => {
2937
- ensureReady("transaction");
2938
- console.log("\u{1F4CA} useCrudifyData - transaction:", { operations, options });
2939
- try {
2940
- const response = await crudify4.transaction(operations, options);
2941
- console.log("\u{1F4CA} useCrudifyData - transaction response:", response);
2942
- return response;
2943
- } catch (error) {
2944
- console.error("\u{1F4CA} useCrudifyData - transaction error:", error);
2945
- throw error;
2946
- }
2947
- }, [ensureReady]);
2948
- const login = useCallback3(async (email, password) => {
2949
- ensureReady("login");
2950
- console.log("\u{1F4CA} useCrudifyData - login:", { email });
2951
- try {
2952
- const response = await crudify4.login(email, password);
2953
- console.log("\u{1F4CA} useCrudifyData - login response:", response);
2954
- return response;
2955
- } catch (error) {
2956
- console.error("\u{1F4CA} useCrudifyData - login error:", error);
2957
- throw error;
2958
- }
2959
- }, [ensureReady]);
2960
- return {
2961
- // Operaciones básicas CRUD
2962
- readItems,
2963
- readItem,
2964
- createItem,
2965
- updateItem,
2966
- deleteItem,
2967
- // Operaciones avanzadas
2968
- transaction,
2969
- login,
2970
- // Estado de inicialización
2971
- isInitialized,
2972
- isInitializing,
2973
- initializationError,
2974
- // Utilidades
2975
- isReady,
2976
- waitForReady
2977
- };
2978
- };
2979
-
2980
- // src/hooks/useCrudifyInstance.ts
2981
- import { useCallback as useCallback4 } from "react";
2982
- import crudify5 from "@nocios/crudify-browser";
2983
- var useCrudifyInstance = () => {
2984
- const {
2985
- isInitialized,
2986
- isInitializing,
2987
- initializationError
2988
- } = useCrudifyDataContext();
2989
- const isReady = isInitialized && !initializationError && !isInitializing;
2990
- const waitForReady = useCallback4(async () => {
2991
- console.log("\u{1F504} useCrudifyInstance - waitForReady: Starting wait");
2992
- console.log(" - isReady:", isReady);
2993
- console.log(" - isInitialized:", isInitialized);
2994
- console.log(" - isInitializing:", isInitializing);
2995
- console.log(" - initializationError:", initializationError);
2996
- if (isReady) {
2997
- console.log("\u2705 useCrudifyInstance - waitForReady: Already ready, returning immediately");
2998
- return;
2999
- }
3000
- if (initializationError) {
3001
- throw new Error(`Crudify initialization failed: ${initializationError}`);
3002
- }
3003
- try {
3004
- console.log("\u{1F504} useCrudifyInstance - waitForReady: Using CrudifyInitializer.waitForInitialization()");
3005
- const { crudifyInitializer: crudifyInitializer2 } = await import("./CrudifyDataProvider-5GXGNQKI.mjs");
3006
- await crudifyInitializer2.waitForInitialization();
3007
- console.log("\u2705 useCrudifyInstance - waitForReady: CrudifyInitializer completed");
3008
- if (!crudifyInitializer2.isReady()) {
3009
- const error = crudifyInitializer2.getError();
3010
- throw new Error(`Crudify initialization failed: ${error || "Unknown error"}`);
3011
- }
3012
- console.log("\u2705 useCrudifyInstance - waitForReady: Verification successful");
3013
- } catch (error) {
3014
- console.error("\u274C useCrudifyInstance - waitForReady: Error during wait:", error);
3015
- throw error;
3016
- }
3017
- }, [isReady, initializationError, isInitialized, isInitializing]);
3018
- const ensureReady = useCallback4(async (operationName) => {
3019
- if (!isReady) {
3020
- console.log(`\u{1F504} useCrudifyInstance - ${operationName}: Waiting for crudify to be ready...`);
3021
- await waitForReady();
3022
- console.log(`\u2705 useCrudifyInstance - ${operationName}: Crudify is ready`);
3023
- }
3024
- }, [isReady, waitForReady]);
3025
- const ensureTokenSync = useCallback4(async () => {
3026
- console.log("\u{1F504} useCrudifyInstance - ensureTokenSync: Starting token sync check");
3027
- const { tokenManager: tokenManager2 } = await import("./TokenManager-AYUNIXQU.mjs");
3028
- const tmToken = tokenManager2.getToken();
3029
- const crudifyToken = crudify5.getToken?.();
3030
- console.log(" - TokenManager token in sync check:", tmToken ? `${tmToken.substring(0, 20)}...` : "null");
3031
- console.log(" - crudify token in sync check:", crudifyToken ? `${crudifyToken.substring(0, 20)}...` : "null");
3032
- if (tmToken && tmToken !== crudifyToken) {
3033
- console.log("\u{1F504} useCrudifyInstance - Forcing token sync for authenticated operation");
3034
- crudify5.setToken(tmToken);
3035
- console.log(" - crudify token after sync:", crudify5.getToken?.() ? `${crudify5.getToken?.()?.substring(0, 20)}...` : "null");
3036
- } else {
3037
- console.log("\u{1F504} useCrudifyInstance - No token sync needed, tokens match or no token");
3038
- }
3039
- }, []);
3040
- const getStructure = useCallback4(async (options) => {
3041
- console.log("\u{1F4E1} useCrudifyInstance - getStructure: Starting");
3042
- await ensureReady("getStructure");
3043
- try {
3044
- const { tokenManager: tokenManager2 } = await import("./TokenManager-AYUNIXQU.mjs");
3045
- const tmToken = tokenManager2.getToken();
3046
- const crudifyToken = crudify5.getToken?.();
3047
- console.log("\u{1F510} useCrudifyInstance - getStructure: Token status check:");
3048
- console.log(" - TokenManager token:", tmToken ? `${tmToken.substring(0, 20)}...` : "null");
3049
- console.log(" - crudify.getToken():", crudifyToken ? `${crudifyToken.substring(0, 20)}...` : "null");
3050
- console.log(" - Tokens match:", tmToken === crudifyToken);
3051
- await ensureTokenSync();
3052
- console.log("\u{1F4E1} useCrudifyInstance - getStructure: Calling crudify.getStructure");
3053
- const response = await crudify5.getStructure(options);
3054
- console.log("\u{1F4E1} useCrudifyInstance - getStructure: Response received", response);
3055
- return response;
3056
- } catch (error) {
3057
- console.error("\u{1F4E1} useCrudifyInstance - getStructure: Error", error);
3058
- throw error;
3059
- }
3060
- }, [ensureReady, ensureTokenSync]);
3061
- const getStructurePublic = useCallback4(async (options) => {
3062
- console.log("\u{1F4E1} useCrudifyInstance - getStructurePublic: Starting");
3063
- await ensureReady("getStructurePublic");
3064
- try {
3065
- console.log("\u{1F4E1} useCrudifyInstance - getStructurePublic: Calling crudify.getStructurePublic");
3066
- const response = await crudify5.getStructurePublic(options);
3067
- console.log("\u{1F4E1} useCrudifyInstance - getStructurePublic: Response received", response);
3068
- return response;
3069
- } catch (error) {
3070
- console.error("\u{1F4E1} useCrudifyInstance - getStructurePublic: Error", error);
3071
- throw error;
3072
- }
3073
- }, [ensureReady]);
3074
- const readItems = useCallback4(async (moduleKey, filter, options) => {
3075
- await ensureReady("readItems");
3076
- await ensureTokenSync();
3077
- if (moduleKey === "__test_connection__") {
3078
- console.error("\u{1F6A8} FOUND TEST CONNECTION CALL in useCrudifyInstance! Stack trace:");
3079
- console.error(new Error().stack);
3080
- }
3081
- try {
3082
- const response = await crudify5.readItems(moduleKey, filter || {}, options);
3083
- return response;
3084
- } catch (error) {
3085
- console.error("\u{1F4CA} useCrudifyInstance - readItems error:", error);
3086
- throw error;
3087
- }
3088
- }, [ensureReady, ensureTokenSync]);
3089
- const readItem = useCallback4(async (moduleKey, filter, options) => {
3090
- await ensureReady("readItem");
3091
- try {
3092
- const response = await crudify5.readItem(moduleKey, filter, options);
3093
- return response;
3094
- } catch (error) {
3095
- console.error("\u{1F4CA} useCrudifyInstance - readItem error:", error);
3096
- throw error;
3097
- }
3098
- }, [ensureReady]);
3099
- const createItem = useCallback4(async (moduleKey, data, options) => {
3100
- await ensureReady("createItem");
3101
- try {
3102
- const response = await crudify5.createItem(moduleKey, data, options);
3103
- return response;
3104
- } catch (error) {
3105
- console.error("\u{1F4CA} useCrudifyInstance - createItem error:", error);
3106
- throw error;
3107
- }
3108
- }, [ensureReady]);
3109
- const updateItem = useCallback4(async (moduleKey, data, options) => {
3110
- await ensureReady("updateItem");
3111
- try {
3112
- const response = await crudify5.updateItem(moduleKey, data, options);
3113
- return response;
3114
- } catch (error) {
3115
- console.error("\u{1F4CA} useCrudifyInstance - updateItem error:", error);
3116
- throw error;
3117
- }
3118
- }, [ensureReady]);
3119
- const deleteItem = useCallback4(async (moduleKey, id, options) => {
3120
- await ensureReady("deleteItem");
3121
- try {
3122
- const response = await crudify5.deleteItem(moduleKey, id, options);
3123
- return response;
3124
- } catch (error) {
3125
- console.error("\u{1F4CA} useCrudifyInstance - deleteItem error:", error);
3126
- throw error;
3127
- }
3128
- }, [ensureReady]);
3129
- const transaction = useCallback4(async (operations, options) => {
3130
- await ensureReady("transaction");
3131
- try {
3132
- const response = await crudify5.transaction(operations, options);
3133
- return response;
3134
- } catch (error) {
3135
- console.error("\u{1F4CA} useCrudifyInstance - transaction error:", error);
3136
- throw error;
3137
- }
3138
- }, [ensureReady]);
3139
- const login = useCallback4(async (email, password) => {
3140
- await ensureReady("login");
3141
- try {
3142
- const response = await crudify5.login(email, password);
3143
- return response;
3144
- } catch (error) {
3145
- console.error("\u{1F4CA} useCrudifyInstance - login error:", error);
3146
- throw error;
3147
- }
3148
- }, [ensureReady]);
3149
- return {
3150
- // Core operations
3151
- getStructure,
3152
- getStructurePublic,
3153
- readItems,
3154
- readItem,
3155
- createItem,
3156
- updateItem,
3157
- deleteItem,
3158
- transaction,
3159
- login,
3160
- // State information
3161
- isReady,
3162
- isInitialized,
3163
- isInitializing,
3164
- initializationError,
3165
- // Utility methods
3166
- waitForReady
3167
- };
3168
- };
3169
- var getCrudifyInstanceAsync = async () => {
3170
- console.log("\u{1F504} getCrudifyInstanceAsync - Starting");
3171
- const { crudifyInitializer: crudifyInitializer2 } = await import("./CrudifyDataProvider-5GXGNQKI.mjs");
3172
- console.log("\u{1F504} getCrudifyInstanceAsync - Checking if ready");
3173
- console.log(" - crudifyInitializer.isReady():", crudifyInitializer2.isReady());
3174
- console.log(" - crudifyInitializer.getStatus():", crudifyInitializer2.getStatus());
3175
- if (!crudifyInitializer2.isReady()) {
3176
- console.log("\u{1F504} getCrudifyInstanceAsync - Waiting for crudify initialization...");
3177
- await crudifyInitializer2.waitForInitialization();
3178
- if (!crudifyInitializer2.isReady()) {
3179
- const error = crudifyInitializer2.getError();
3180
- throw new Error(`Crudify initialization failed: ${error || "Unknown error after waiting"}`);
3181
- }
3182
- console.log("\u2705 getCrudifyInstanceAsync - Crudify is ready after waiting");
3183
- } else {
3184
- console.log("\u2705 getCrudifyInstanceAsync - Already ready, no wait needed");
3185
- }
3186
- console.log("\u2705 getCrudifyInstanceAsync - Returning crudify instance");
3187
- return crudify5;
3188
- };
3189
- var getCrudifyInstanceSync = async () => {
3190
- const { crudifyInitializer: crudifyInitializer2 } = await import("./CrudifyDataProvider-5GXGNQKI.mjs");
3191
- if (!crudifyInitializer2.isReady()) {
3192
- throw new Error("Crudify not ready. Use getCrudifyInstanceAsync() or call this from within a React component using useCrudifyInstance()");
3193
- }
3194
- return crudify5;
3195
- };
3196
-
3197
2639
  // src/core/SessionManager.ts
3198
- import crudify6 from "@nocios/crudify-browser";
2640
+ import crudify4 from "@nocios/crudify-browser";
3199
2641
 
3200
2642
  // src/utils/tokenStorage.ts
3201
2643
  import CryptoJS from "crypto-js";
@@ -3405,7 +2847,7 @@ var SessionManager = class _SessionManager {
3405
2847
  async login(email, password) {
3406
2848
  try {
3407
2849
  this.log("Attempting login...");
3408
- const response = await crudify6.login(email, password);
2850
+ const response = await crudify4.login(email, password);
3409
2851
  if (!response.success) {
3410
2852
  this.log("Login failed:", response.errors);
3411
2853
  return {
@@ -3440,7 +2882,7 @@ var SessionManager = class _SessionManager {
3440
2882
  async logout() {
3441
2883
  try {
3442
2884
  this.log("Logging out...");
3443
- await crudify6.logout();
2885
+ await crudify4.logout();
3444
2886
  TokenStorage.clearTokens();
3445
2887
  this.log("Logout successful");
3446
2888
  this.config.onLogout?.();
@@ -3460,7 +2902,7 @@ var SessionManager = class _SessionManager {
3460
2902
  this.log("No valid tokens found in storage");
3461
2903
  return false;
3462
2904
  }
3463
- crudify6.setTokens({
2905
+ crudify4.setTokens({
3464
2906
  accessToken: savedTokens.accessToken,
3465
2907
  refreshToken: savedTokens.refreshToken,
3466
2908
  expiresAt: savedTokens.expiresAt,
@@ -3479,13 +2921,13 @@ var SessionManager = class _SessionManager {
3479
2921
  * Verificar si el usuario está autenticado
3480
2922
  */
3481
2923
  isAuthenticated() {
3482
- return crudify6.isLogin() || TokenStorage.hasValidTokens();
2924
+ return crudify4.isLogin() || TokenStorage.hasValidTokens();
3483
2925
  }
3484
2926
  /**
3485
2927
  * Obtener información de tokens actuales
3486
2928
  */
3487
2929
  getTokenInfo() {
3488
- const crudifyTokens = crudify6.getTokenData();
2930
+ const crudifyTokens = crudify4.getTokenData();
3489
2931
  const storageInfo = TokenStorage.getExpirationInfo();
3490
2932
  return {
3491
2933
  isLoggedIn: this.isAuthenticated(),
@@ -3500,7 +2942,7 @@ var SessionManager = class _SessionManager {
3500
2942
  async refreshTokens() {
3501
2943
  try {
3502
2944
  this.log("Manually refreshing tokens...");
3503
- const response = await crudify6.refreshAccessToken();
2945
+ const response = await crudify4.refreshAccessToken();
3504
2946
  if (!response.success) {
3505
2947
  this.log("Token refresh failed:", response.errors);
3506
2948
  TokenStorage.clearTokens();
@@ -3527,7 +2969,7 @@ var SessionManager = class _SessionManager {
3527
2969
  * Configurar interceptor de respuesta para manejo automático de errores
3528
2970
  */
3529
2971
  setupResponseInterceptor() {
3530
- crudify6.setResponseInterceptor(async (response) => {
2972
+ crudify4.setResponseInterceptor(async (response) => {
3531
2973
  if (response.errors) {
3532
2974
  const hasAuthError = response.errors.some(
3533
2975
  (error) => error.message?.includes("Unauthorized") || error.message?.includes("Token") || error.extensions?.code === "UNAUTHENTICATED"
@@ -3550,7 +2992,7 @@ var SessionManager = class _SessionManager {
3550
2992
  */
3551
2993
  clearSession() {
3552
2994
  TokenStorage.clearTokens();
3553
- crudify6.logout();
2995
+ crudify4.logout();
3554
2996
  this.log("Session cleared completely");
3555
2997
  }
3556
2998
  // Métodos privados
@@ -3571,9 +3013,9 @@ var SessionManager = class _SessionManager {
3571
3013
  };
3572
3014
 
3573
3015
  // src/hooks/useSession.ts
3574
- import { useState as useState10, useEffect as useEffect10, useCallback as useCallback5 } from "react";
3016
+ import { useState as useState9, useEffect as useEffect9, useCallback as useCallback2 } from "react";
3575
3017
  function useSession(options = {}) {
3576
- const [state, setState] = useState10({
3018
+ const [state, setState] = useState9({
3577
3019
  isAuthenticated: false,
3578
3020
  isLoading: true,
3579
3021
  isInitialized: false,
@@ -3581,7 +3023,7 @@ function useSession(options = {}) {
3581
3023
  error: null
3582
3024
  });
3583
3025
  const sessionManager = SessionManager.getInstance();
3584
- const initialize = useCallback5(async () => {
3026
+ const initialize = useCallback2(async () => {
3585
3027
  try {
3586
3028
  setState((prev) => ({ ...prev, isLoading: true, error: null }));
3587
3029
  const config = {
@@ -3647,7 +3089,7 @@ function useSession(options = {}) {
3647
3089
  }));
3648
3090
  }
3649
3091
  }, [options.autoRestore, options.enableLogging, options.onSessionExpired, options.onSessionRestored]);
3650
- const login = useCallback5(async (email, password) => {
3092
+ const login = useCallback2(async (email, password) => {
3651
3093
  setState((prev) => ({ ...prev, isLoading: true, error: null }));
3652
3094
  try {
3653
3095
  const result = await sessionManager.login(email, password);
@@ -3684,7 +3126,7 @@ function useSession(options = {}) {
3684
3126
  };
3685
3127
  }
3686
3128
  }, [sessionManager]);
3687
- const logout = useCallback5(async () => {
3129
+ const logout = useCallback2(async () => {
3688
3130
  setState((prev) => ({ ...prev, isLoading: true }));
3689
3131
  try {
3690
3132
  await sessionManager.logout();
@@ -3705,7 +3147,7 @@ function useSession(options = {}) {
3705
3147
  }));
3706
3148
  }
3707
3149
  }, [sessionManager]);
3708
- const refreshTokens = useCallback5(async () => {
3150
+ const refreshTokens = useCallback2(async () => {
3709
3151
  try {
3710
3152
  const success = await sessionManager.refreshTokens();
3711
3153
  if (success) {
@@ -3739,13 +3181,13 @@ function useSession(options = {}) {
3739
3181
  return false;
3740
3182
  }
3741
3183
  }, [sessionManager]);
3742
- const clearError = useCallback5(() => {
3184
+ const clearError = useCallback2(() => {
3743
3185
  setState((prev) => ({ ...prev, error: null }));
3744
3186
  }, []);
3745
- const getTokenInfo = useCallback5(() => {
3187
+ const getTokenInfo = useCallback2(() => {
3746
3188
  return sessionManager.getTokenInfo();
3747
3189
  }, [sessionManager]);
3748
- useEffect10(() => {
3190
+ useEffect9(() => {
3749
3191
  initialize();
3750
3192
  }, [initialize]);
3751
3193
  return {
@@ -3890,13 +3332,13 @@ function SessionDebugInfo() {
3890
3332
  }
3891
3333
 
3892
3334
  // src/components/LoginComponent.tsx
3893
- import { useState as useState11 } from "react";
3335
+ import { useState as useState10 } from "react";
3894
3336
  import { Button as Button8, TextField as TextField5, Box as Box11, Alert as Alert8, Typography as Typography11, CircularProgress as CircularProgress7 } from "@mui/material";
3895
3337
  import { jsx as jsx15, jsxs as jsxs12 } from "react/jsx-runtime";
3896
3338
  function LoginComponent() {
3897
- const [email, setEmail] = useState11("");
3898
- const [password, setPassword] = useState11("");
3899
- const [showForm, setShowForm] = useState11(false);
3339
+ const [email, setEmail] = useState10("");
3340
+ const [password, setPassword] = useState10("");
3341
+ const [showForm, setShowForm] = useState10(false);
3900
3342
  const {
3901
3343
  isAuthenticated,
3902
3344
  isLoading,
@@ -4043,29 +3485,29 @@ function SessionStatus() {
4043
3485
  }
4044
3486
 
4045
3487
  // src/hooks/useUserData.ts
4046
- import { useState as useState12, useEffect as useEffect11, useCallback as useCallback6, useRef as useRef6 } from "react";
4047
- import crudify7 from "@nocios/crudify-browser";
3488
+ import { useState as useState11, useEffect as useEffect10, useCallback as useCallback3, useRef as useRef5 } from "react";
3489
+ import crudify5 from "@nocios/crudify-browser";
4048
3490
  var useUserData = (options = {}) => {
4049
3491
  const { autoFetch = true, retryOnError = false, maxRetries = 3 } = options;
4050
3492
  const { isAuthenticated, isInitialized, sessionData, tokens } = useSessionContext();
4051
- const [userData, setUserData] = useState12(null);
4052
- const [loading, setLoading] = useState12(false);
4053
- const [error, setError] = useState12(null);
4054
- const abortControllerRef = useRef6(null);
4055
- const mountedRef = useRef6(true);
4056
- const requestIdRef = useRef6(0);
4057
- const retryCountRef = useRef6(0);
4058
- const getUserEmail = useCallback6(() => {
3493
+ const [userData, setUserData] = useState11(null);
3494
+ const [loading, setLoading] = useState11(false);
3495
+ const [error, setError] = useState11(null);
3496
+ const abortControllerRef = useRef5(null);
3497
+ const mountedRef = useRef5(true);
3498
+ const requestIdRef = useRef5(0);
3499
+ const retryCountRef = useRef5(0);
3500
+ const getUserEmail = useCallback3(() => {
4059
3501
  if (!sessionData) return null;
4060
3502
  return sessionData.email || sessionData["cognito:username"] || null;
4061
3503
  }, [sessionData]);
4062
- const clearProfile = useCallback6(() => {
3504
+ const clearProfile = useCallback3(() => {
4063
3505
  setUserData(null);
4064
3506
  setError(null);
4065
3507
  setLoading(false);
4066
3508
  retryCountRef.current = 0;
4067
3509
  }, []);
4068
- const refreshProfile = useCallback6(async () => {
3510
+ const refreshProfile = useCallback3(async () => {
4069
3511
  const userEmail = getUserEmail();
4070
3512
  console.log("\u{1F464} useUserData - Refreshing profile for:", userEmail);
4071
3513
  if (!userEmail) {
@@ -4094,7 +3536,7 @@ var useUserData = (options = {}) => {
4094
3536
  setError(null);
4095
3537
  }
4096
3538
  console.log("\u{1F464} useUserData - Fetching profile data from database");
4097
- const response = await crudify7.readItems("users", {
3539
+ const response = await crudify5.readItems("users", {
4098
3540
  filter: { email: userEmail },
4099
3541
  pagination: { limit: 1 }
4100
3542
  });
@@ -4197,14 +3639,14 @@ var useUserData = (options = {}) => {
4197
3639
  }
4198
3640
  }
4199
3641
  }, [isInitialized, getUserEmail, retryOnError, maxRetries]);
4200
- useEffect11(() => {
3642
+ useEffect10(() => {
4201
3643
  if (autoFetch && isAuthenticated && isInitialized) {
4202
3644
  refreshProfile();
4203
3645
  } else if (!isAuthenticated) {
4204
3646
  clearProfile();
4205
3647
  }
4206
3648
  }, [autoFetch, isAuthenticated, isInitialized, refreshProfile, clearProfile]);
4207
- useEffect11(() => {
3649
+ useEffect10(() => {
4208
3650
  mountedRef.current = true;
4209
3651
  return () => {
4210
3652
  mountedRef.current = false;
@@ -4230,7 +3672,7 @@ var useUserData = (options = {}) => {
4230
3672
  };
4231
3673
 
4232
3674
  // src/hooks/useAuth.ts
4233
- import { useCallback as useCallback7 } from "react";
3675
+ import { useCallback as useCallback4 } from "react";
4234
3676
  var useAuth = () => {
4235
3677
  const {
4236
3678
  isAuthenticated,
@@ -4248,7 +3690,7 @@ var useAuth = () => {
4248
3690
  expiresIn,
4249
3691
  refreshExpiresIn
4250
3692
  } = useSessionContext();
4251
- const setToken = useCallback7((token) => {
3693
+ const setToken = useCallback4((token) => {
4252
3694
  if (token) {
4253
3695
  console.warn("useAuth.setToken() is deprecated. Use login() method instead for better security.");
4254
3696
  } else {
@@ -4283,8 +3725,8 @@ var useAuth = () => {
4283
3725
  };
4284
3726
 
4285
3727
  // src/hooks/useData.ts
4286
- import { useCallback as useCallback8 } from "react";
4287
- import crudify8 from "@nocios/crudify-browser";
3728
+ import { useCallback as useCallback5 } from "react";
3729
+ import crudify6 from "@nocios/crudify-browser";
4288
3730
  var useData = () => {
4289
3731
  const {
4290
3732
  isInitialized,
@@ -4293,10 +3735,10 @@ var useData = () => {
4293
3735
  isAuthenticated,
4294
3736
  login: sessionLogin
4295
3737
  } = useSessionContext();
4296
- const isReady = useCallback8(() => {
3738
+ const isReady = useCallback5(() => {
4297
3739
  return isInitialized && !isLoading && !error;
4298
3740
  }, [isInitialized, isLoading, error]);
4299
- const waitForReady = useCallback8(async () => {
3741
+ const waitForReady = useCallback5(async () => {
4300
3742
  return new Promise((resolve, reject) => {
4301
3743
  const checkReady = () => {
4302
3744
  if (isReady()) {
@@ -4310,36 +3752,36 @@ var useData = () => {
4310
3752
  checkReady();
4311
3753
  });
4312
3754
  }, [isReady, error]);
4313
- const ensureReady = useCallback8(async () => {
3755
+ const ensureReady = useCallback5(async () => {
4314
3756
  if (!isReady()) {
4315
3757
  throw new Error("System not ready. Check isInitialized, isLoading, and error states.");
4316
3758
  }
4317
3759
  }, [isReady]);
4318
- const readItems = useCallback8(async (moduleKey, filter, options) => {
3760
+ const readItems = useCallback5(async (moduleKey, filter, options) => {
4319
3761
  await ensureReady();
4320
- return await crudify8.readItems(moduleKey, filter || {}, options);
3762
+ return await crudify6.readItems(moduleKey, filter || {}, options);
4321
3763
  }, [ensureReady]);
4322
- const readItem = useCallback8(async (moduleKey, filter, options) => {
3764
+ const readItem = useCallback5(async (moduleKey, filter, options) => {
4323
3765
  await ensureReady();
4324
- return await crudify8.readItem(moduleKey, filter, options);
3766
+ return await crudify6.readItem(moduleKey, filter, options);
4325
3767
  }, [ensureReady]);
4326
- const createItem = useCallback8(async (moduleKey, data, options) => {
3768
+ const createItem = useCallback5(async (moduleKey, data, options) => {
4327
3769
  await ensureReady();
4328
- return await crudify8.createItem(moduleKey, data, options);
3770
+ return await crudify6.createItem(moduleKey, data, options);
4329
3771
  }, [ensureReady]);
4330
- const updateItem = useCallback8(async (moduleKey, data, options) => {
3772
+ const updateItem = useCallback5(async (moduleKey, data, options) => {
4331
3773
  await ensureReady();
4332
- return await crudify8.updateItem(moduleKey, data, options);
3774
+ return await crudify6.updateItem(moduleKey, data, options);
4333
3775
  }, [ensureReady]);
4334
- const deleteItem = useCallback8(async (moduleKey, id, options) => {
3776
+ const deleteItem = useCallback5(async (moduleKey, id, options) => {
4335
3777
  await ensureReady();
4336
- return await crudify8.deleteItem(moduleKey, id, options);
3778
+ return await crudify6.deleteItem(moduleKey, id, options);
4337
3779
  }, [ensureReady]);
4338
- const transaction = useCallback8(async (operations, options) => {
3780
+ const transaction = useCallback5(async (operations, options) => {
4339
3781
  await ensureReady();
4340
- return await crudify8.transaction(operations, options);
3782
+ return await crudify6.transaction(operations, options);
4341
3783
  }, [ensureReady]);
4342
- const login = useCallback8(async (email, password) => {
3784
+ const login = useCallback5(async (email, password) => {
4343
3785
  try {
4344
3786
  const result = await sessionLogin(email, password);
4345
3787
  if (result.success) {
@@ -4379,8 +3821,116 @@ var useData = () => {
4379
3821
  waitForReady
4380
3822
  };
4381
3823
  };
3824
+
3825
+ // src/components/CrudifyLogin/utils/secureStorage.ts
3826
+ import CryptoJS2 from "crypto-js";
3827
+ var SecureStorage = class {
3828
+ constructor(storageType = "sessionStorage") {
3829
+ this.encryptionKey = this.generateEncryptionKey();
3830
+ this.storage = storageType === "localStorage" ? window.localStorage : window.sessionStorage;
3831
+ }
3832
+ generateEncryptionKey() {
3833
+ const browserFingerprint = [
3834
+ navigator.userAgent,
3835
+ navigator.language,
3836
+ (/* @__PURE__ */ new Date()).getTimezoneOffset(),
3837
+ screen.colorDepth,
3838
+ screen.width,
3839
+ screen.height,
3840
+ "crudify-login"
3841
+ ].join("|");
3842
+ return CryptoJS2.SHA256(browserFingerprint).toString();
3843
+ }
3844
+ setItem(key, value, expiryMinutes) {
3845
+ try {
3846
+ const encrypted = CryptoJS2.AES.encrypt(value, this.encryptionKey).toString();
3847
+ this.storage.setItem(key, encrypted);
3848
+ if (expiryMinutes) {
3849
+ const expiryTime = (/* @__PURE__ */ new Date()).getTime() + expiryMinutes * 60 * 1e3;
3850
+ this.storage.setItem(`${key}_expiry`, expiryTime.toString());
3851
+ }
3852
+ } catch (error) {
3853
+ console.error("Failed to encrypt and store data:", error);
3854
+ }
3855
+ }
3856
+ getItem(key) {
3857
+ try {
3858
+ const expiryKey = `${key}_expiry`;
3859
+ const expiry = this.storage.getItem(expiryKey);
3860
+ if (expiry) {
3861
+ const expiryTime = parseInt(expiry, 10);
3862
+ if ((/* @__PURE__ */ new Date()).getTime() > expiryTime) {
3863
+ this.removeItem(key);
3864
+ return null;
3865
+ }
3866
+ }
3867
+ const encrypted = this.storage.getItem(key);
3868
+ if (!encrypted) return null;
3869
+ const decrypted = CryptoJS2.AES.decrypt(encrypted, this.encryptionKey);
3870
+ const result = decrypted.toString(CryptoJS2.enc.Utf8);
3871
+ if (!result) {
3872
+ console.warn("Failed to decrypt stored data - may be corrupted");
3873
+ this.removeItem(key);
3874
+ return null;
3875
+ }
3876
+ return result;
3877
+ } catch (error) {
3878
+ console.error("Failed to decrypt data:", error);
3879
+ this.removeItem(key);
3880
+ return null;
3881
+ }
3882
+ }
3883
+ removeItem(key) {
3884
+ this.storage.removeItem(key);
3885
+ this.storage.removeItem(`${key}_expiry`);
3886
+ }
3887
+ setToken(token) {
3888
+ try {
3889
+ const parts = token.split(".");
3890
+ if (parts.length === 3) {
3891
+ const payload = JSON.parse(atob(parts[1]));
3892
+ if (payload.exp) {
3893
+ const expiryTime = payload.exp * 1e3;
3894
+ const now = (/* @__PURE__ */ new Date()).getTime();
3895
+ const minutesUntilExpiry = Math.floor((expiryTime - now) / (60 * 1e3));
3896
+ if (minutesUntilExpiry > 0) {
3897
+ this.setItem("authToken", token, minutesUntilExpiry);
3898
+ return;
3899
+ }
3900
+ }
3901
+ }
3902
+ } catch (error) {
3903
+ console.warn("Failed to parse token expiry, using default expiry");
3904
+ }
3905
+ this.setItem("authToken", token, 24 * 60);
3906
+ }
3907
+ getToken() {
3908
+ const token = this.getItem("authToken");
3909
+ if (token) {
3910
+ try {
3911
+ const parts = token.split(".");
3912
+ if (parts.length === 3) {
3913
+ const payload = JSON.parse(atob(parts[1]));
3914
+ if (payload.exp) {
3915
+ const now = Math.floor(Date.now() / 1e3);
3916
+ if (payload.exp < now) {
3917
+ this.removeItem("authToken");
3918
+ return null;
3919
+ }
3920
+ }
3921
+ }
3922
+ } catch (error) {
3923
+ console.warn("Failed to validate token expiry");
3924
+ this.removeItem("authToken");
3925
+ return null;
3926
+ }
3927
+ }
3928
+ return token;
3929
+ }
3930
+ };
3931
+ var secureSessionStorage = new SecureStorage("sessionStorage");
3932
+ var secureLocalStorage = new SecureStorage("localStorage");
4382
3933
  export {
4383
- CrudifyDataProvider,
4384
3934
  CrudifyLogin_default as CrudifyLogin,
4385
3935
  ERROR_CODES,
4386
3936
  ERROR_SEVERITY_MAP,
@@ -4395,13 +3945,9 @@ export {
4395
3945
  SessionStatus,
4396
3946
  TokenStorage,
4397
3947
  UserProfileDisplay_default as UserProfileDisplay,
4398
- configurationManager,
4399
3948
  default2 as crudify,
4400
- crudifyInitializer,
4401
3949
  decodeJwtSafely,
4402
3950
  getCookie,
4403
- getCrudifyInstanceAsync,
4404
- getCrudifyInstanceSync,
4405
3951
  getCurrentUserEmail,
4406
3952
  getErrorMessage,
4407
3953
  handleCrudifyError,
@@ -4411,15 +3957,7 @@ export {
4411
3957
  parseTransactionError,
4412
3958
  secureLocalStorage,
4413
3959
  secureSessionStorage,
4414
- tokenManager,
4415
3960
  useAuth,
4416
- useCrudifyAuth,
4417
- useCrudifyConfig,
4418
- useCrudifyData,
4419
- useCrudifyDataContext,
4420
- useCrudifyInstance,
4421
- useCrudifyLogin,
4422
- useCrudifyUser,
4423
3961
  useData,
4424
3962
  useSession,
4425
3963
  useSessionContext,