@terreno/rtk 0.0.18 → 0.2.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.
@@ -0,0 +1,307 @@
1
+ /**
2
+ * Better Auth Redux slice for session state management.
3
+ *
4
+ * Provides Redux integration for Better Auth, including session synchronization,
5
+ * login/logout actions, and selectors for auth state.
6
+ */
7
+
8
+ import {createListenerMiddleware, createSlice, type PayloadAction} from "@reduxjs/toolkit";
9
+
10
+ import type {BetterAuthClientInterface, BetterAuthUser} from "./betterAuthTypes";
11
+
12
+ /**
13
+ * Global logout action type for compatibility with other auth systems.
14
+ */
15
+ const LOGOUT_ACTION_TYPE = "auth/logout";
16
+
17
+ /**
18
+ * Root state type - loosely typed to avoid circular dependencies.
19
+ */
20
+ // biome-ignore lint/suspicious/noExplicitAny: RootState is loosely typed to work with any Redux store configuration.
21
+ type RootState = any;
22
+
23
+ /**
24
+ * Better Auth Redux state interface.
25
+ */
26
+ export interface BetterAuthState {
27
+ /**
28
+ * Whether the user is authenticated.
29
+ */
30
+ isAuthenticated: boolean;
31
+
32
+ /**
33
+ * The authenticated user's ID, or null if not authenticated.
34
+ */
35
+ userId: string | null;
36
+
37
+ /**
38
+ * The authenticated user data, or null if not authenticated.
39
+ */
40
+ user: BetterAuthUser | null;
41
+
42
+ /**
43
+ * Whether the auth state is currently loading.
44
+ */
45
+ isLoading: boolean;
46
+
47
+ /**
48
+ * Last error message, if any.
49
+ */
50
+ error: string | null;
51
+
52
+ /**
53
+ * Timestamp of the last session sync.
54
+ */
55
+ lastSyncTimestamp: number | null;
56
+ }
57
+
58
+ const initialState: BetterAuthState = {
59
+ error: null,
60
+ isAuthenticated: false,
61
+ isLoading: true,
62
+ lastSyncTimestamp: null,
63
+ user: null,
64
+ userId: null,
65
+ };
66
+
67
+ /**
68
+ * Configuration for generating the Better Auth slice.
69
+ */
70
+ export interface GenerateBetterAuthSliceConfig {
71
+ /**
72
+ * The Better Auth client instance.
73
+ */
74
+ authClient: BetterAuthClientInterface;
75
+
76
+ /**
77
+ * How often to sync the session state (in milliseconds).
78
+ * @default 60000 (1 minute)
79
+ */
80
+ syncInterval?: number;
81
+ }
82
+
83
+ /**
84
+ * Generates a Better Auth Redux slice with session management.
85
+ *
86
+ * @example
87
+ * ```typescript
88
+ * const authClient = createBetterAuthClient({
89
+ * baseURL: "http://localhost:3000",
90
+ * scheme: "terreno",
91
+ * });
92
+ *
93
+ * const betterAuthSlice = generateBetterAuthSlice({ authClient });
94
+ *
95
+ * // Add to your store
96
+ * const store = configureStore({
97
+ * reducer: {
98
+ * betterAuth: betterAuthSlice.reducer,
99
+ * },
100
+ * middleware: (getDefaultMiddleware) =>
101
+ * getDefaultMiddleware().concat(betterAuthSlice.middleware),
102
+ * });
103
+ *
104
+ * // Use in components
105
+ * const isAuthenticated = useSelector(selectBetterAuthIsAuthenticated);
106
+ * const user = useSelector(selectBetterAuthUser);
107
+ *
108
+ * // Trigger logout
109
+ * dispatch(betterAuthSlice.actions.logout());
110
+ * ```
111
+ */
112
+ export const generateBetterAuthSlice = (config: GenerateBetterAuthSliceConfig) => {
113
+ const {authClient} = config;
114
+
115
+ const betterAuthSlice = createSlice({
116
+ initialState,
117
+ name: "betterAuth",
118
+ reducers: {
119
+ /**
120
+ * Clear the session data on logout.
121
+ */
122
+ clearSession: (state) => {
123
+ state.isAuthenticated = false;
124
+ state.userId = null;
125
+ state.user = null;
126
+ state.isLoading = false;
127
+ state.error = null;
128
+ state.lastSyncTimestamp = Date.now();
129
+ },
130
+
131
+ /**
132
+ * Trigger logout action.
133
+ */
134
+ logout: (state) => {
135
+ state.isAuthenticated = false;
136
+ state.userId = null;
137
+ state.user = null;
138
+ state.isLoading = false;
139
+ state.error = null;
140
+ },
141
+
142
+ /**
143
+ * Set error state.
144
+ */
145
+ setError: (state, action: PayloadAction<string | null>) => {
146
+ state.error = action.payload;
147
+ state.isLoading = false;
148
+ },
149
+
150
+ /**
151
+ * Set loading state.
152
+ */
153
+ setLoading: (state, action: PayloadAction<boolean>) => {
154
+ state.isLoading = action.payload;
155
+ },
156
+ /**
157
+ * Set the session data after successful authentication or session refresh.
158
+ */
159
+ setSession: (state, action: PayloadAction<{user: BetterAuthUser; userId: string}>) => {
160
+ state.isAuthenticated = true;
161
+ state.userId = action.payload.userId;
162
+ state.user = action.payload.user;
163
+ state.isLoading = false;
164
+ state.error = null;
165
+ state.lastSyncTimestamp = Date.now();
166
+ },
167
+ },
168
+ });
169
+
170
+ // Listener middleware for handling logout side effects
171
+ const logoutListenerMiddleware = createListenerMiddleware();
172
+
173
+ // Handle logout action - sign out from Better Auth
174
+ logoutListenerMiddleware.startListening({
175
+ actionCreator: betterAuthSlice.actions.logout,
176
+ effect: async (_action, _listenerApi) => {
177
+ try {
178
+ await authClient.signOut();
179
+ console.debug("Better Auth: Signed out successfully");
180
+ } catch (error) {
181
+ console.error("Better Auth: Error signing out:", error);
182
+ }
183
+ },
184
+ });
185
+
186
+ // Also listen for the global logout action type for compatibility
187
+ logoutListenerMiddleware.startListening({
188
+ effect: async (_action, listenerApi) => {
189
+ try {
190
+ await authClient.signOut();
191
+ listenerApi.dispatch(betterAuthSlice.actions.clearSession());
192
+ console.debug("Better Auth: Signed out via global logout action");
193
+ } catch (error) {
194
+ console.error("Better Auth: Error signing out:", error);
195
+ }
196
+ },
197
+ type: LOGOUT_ACTION_TYPE,
198
+ });
199
+
200
+ /**
201
+ * Syncs the session state from Better Auth to Redux.
202
+ * Call this on app startup and periodically to keep state in sync.
203
+ */
204
+ // biome-ignore lint/suspicious/noExplicitAny: Redux dispatch type varies by store configuration
205
+ const syncSession = async (dispatch: any): Promise<void> => {
206
+ dispatch(betterAuthSlice.actions.setLoading(true));
207
+
208
+ try {
209
+ const sessionData = await authClient.getSession();
210
+
211
+ if (sessionData?.data?.user && sessionData?.data?.session) {
212
+ dispatch(
213
+ betterAuthSlice.actions.setSession({
214
+ user: sessionData.data.user as BetterAuthUser,
215
+ userId: sessionData.data.user.id,
216
+ })
217
+ );
218
+ } else {
219
+ dispatch(betterAuthSlice.actions.clearSession());
220
+ }
221
+ } catch (error) {
222
+ console.error("Better Auth: Error syncing session:", error);
223
+ dispatch(betterAuthSlice.actions.setError("Failed to sync session"));
224
+ dispatch(betterAuthSlice.actions.clearSession());
225
+ }
226
+ };
227
+
228
+ return {
229
+ /**
230
+ * Actions for the Better Auth slice.
231
+ */
232
+ actions: betterAuthSlice.actions,
233
+
234
+ /**
235
+ * The Better Auth client instance.
236
+ */
237
+ authClient,
238
+
239
+ /**
240
+ * Middleware for handling Better Auth side effects.
241
+ */
242
+ middleware: [logoutListenerMiddleware.middleware],
243
+
244
+ /**
245
+ * The reducer for the Better Auth slice.
246
+ */
247
+ reducer: betterAuthSlice.reducer,
248
+ /**
249
+ * The Better Auth Redux slice.
250
+ */
251
+ slice: betterAuthSlice,
252
+
253
+ /**
254
+ * Function to sync session state from Better Auth to Redux.
255
+ */
256
+ syncSession,
257
+ };
258
+ };
259
+
260
+ /**
261
+ * Type for the return value of generateBetterAuthSlice.
262
+ */
263
+ export type BetterAuthSlice = ReturnType<typeof generateBetterAuthSlice>;
264
+
265
+ // Selectors
266
+
267
+ /**
268
+ * Selects the entire Better Auth state.
269
+ */
270
+ export const selectBetterAuthState = (state: RootState): BetterAuthState | undefined =>
271
+ // biome-ignore lint/suspicious/noExplicitAny: RootState is loosely typed
272
+ (state as any).betterAuth;
273
+
274
+ /**
275
+ * Selects whether the user is authenticated.
276
+ */
277
+ export const selectBetterAuthIsAuthenticated = (state: RootState): boolean =>
278
+ // biome-ignore lint/suspicious/noExplicitAny: RootState is loosely typed
279
+ (state as any).betterAuth?.isAuthenticated ?? false;
280
+
281
+ /**
282
+ * Selects the current user ID.
283
+ */
284
+ export const selectBetterAuthUserId = (state: RootState): string | null =>
285
+ // biome-ignore lint/suspicious/noExplicitAny: RootState is loosely typed
286
+ (state as any).betterAuth?.userId ?? null;
287
+
288
+ /**
289
+ * Selects the current user data.
290
+ */
291
+ export const selectBetterAuthUser = (state: RootState): BetterAuthUser | null =>
292
+ // biome-ignore lint/suspicious/noExplicitAny: RootState is loosely typed
293
+ (state as any).betterAuth?.user ?? null;
294
+
295
+ /**
296
+ * Selects whether the auth state is loading.
297
+ */
298
+ export const selectBetterAuthIsLoading = (state: RootState): boolean =>
299
+ // biome-ignore lint/suspicious/noExplicitAny: RootState is loosely typed
300
+ (state as any).betterAuth?.isLoading ?? false;
301
+
302
+ /**
303
+ * Selects the last error message.
304
+ */
305
+ export const selectBetterAuthError = (state: RootState): string | null =>
306
+ // biome-ignore lint/suspicious/noExplicitAny: RootState is loosely typed
307
+ (state as any).betterAuth?.error ?? null;
@@ -0,0 +1,81 @@
1
+ /**
2
+ * Better Auth types for use in Redux slices and components.
3
+ *
4
+ * This file contains only type definitions to avoid importing React Native
5
+ * dependencies in environments that don't support them (e.g., tests).
6
+ */
7
+
8
+ /**
9
+ * Configuration options for the Better Auth client.
10
+ */
11
+ export interface BetterAuthClientConfig {
12
+ /**
13
+ * Base URL of the auth server (e.g., "http://localhost:3000").
14
+ */
15
+ baseURL: string;
16
+
17
+ /**
18
+ * App URL scheme for deep linking (e.g., "terreno").
19
+ */
20
+ scheme: string;
21
+
22
+ /**
23
+ * Storage key prefix for auth tokens.
24
+ * @default "terreno"
25
+ */
26
+ storagePrefix?: string;
27
+ }
28
+
29
+ /**
30
+ * User data from Better Auth session.
31
+ */
32
+ export interface BetterAuthUser {
33
+ id: string;
34
+ email: string;
35
+ name: string | null;
36
+ image: string | null;
37
+ emailVerified: boolean;
38
+ createdAt: Date;
39
+ updatedAt: Date;
40
+ }
41
+
42
+ /**
43
+ * Session data from Better Auth.
44
+ */
45
+ export interface BetterAuthSession {
46
+ id: string;
47
+ userId: string;
48
+ expiresAt: Date;
49
+ ipAddress: string | null;
50
+ userAgent: string | null;
51
+ createdAt: Date;
52
+ updatedAt: Date;
53
+ }
54
+
55
+ /**
56
+ * Combined session and user data from Better Auth.
57
+ */
58
+ export interface BetterAuthSessionData {
59
+ session: BetterAuthSession;
60
+ user: BetterAuthUser;
61
+ }
62
+
63
+ /**
64
+ * OAuth provider types supported by Better Auth.
65
+ */
66
+ export type BetterAuthOAuthProvider = "google" | "github" | "apple";
67
+
68
+ /**
69
+ * Minimal interface for the Better Auth client used by the Redux slice.
70
+ * This interface defines only the methods needed by the slice, allowing
71
+ * tests to use mock clients without importing React Native.
72
+ */
73
+ export interface BetterAuthClientInterface {
74
+ getSession: () => Promise<{
75
+ data?: {
76
+ user?: BetterAuthUser;
77
+ session?: BetterAuthSession;
78
+ };
79
+ }>;
80
+ signOut: () => Promise<void>;
81
+ }
package/src/constants.ts CHANGED
@@ -49,9 +49,11 @@ export let baseUrl: string;
49
49
  export let baseWebsocketsUrl: string;
50
50
  export let baseTasksUrl: string;
51
51
 
52
- if (Constants.expoConfig?.extra?.BASE_URL) {
53
- // For prod/staging
54
- baseUrl = Constants.expoConfig?.extra?.BASE_URL;
52
+ const isDev = typeof __DEV__ !== "undefined" && __DEV__;
53
+
54
+ if (process.env.EXPO_PUBLIC_API_URL) {
55
+ // Explicit override (e.g. .env)
56
+ baseUrl = process.env.EXPO_PUBLIC_API_URL;
55
57
  baseWebsocketsUrl = `${baseUrl.replace("api.", "ws.")}/`;
56
58
  baseTasksUrl = `${baseUrl.replace("api.", "tasks.")}/tasks`;
57
59
 
@@ -60,9 +62,33 @@ if (Constants.expoConfig?.extra?.BASE_URL) {
60
62
  Constants.expoConfig?.extra?.APP_ENV ?? "unknown"
61
63
  }, websocket to ${baseWebsocketsUrl}, tasks to ${baseTasksUrl}`
62
64
  );
63
- } else if (process.env.EXPO_PUBLIC_API_URL) {
64
- // For dev web
65
- baseUrl = process.env.EXPO_PUBLIC_API_URL;
65
+ } else if (isDev && Constants.expoConfig?.hostUri) {
66
+ // Dev simulator/device
67
+ baseUrl = `http://${Constants.expoConfig?.hostUri?.split(`:`).shift()?.concat(":4000")}`;
68
+ baseWebsocketsUrl = `ws://${Constants.expoConfig?.hostUri?.split(`:`).shift()?.concat(":4000")}/`;
69
+ baseTasksUrl = `http://${Constants.expoConfig?.hostUri?.split(`:`).shift()?.concat(":4000")}/tasks`;
70
+ console.debug(
71
+ `Base URL set to hostUri ${baseUrl}, websocket to ${baseWebsocketsUrl}`,
72
+ Constants.expoConfig?.hostUri
73
+ );
74
+ } else if (isDev && Constants.experienceUrl) {
75
+ // Dev web (experienceUrl)
76
+ baseUrl = `http:${Constants.experienceUrl?.split(`:`)[1]?.concat(":4000")}`;
77
+ baseWebsocketsUrl = `ws:${Constants.experienceUrl?.split(`:`)[1]?.concat(":4000")}/`;
78
+ baseTasksUrl = `http:${Constants.experienceUrl?.split(`:`)[1]?.concat(":4000")}/tasks`;
79
+ console.debug(
80
+ `Base URL set to experienceUrl ${baseUrl}, websocket to ${baseWebsocketsUrl}`,
81
+ Constants.expoConfig?.hostUri
82
+ );
83
+ } else if (isDev) {
84
+ // Dev web fallback
85
+ baseUrl = `http://localhost:4000`;
86
+ baseWebsocketsUrl = `ws://localhost:4000/`;
87
+ baseTasksUrl = `http://localhost:4000/tasks`;
88
+ console.debug(`Base URL set to localhost ${baseUrl}, websocket to ${baseWebsocketsUrl}`);
89
+ } else if (Constants.expoConfig?.extra?.BASE_URL) {
90
+ // Prod/staging
91
+ baseUrl = Constants.expoConfig?.extra?.BASE_URL;
66
92
  baseWebsocketsUrl = `${baseUrl.replace("api.", "ws.")}/`;
67
93
  baseTasksUrl = `${baseUrl.replace("api.", "tasks.")}/tasks`;
68
94
 
@@ -72,34 +98,24 @@ if (Constants.expoConfig?.extra?.BASE_URL) {
72
98
  }, websocket to ${baseWebsocketsUrl}, tasks to ${baseTasksUrl}`
73
99
  );
74
100
  } else if (Constants.expoConfig?.hostUri) {
75
- // For dev simulator/device
76
- baseUrl = `http://${Constants.expoConfig?.hostUri?.split(`:`).shift()?.concat(":3000")}`;
77
- baseWebsocketsUrl = `ws://${Constants.expoConfig?.hostUri?.split(`:`).shift()?.concat(":3000")}/`;
78
- baseTasksUrl = `http://${Constants.expoConfig?.hostUri?.split(`:`).shift()?.concat(":3000")}/tasks`;
101
+ baseUrl = `http://${Constants.expoConfig?.hostUri?.split(`:`).shift()?.concat(":4000")}`;
102
+ baseWebsocketsUrl = `ws://${Constants.expoConfig?.hostUri?.split(`:`).shift()?.concat(":4000")}/`;
103
+ baseTasksUrl = `http://${Constants.expoConfig?.hostUri?.split(`:`).shift()?.concat(":4000")}/tasks`;
79
104
  console.debug(
80
105
  `Base URL set to hostUri ${baseUrl}, websocket to ${baseWebsocketsUrl}`,
81
106
  Constants.expoConfig?.hostUri
82
107
  );
83
108
  } else if (Constants.experienceUrl) {
84
- // For dev web
85
- baseUrl = `http:${Constants.experienceUrl?.split(`:`)[1]?.concat(":3000")}`;
86
- baseWebsocketsUrl = `ws:${Constants.experienceUrl?.split(`:`)[1]?.concat(":3000")}/`;
87
- baseTasksUrl = `http:${Constants.experienceUrl?.split(`:`)[1]?.concat(":3000")}/tasks`;
109
+ baseUrl = `http:${Constants.experienceUrl?.split(`:`)[1]?.concat(":4000")}`;
110
+ baseWebsocketsUrl = `ws:${Constants.experienceUrl?.split(`:`)[1]?.concat(":4000")}/`;
111
+ baseTasksUrl = `http:${Constants.experienceUrl?.split(`:`)[1]?.concat(":4000")}/tasks`;
88
112
  console.debug(
89
113
  `Base URL set to experienceUrl ${baseUrl}, websocket to ${baseWebsocketsUrl}`,
90
114
  Constants.expoConfig?.hostUri
91
115
  );
92
- } else if (
93
- !Constants.expoConfig?.extra?.BASE_URL &&
94
- !Constants.expoConfig?.hostUri &&
95
- !Constants.experienceUrl
96
- ) {
97
- // For dev web, which doesn't have experienceUrl for some reason?
98
- baseUrl = `http://localhost:3000`;
99
- baseWebsocketsUrl = `ws://localhost:3000/`;
100
- baseTasksUrl = `http://localhost:3000/tasks`;
101
- console.debug(`Base URL set to localhost ${baseUrl}, websocket to ${baseWebsocketsUrl}`);
102
116
  } else {
103
- console.error("No base URL found", Constants.expoConfig, Constants.experienceUrl);
104
- throw new Error("No base URL found");
117
+ baseUrl = `http://localhost:4000`;
118
+ baseWebsocketsUrl = `ws://localhost:4000/`;
119
+ baseTasksUrl = `http://localhost:4000/tasks`;
120
+ console.debug(`Base URL set to localhost ${baseUrl}, websocket to ${baseWebsocketsUrl}`);
105
121
  }
package/src/index.ts CHANGED
@@ -1,4 +1,7 @@
1
1
  export * from "./authSlice";
2
+ export * from "./betterAuthClient";
3
+ export * from "./betterAuthSlice";
4
+ export * from "./betterAuthTypes";
2
5
  export * from "./constants";
3
6
  export * from "./emptyApi";
4
7
  export * from "./mongooseSlice";
@@ -47,7 +47,9 @@ export const generateTags = (api: any, tagTypes: string[]): any => {
47
47
  if (!endpoint.toLowerCase().includes("byid")) {
48
48
  const tag = tagTypes.find((t: string) =>
49
49
  // remove "get" from the endpoint name and "ById" from the endpoint name
50
- t.toLowerCase().includes(cleanEndpointStringToGenerateTag(endpoint))
50
+ t
51
+ .toLowerCase()
52
+ .includes(cleanEndpointStringToGenerateTag(endpoint))
51
53
  );
52
54
  if (tag) {
53
55
  tags[endpoint] = {providesTags: providesIdTags(tag)};