@etdt/etdt-e-comps 1.0.0 → 1.1.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/README.md CHANGED
@@ -1,5 +1,13 @@
1
1
  # etdt-e-comps
2
2
 
3
+ ## Instalar
4
+
5
+ ```sh
6
+ npm install @etdt/etdt-e-comps
7
+ ```
8
+
9
+ ## Componentes
10
+
3
11
  Componentes reutilizables para aplicaciones React con Ionic:
4
12
 
5
13
  - `PForm`: formulario con campos Ionic y validación de `react-hook-form`.
@@ -7,15 +15,117 @@ Componentes reutilizables para aplicaciones React con Ionic:
7
15
  - `PFooter`: pie de página Ionic con texto opcional.
8
16
  - `PRecordList`: lista de registros con acciones opcionales.
9
17
 
10
- ## Instalar y usar
18
+ ### Utilizar los componentes
11
19
 
12
- ```sh
13
- npm install etdt-e-comps
20
+ ```tsx
21
+ import { PFooter, PForm, PInput, PRecordList } from '@etdt/etdt-e-comps';
14
22
  ```
15
23
 
24
+ > La aplicación que utilice estos componentes debe tener instaladas las dependencias
25
+ peer declaradas en `package.json`.
26
+
27
+ ## Contexto de autenticación (AuthContext.tsx)
28
+
29
+ Contexto de autenticación para compartir el estado del usuario y las operaciones de inicio y
30
+ cierre de sesión entre los componentes de la aplicación, delegando la comunicación con el
31
+ servidor en un adaptador configurable.
32
+
33
+ `createAuthContext<TUser, TLoginInput>(options)` crea un proveedor y un hook tipados.
34
+ `TUser` es el tipo del usuario y `TLoginInput` el tipo de los datos necesarios para iniciar
35
+ sesión.
36
+
37
+ El almacenamiento se configura mediante un objeto `AuthStorage` que permite proporcionar una
38
+ implementación propia de `getItem`, `setItem` y `removeItem` o con los siguientes `storage`:
39
+
40
+ - `local`: usa `localStorage`.
41
+ - `session`: usa `sessionStorage`.
42
+ - `memory`: usa un `Map` en memoria; los datos se pierden al recargar o cerrar la pestaña.
43
+
44
+ > Por defecto se tiene `storage: 'localStorage'` y `storageKey: 'user'`.
45
+
46
+ La autenticación se conecta mediante un `AuthAdapter<TUser, TLoginInput>`, que debe
47
+ implementar `login` y `logout`. Puede implementar también `restoreSession` para recuperar
48
+ la sesión al iniciar o cuando se llame a `refreshSession`. Por ejemplo, para una aplicación
49
+ que autentica mediante cookies:
50
+
16
51
  ```tsx
17
- import { PFooter, PForm, PInput, PRecordList } from 'etdt-e-comps';
52
+ import {
53
+ createAuthContext,
54
+ type AuthAdapter,
55
+ } from '@etdt/etdt-e-comps';
56
+
57
+ interface User {
58
+ id: number;
59
+ name: string;
60
+ }
61
+
62
+ interface LoginInput {
63
+ username: string;
64
+ password: string;
65
+ }
66
+
67
+ const authAdapter: AuthAdapter<User, LoginInput> = {
68
+ async login(input) {
69
+ const response = await fetch('/api/login', {
70
+ method: 'POST',
71
+ headers: { 'Content-Type': 'application/json' },
72
+ credentials: 'include',
73
+ body: JSON.stringify(input),
74
+ });
75
+ if (!response.ok) {
76
+ throw new Error(`Login failed (${response.status})`);
77
+ }
78
+ return (await response.json()) as User;
79
+ },
80
+
81
+ async restoreSession() {
82
+ const response = await fetch('/api/get_user', {
83
+ credentials: 'include',
84
+ });
85
+ if (response.status === 401) {
86
+ return null;
87
+ }
88
+ if (!response.ok) {
89
+ throw new Error(`Session restore failed (${response.status})`);
90
+ }
91
+ return (await response.json()) as User;
92
+ },
93
+
94
+ async logout() {
95
+ const response = await fetch('/api/logout', {
96
+ method: 'POST',
97
+ credentials: 'include',
98
+ });
99
+ if (!response.ok) {
100
+ throw new Error(`Logout failed (${response.status})`);
101
+ }
102
+ },
103
+ };
104
+
105
+ const { AuthProvider, useAuth } = createAuthContext<User, LoginInput>({
106
+ storage: 'local',
107
+ });
108
+
109
+
110
+ const UserProvider = ({ children }: { children: React.ReactNode }) => (
111
+ <AuthProvider adapter={authAdapter}>{children}</AuthProvider>
112
+ );
113
+
114
+ export default UserProvider
18
115
  ```
19
116
 
20
- > La aplicación que utilice estos componentes debe tener instaladas las dependencias
21
- peer declaradas en `package.json`.
117
+ `restoreSession` devuelve el usuario si la sesión sigue activa o `null` si no lo está.
118
+ El ejemplo supone que `/api/get_user` responde directamente con el usuario y devuelve
119
+ HTTP 401 cuando no hay sesión; adapta el manejo de la respuesta al contrato de tu API.
120
+ El paquete no gestiona ni almacena el token o la cookie de sesión: eso corresponde a la
121
+ aplicación y al servidor.
122
+
123
+ El hook expone `user`, `isLoading`, `restoreError`, `login`, `logout`, `updateUser` y
124
+ `refreshSession`. `login` y `logout` delegan en el adaptador. `updateUser` combina los
125
+ cambios indicados con el usuario actual. `refreshSession` vuelve a llamar a
126
+ `adapter.restoreSession`; si no se ha proporcionado ese método, lanza un error. El hook
127
+ debe usarse dentro de su `AuthProvider`.
128
+
129
+ El usuario guardado se serializa como JSON y se parsea al leerlo. El paquete no valida la
130
+ forma de los datos leídos; valida la respuesta del servidor y cualquier dato almacenado si
131
+ no confías en su origen.
@@ -0,0 +1,33 @@
1
+ import { type ReactElement, type ReactNode } from 'react';
2
+ export interface AuthAdapter<TUser, TLoginInput> {
3
+ login: (input: TLoginInput) => Promise<TUser>;
4
+ logout: () => Promise<void>;
5
+ restoreSession?: () => Promise<TUser | null>;
6
+ }
7
+ export interface AuthContextValue<TUser, TLoginInput> {
8
+ user: TUser | null;
9
+ isLoading: boolean;
10
+ restoreError: unknown | null;
11
+ login: (input: TLoginInput) => Promise<void>;
12
+ logout: () => Promise<void>;
13
+ updateUser: (data: Partial<TUser>) => void;
14
+ refreshSession: () => Promise<TUser | null>;
15
+ }
16
+ export interface AuthStorage {
17
+ getItem: (key: string) => string | null;
18
+ setItem: (key: string, value: string) => void;
19
+ removeItem: (key: string) => void;
20
+ }
21
+ export interface AuthContextOptions {
22
+ storage?: 'local' | 'session' | 'memory' | AuthStorage;
23
+ storageKey?: string;
24
+ }
25
+ export interface AuthProviderProps<TUser, TLoginInput> {
26
+ adapter: AuthAdapter<TUser, TLoginInput>;
27
+ children: ReactNode;
28
+ }
29
+ export declare function createAuthContext<TUser, TLoginInput>(options?: AuthContextOptions): {
30
+ AuthProvider: ({ adapter, children, }: AuthProviderProps<TUser, TLoginInput>) => ReactElement;
31
+ useAuth: () => AuthContextValue<TUser, TLoginInput>;
32
+ };
33
+ //# sourceMappingURL=AuthContext.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"AuthContext.d.ts","sourceRoot":"","sources":["../src/AuthContext.tsx"],"names":[],"mappings":"AAAA,OAAO,EAML,KAAK,YAAY,EACjB,KAAK,SAAS,EACf,MAAM,OAAO,CAAC;AAEf,MAAM,WAAW,WAAW,CAAC,KAAK,EAAE,WAAW;IAC7C,KAAK,EAAE,CAAC,KAAK,EAAE,WAAW,KAAK,OAAO,CAAC,KAAK,CAAC,CAAC;IAC9C,MAAM,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,CAAC;IAC5B,cAAc,CAAC,EAAE,MAAM,OAAO,CAAC,KAAK,GAAG,IAAI,CAAC,CAAC;CAC9C;AAED,MAAM,WAAW,gBAAgB,CAAC,KAAK,EAAE,WAAW;IAClD,IAAI,EAAE,KAAK,GAAG,IAAI,CAAC;IACnB,SAAS,EAAE,OAAO,CAAC;IACnB,YAAY,EAAE,OAAO,GAAG,IAAI,CAAC;IAC7B,KAAK,EAAE,CAAC,KAAK,EAAE,WAAW,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;IAC7C,MAAM,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,CAAC;IAC5B,UAAU,EAAE,CAAC,IAAI,EAAE,OAAO,CAAC,KAAK,CAAC,KAAK,IAAI,CAAC;IAC3C,cAAc,EAAE,MAAM,OAAO,CAAC,KAAK,GAAG,IAAI,CAAC,CAAC;CAC7C;AAED,MAAM,WAAW,WAAW;IAC1B,OAAO,EAAE,CAAC,GAAG,EAAE,MAAM,KAAK,MAAM,GAAG,IAAI,CAAC;IACxC,OAAO,EAAE,CAAC,GAAG,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,KAAK,IAAI,CAAC;IAC9C,UAAU,EAAE,CAAC,GAAG,EAAE,MAAM,KAAK,IAAI,CAAC;CACnC;AAED,MAAM,WAAW,kBAAkB;IACjC,OAAO,CAAC,EAAE,OAAO,GAAG,SAAS,GAAG,QAAQ,GAAG,WAAW,CAAC;IACvD,UAAU,CAAC,EAAE,MAAM,CAAC;CACrB;AAED,MAAM,WAAW,iBAAiB,CAAC,KAAK,EAAE,WAAW;IACnD,OAAO,EAAE,WAAW,CAAC,KAAK,EAAE,WAAW,CAAC,CAAC;IACzC,QAAQ,EAAE,SAAS,CAAC;CACrB;AAeD,wBAAgB,iBAAiB,CAAC,KAAK,EAAE,WAAW,EAClD,OAAO,GAAE,kBAAuB;2CA8B7B,iBAAiB,CAAC,KAAK,EAAE,WAAW,CAAC,KAAG,YAAY;mBAqInC,gBAAgB,CAAC,KAAK,EAAE,WAAW,CAAC;EASzD"}
@@ -0,0 +1,155 @@
1
+ import { jsx as _jsx } from "react/jsx-runtime";
2
+ import { createContext, useContext, useEffect, useRef, useState, } from 'react';
3
+ function createMemoryStorage() {
4
+ const values = new Map();
5
+ return {
6
+ getItem: (key) => values.get(key) ?? null,
7
+ setItem: (key, value) => {
8
+ values.set(key, value);
9
+ },
10
+ removeItem: (key) => {
11
+ values.delete(key);
12
+ },
13
+ };
14
+ }
15
+ export function createAuthContext(options = {}) {
16
+ const AuthContext = createContext(undefined);
17
+ const memoryStorage = createMemoryStorage();
18
+ const storageKey = options.storageKey ?? 'user';
19
+ const getStorage = () => {
20
+ if (typeof options.storage === 'object') {
21
+ return options.storage;
22
+ }
23
+ if (options.storage === 'memory') {
24
+ return memoryStorage;
25
+ }
26
+ if (typeof window === 'undefined') {
27
+ return undefined;
28
+ }
29
+ if (options.storage === 'local') {
30
+ return window.localStorage;
31
+ }
32
+ if (options.storage === 'session') {
33
+ return window.sessionStorage;
34
+ }
35
+ return window.localStorage;
36
+ };
37
+ function AuthProvider({ adapter, children, }) {
38
+ const [user, setUser] = useState(() => {
39
+ const storage = getStorage();
40
+ if (!storage) {
41
+ return null;
42
+ }
43
+ try {
44
+ const storedUser = storage.getItem(storageKey);
45
+ return storedUser === null ? null : JSON.parse(storedUser);
46
+ }
47
+ catch (error) {
48
+ const detail = error instanceof Error ? error.message : String(error);
49
+ throw new Error(`Unable to read auth user from storage key "${storageKey}": ${detail}`);
50
+ }
51
+ });
52
+ const shouldRestoreSession = useRef(user === null);
53
+ const [isLoading, setIsLoading] = useState(adapter.restoreSession !== undefined && user === null);
54
+ const [restoreError, setRestoreError] = useState(null);
55
+ useEffect(() => {
56
+ const storage = getStorage();
57
+ if (!storage) {
58
+ return;
59
+ }
60
+ try {
61
+ if (user === null) {
62
+ storage.removeItem(storageKey);
63
+ }
64
+ else {
65
+ storage.setItem(storageKey, JSON.stringify(user));
66
+ }
67
+ }
68
+ catch (error) {
69
+ const detail = error instanceof Error ? error.message : String(error);
70
+ throw new Error(`Unable to persist auth user to storage key "${storageKey}": ${detail}`);
71
+ }
72
+ }, [storageKey, user]);
73
+ useEffect(() => {
74
+ const restoreSession = adapter.restoreSession;
75
+ if (!restoreSession || !shouldRestoreSession.current) {
76
+ setIsLoading(false);
77
+ return;
78
+ }
79
+ let cancelled = false;
80
+ setIsLoading(true);
81
+ setRestoreError(null);
82
+ const restore = async () => {
83
+ try {
84
+ const restoredUser = await restoreSession();
85
+ if (!cancelled) {
86
+ setUser(restoredUser);
87
+ }
88
+ }
89
+ catch (error) {
90
+ if (!cancelled) {
91
+ setRestoreError(error);
92
+ }
93
+ }
94
+ finally {
95
+ if (!cancelled) {
96
+ setIsLoading(false);
97
+ shouldRestoreSession.current = false;
98
+ }
99
+ }
100
+ };
101
+ void restore();
102
+ return () => {
103
+ cancelled = true;
104
+ };
105
+ }, [adapter]);
106
+ const refreshSession = async () => {
107
+ if (!adapter.restoreSession) {
108
+ throw new Error('Refreshing the session requires a restoreSession adapter.');
109
+ }
110
+ setIsLoading(true);
111
+ setRestoreError(null);
112
+ try {
113
+ const restoredUser = await adapter.restoreSession();
114
+ setUser(restoredUser);
115
+ return restoredUser;
116
+ }
117
+ catch (error) {
118
+ setRestoreError(error);
119
+ throw error;
120
+ }
121
+ finally {
122
+ setIsLoading(false);
123
+ }
124
+ };
125
+ const login = async (input) => {
126
+ const authenticatedUser = await adapter.login(input);
127
+ setUser(authenticatedUser);
128
+ setRestoreError(null);
129
+ };
130
+ const logout = async () => {
131
+ await adapter.logout();
132
+ setUser(null);
133
+ };
134
+ const updateUser = (data) => {
135
+ setUser((currentUser) => currentUser === null ? null : { ...currentUser, ...data });
136
+ };
137
+ return (_jsx(AuthContext.Provider, { value: {
138
+ user,
139
+ isLoading,
140
+ restoreError,
141
+ login,
142
+ logout,
143
+ updateUser,
144
+ refreshSession,
145
+ }, children: children }));
146
+ }
147
+ function useAuth() {
148
+ const context = useContext(AuthContext);
149
+ if (!context) {
150
+ throw new Error('useAuth must be used within its AuthProvider');
151
+ }
152
+ return context;
153
+ }
154
+ return { AuthProvider, useAuth };
155
+ }
package/dist/index.d.ts CHANGED
@@ -5,4 +5,6 @@ export type { PInputOption, PInputProps, } from './PInput/PInput.types.js';
5
5
  export { default as PFooter } from './PFooter.js';
6
6
  export { default as PRecordList } from './PRecordList.js';
7
7
  export type { PRecord, PRecordAction, PRecordListProps, } from './PRecordList.js';
8
+ export { createAuthContext } from './AuthContext.js';
9
+ export type { AuthAdapter, AuthContextValue, AuthContextOptions, AuthProviderProps, AuthStorage, } from './AuthContext.js';
8
10
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,IAAI,KAAK,EAAE,MAAM,kBAAkB,CAAC;AACpD,YAAY,EACV,WAAW,EACX,UAAU,EACV,UAAU,GACX,MAAM,wBAAwB,CAAC;AAEhC,OAAO,EAAE,OAAO,IAAI,MAAM,EAAE,MAAM,oBAAoB,CAAC;AACvD,YAAY,EACV,YAAY,EACZ,WAAW,GACZ,MAAM,0BAA0B,CAAC;AAElC,OAAO,EAAE,OAAO,IAAI,OAAO,EAAE,MAAM,cAAc,CAAC;AAElD,OAAO,EAAE,OAAO,IAAI,WAAW,EAAE,MAAM,kBAAkB,CAAC;AAC1D,YAAY,EACV,OAAO,EACP,aAAa,EACb,gBAAgB,GACjB,MAAM,kBAAkB,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,IAAI,KAAK,EAAE,MAAM,kBAAkB,CAAC;AACpD,YAAY,EACV,WAAW,EACX,UAAU,EACV,UAAU,GACX,MAAM,wBAAwB,CAAC;AAEhC,OAAO,EAAE,OAAO,IAAI,MAAM,EAAE,MAAM,oBAAoB,CAAC;AACvD,YAAY,EACV,YAAY,EACZ,WAAW,GACZ,MAAM,0BAA0B,CAAC;AAElC,OAAO,EAAE,OAAO,IAAI,OAAO,EAAE,MAAM,cAAc,CAAC;AAElD,OAAO,EAAE,OAAO,IAAI,WAAW,EAAE,MAAM,kBAAkB,CAAC;AAC1D,YAAY,EACV,OAAO,EACP,aAAa,EACb,gBAAgB,GACjB,MAAM,kBAAkB,CAAC;AAE1B,OAAO,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AACrD,YAAY,EACV,WAAW,EACX,gBAAgB,EAChB,kBAAkB,EAClB,iBAAiB,EACjB,WAAW,GACZ,MAAM,kBAAkB,CAAC"}
package/dist/index.js CHANGED
@@ -2,3 +2,4 @@ export { default as PForm } from './PForm/PForm.js';
2
2
  export { default as PInput } from './PInput/PInput.js';
3
3
  export { default as PFooter } from './PFooter.js';
4
4
  export { default as PRecordList } from './PRecordList.js';
5
+ export { createAuthContext } from './AuthContext.js';
package/package.json CHANGED
@@ -1,10 +1,11 @@
1
1
  {
2
2
  "name": "@etdt/etdt-e-comps",
3
- "version": "1.0.0",
3
+ "version": "1.1.0",
4
4
  "description": "Reusable Ionic React form components",
5
5
  "keywords": [
6
6
  "react",
7
- "typescript"
7
+ "typescript",
8
+ "ionic"
8
9
  ],
9
10
  "homepage": "https://gitlab.com/etdt/etdt-e-comps#readme",
10
11
  "bugs": {
@@ -17,6 +18,8 @@
17
18
  "license": "MIT",
18
19
  "author": "ETDT",
19
20
  "type": "module",
21
+ "main": "./dist/index.js",
22
+ "types": "./dist/index.d.ts",
20
23
  "exports": {
21
24
  ".": {
22
25
  "types": "./dist/index.d.ts",
@@ -24,13 +27,12 @@
24
27
  "default": "./dist/index.js"
25
28
  }
26
29
  },
27
- "main": "./dist/index.js",
28
- "types": "./dist/index.d.ts",
29
30
  "files": [
30
31
  "dist",
31
32
  "README.md",
32
33
  "LICENSE"
33
34
  ],
35
+ "sideEffects": false,
34
36
  "scripts": {
35
37
  "build": "tsc --project tsconfig.json",
36
38
  "prepack": "npm run build"
@@ -39,6 +41,13 @@
39
41
  "moment": "^2.30.1",
40
42
  "ionicons": "^7.0.0"
41
43
  },
44
+ "peerDependencies": {
45
+ "@capacitor/core": "^7.0.0",
46
+ "@ionic/react": "^9.0.0",
47
+ "react": "^18.2.0",
48
+ "react-dom": "^18.2.0",
49
+ "react-hook-form": "^7.53.2"
50
+ },
42
51
  "devDependencies": {
43
52
  "@capacitor/core": "^7.0.0",
44
53
  "@ionic/react": "^9.0.0",
@@ -48,13 +57,5 @@
48
57
  "react-dom": "^18.0.0",
49
58
  "react-hook-form": "^7.0.0",
50
59
  "typescript": "^5.4.0"
51
- },
52
- "peerDependencies": {
53
- "@capacitor/core": "^7.0.0",
54
- "@ionic/react": "^9.0.0",
55
- "react": "^18.2.0",
56
- "react-dom": "^18.2.0",
57
- "react-hook-form": "^7.53.2"
58
- },
59
- "sideEffects": false
60
+ }
60
61
  }