@terreno/rtk 0.24.0 → 0.25.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.
Files changed (39) hide show
  1. package/dist/betterAuthSlice.d.ts +9 -5
  2. package/dist/betterAuthSlice.d.ts.map +1 -1
  3. package/dist/betterAuthSlice.js +7 -20
  4. package/dist/betterAuthSlice.js.map +1 -1
  5. package/dist/isolated/constants.test.d.ts +2 -0
  6. package/dist/isolated/constants.test.d.ts.map +1 -0
  7. package/dist/isolated/{constants.isolated.js → constants.test.js} +1 -1
  8. package/dist/isolated/constants.test.js.map +1 -0
  9. package/dist/useFeatureFlags.d.ts.map +1 -1
  10. package/dist/useFeatureFlags.js +4 -3
  11. package/dist/useFeatureFlags.js.map +1 -1
  12. package/dist/useRealtimeDebug.test.d.ts +2 -0
  13. package/dist/useRealtimeDebug.test.d.ts.map +1 -0
  14. package/dist/useRealtimeDebug.test.js +131 -0
  15. package/dist/useRealtimeDebug.test.js.map +1 -0
  16. package/dist/useServerStatus.test.js +49 -0
  17. package/dist/useServerStatus.test.js.map +1 -1
  18. package/dist/useTerrenoFeatureFlags.test.js +15 -0
  19. package/dist/useTerrenoFeatureFlags.test.js.map +1 -1
  20. package/dist/useUpgradeCheck.test.d.ts +2 -0
  21. package/dist/useUpgradeCheck.test.d.ts.map +1 -0
  22. package/dist/useUpgradeCheck.test.js +174 -0
  23. package/dist/useUpgradeCheck.test.js.map +1 -0
  24. package/dist/useUpgradeCheckNative.test.d.ts +2 -0
  25. package/dist/useUpgradeCheckNative.test.d.ts.map +1 -0
  26. package/dist/useUpgradeCheckNative.test.js +90 -0
  27. package/dist/useUpgradeCheckNative.test.js.map +1 -0
  28. package/package.json +2 -2
  29. package/src/betterAuthSlice.ts +19 -18
  30. package/src/useFeatureFlags.ts +4 -3
  31. package/src/useRealtimeDebug.test.ts +173 -0
  32. package/src/useServerStatus.test.ts +68 -0
  33. package/src/useTerrenoFeatureFlags.test.ts +25 -0
  34. package/src/useUpgradeCheck.test.ts +226 -0
  35. package/src/useUpgradeCheckNative.test.ts +124 -0
  36. package/dist/isolated/constants.isolated.d.ts +0 -2
  37. package/dist/isolated/constants.isolated.d.ts.map +0 -1
  38. package/dist/isolated/constants.isolated.js.map +0 -1
  39. /package/src/isolated/{constants.isolated.ts → constants.test.ts} +0 -0
@@ -0,0 +1,174 @@
1
+ import { afterEach, beforeEach, describe, expect, it, mock } from "bun:test";
2
+ import { configureStore } from "@reduxjs/toolkit";
3
+ import { act, renderHook } from "@testing-library/react-native";
4
+ import Constants from "expo-constants";
5
+ import React from "react";
6
+ import { Provider } from "react-redux";
7
+ // Capture the AppState "change" handler so tests can simulate foreground transitions.
8
+ let appStateChangeHandler;
9
+ const appStateMock = {
10
+ addEventListener: (_event, handler) => {
11
+ appStateChangeHandler = handler;
12
+ return { remove: () => { } };
13
+ },
14
+ currentState: "active",
15
+ };
16
+ // Keep this react-native mock a superset of the preload's mock so other test
17
+ // files still resolve AppState / Linking / Platform after this file runs.
18
+ mock.module("react-native", () => ({
19
+ AppState: appStateMock,
20
+ Linking: { openURL: async () => true },
21
+ Platform: { OS: "web" },
22
+ StyleSheet: { create: (s) => s },
23
+ }));
24
+ // Force IsWeb=true regardless of load order with the native test files.
25
+ mock.module("./platform", () => ({ IsWeb: true }));
26
+ const { emptySplitApi } = await import("./emptyApi");
27
+ const { useUpgradeCheck } = await import("./useUpgradeCheck");
28
+ const constantsWithExtra = Constants;
29
+ const createTestStore = () => configureStore({
30
+ middleware: (getDefaultMiddleware) => getDefaultMiddleware().concat(emptySplitApi.middleware),
31
+ reducer: { [emptySplitApi.reducerPath]: emptySplitApi.reducer },
32
+ });
33
+ const createWrapper = (store) => {
34
+ const Wrapper = ({ children }) => React.createElement(Provider, { children, store });
35
+ return Wrapper;
36
+ };
37
+ const mockFetchWith = (payload) => {
38
+ const fetchFn = mock(async () => new Response(JSON.stringify(payload), {
39
+ headers: { "content-type": "application/json" },
40
+ status: 200,
41
+ }));
42
+ globalThis.fetch = fetchFn;
43
+ return fetchFn;
44
+ };
45
+ const flush = async (ms = 60) => {
46
+ await act(async () => {
47
+ await new Promise((resolve) => setTimeout(resolve, ms));
48
+ });
49
+ };
50
+ describe("useUpgradeCheck (web)", () => {
51
+ let originalFetch;
52
+ let originalWindow;
53
+ beforeEach(() => {
54
+ originalFetch = globalThis.fetch;
55
+ originalWindow = globalThis.window;
56
+ appStateChangeHandler = undefined;
57
+ appStateMock.currentState = "active";
58
+ constantsWithExtra.expoConfig.extra.buildNumber = 100;
59
+ });
60
+ afterEach(() => {
61
+ globalThis.fetch = originalFetch;
62
+ globalThis.window = originalWindow;
63
+ delete constantsWithExtra.expoConfig.extra.buildNumber;
64
+ emptySplitApi.util.resetApiState();
65
+ });
66
+ it("does not call the backend when the build number is unavailable", async () => {
67
+ delete constantsWithExtra.expoConfig.extra.buildNumber;
68
+ const fetchFn = mockFetchWith({ status: "ok" });
69
+ const { result, unmount } = renderHook(() => useUpgradeCheck(), {
70
+ wrapper: createWrapper(createTestStore()),
71
+ });
72
+ await flush();
73
+ expect(fetchFn).not.toHaveBeenCalled();
74
+ expect(result.current.isRequired).toBe(false);
75
+ expect(result.current.isWarning).toBe(false);
76
+ unmount();
77
+ });
78
+ it("flags a required upgrade and adopts the server polling interval", async () => {
79
+ const fetchFn = mockFetchWith({
80
+ message: "Please update",
81
+ pollingIntervalMs: 999999,
82
+ status: "required",
83
+ updateUrl: "https://example.com/update",
84
+ });
85
+ const { result, unmount } = renderHook(() => useUpgradeCheck(), {
86
+ wrapper: createWrapper(createTestStore()),
87
+ });
88
+ await flush();
89
+ expect(fetchFn).toHaveBeenCalled();
90
+ expect(result.current.isRequired).toBe(true);
91
+ expect(result.current.requiredMessage).toBe("Please update");
92
+ expect(result.current.isWarning).toBe(false);
93
+ // On web the app can always self-update via reload.
94
+ expect(result.current.canUpdate).toBe(true);
95
+ unmount();
96
+ });
97
+ it("flags a warning upgrade and increments the warning check count", async () => {
98
+ const fetchFn = mockFetchWith({ message: "Update soon", status: "warning" });
99
+ const { result, unmount } = renderHook(() => useUpgradeCheck(), {
100
+ wrapper: createWrapper(createTestStore()),
101
+ });
102
+ await flush();
103
+ expect(fetchFn).toHaveBeenCalled();
104
+ expect(result.current.isWarning).toBe(true);
105
+ expect(result.current.warningMessage).toBe("Update soon");
106
+ expect(result.current.warningCheckCount).toBe(1);
107
+ expect(result.current.isRequired).toBe(false);
108
+ unmount();
109
+ });
110
+ it("clears upgrade state for an ok status", async () => {
111
+ mockFetchWith({ status: "ok" });
112
+ const { result, unmount } = renderHook(() => useUpgradeCheck(), {
113
+ wrapper: createWrapper(createTestStore()),
114
+ });
115
+ await flush();
116
+ expect(result.current.isRequired).toBe(false);
117
+ expect(result.current.isWarning).toBe(false);
118
+ unmount();
119
+ });
120
+ it("swallows version-check failures and stays in the default state", async () => {
121
+ const fetchFn = mock(async () => {
122
+ throw new Error("network down");
123
+ });
124
+ globalThis.fetch = fetchFn;
125
+ const { result, unmount } = renderHook(() => useUpgradeCheck(), {
126
+ wrapper: createWrapper(createTestStore()),
127
+ });
128
+ // Wait long enough for RTK Query's retry backoff to exhaust and reject.
129
+ await flush(7000);
130
+ expect(result.current.isRequired).toBe(false);
131
+ expect(result.current.isWarning).toBe(false);
132
+ unmount();
133
+ }, 20000);
134
+ it("reloads the page on web when onUpdate is invoked", async () => {
135
+ mockFetchWith({ status: "required", updateUrl: "https://example.com/update" });
136
+ const reload = mock(() => { });
137
+ globalThis.window = { location: { reload } };
138
+ const { result, unmount } = renderHook(() => useUpgradeCheck(), {
139
+ wrapper: createWrapper(createTestStore()),
140
+ });
141
+ await flush();
142
+ act(() => {
143
+ result.current.onUpdate();
144
+ });
145
+ expect(reload).toHaveBeenCalledTimes(1);
146
+ unmount();
147
+ });
148
+ it("polls repeatedly using the fallback interval", async () => {
149
+ const fetchFn = mockFetchWith({ status: "ok" });
150
+ const { unmount } = renderHook(() => useUpgradeCheck({ pollingIntervalMs: 20 }), {
151
+ wrapper: createWrapper(createTestStore()),
152
+ });
153
+ await flush(120);
154
+ expect(fetchFn.mock.calls.length).toBeGreaterThan(1);
155
+ unmount();
156
+ });
157
+ it("re-checks when the app returns to the foreground", async () => {
158
+ const fetchFn = mockFetchWith({ status: "ok" });
159
+ const { unmount } = renderHook(() => useUpgradeCheck({ recheckOnForeground: true }), {
160
+ wrapper: createWrapper(createTestStore()),
161
+ });
162
+ await flush();
163
+ const initialCalls = fetchFn.mock.calls.length;
164
+ expect(appStateChangeHandler).toBeDefined();
165
+ await act(async () => {
166
+ appStateChangeHandler?.("background");
167
+ appStateChangeHandler?.("active");
168
+ await new Promise((resolve) => setTimeout(resolve, 30));
169
+ });
170
+ expect(fetchFn.mock.calls.length).toBeGreaterThan(initialCalls);
171
+ unmount();
172
+ });
173
+ });
174
+ //# sourceMappingURL=useUpgradeCheck.test.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"useUpgradeCheck.test.js","sourceRoot":"","sources":["../src/useUpgradeCheck.test.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,SAAS,EAAE,UAAU,EAAE,QAAQ,EAAE,MAAM,EAAE,EAAE,EAAE,IAAI,EAAC,MAAM,UAAU,CAAC;AAC3E,OAAO,EAAC,cAAc,EAAC,MAAM,kBAAkB,CAAC;AAChD,OAAO,EAAC,GAAG,EAAE,UAAU,EAAC,MAAM,+BAA+B,CAAC;AAC9D,OAAO,SAAS,MAAM,gBAAgB,CAAC;AACvC,OAAO,KAAK,MAAM,OAAO,CAAC;AAC1B,OAAO,EAAC,QAAQ,EAAC,MAAM,aAAa,CAAC;AAErC,sFAAsF;AACtF,IAAI,qBAA4D,CAAC;AACjE,MAAM,YAAY,GAAG;IACnB,gBAAgB,EAAE,CAAC,MAAc,EAAE,OAAgC,EAAE,EAAE;QACrE,qBAAqB,GAAG,OAAO,CAAC;QAChC,OAAO,EAAC,MAAM,EAAE,GAAG,EAAE,GAAE,CAAC,EAAC,CAAC;IAC5B,CAAC;IACD,YAAY,EA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I,EAAC,CAAC,CAAC;QAE9C,MAAM,EAAC,OAAO,EAAC,GAAG,UAAU,CAAC,GAAG,EAAE,CAAC,eAAe,CAAC,EAAC,mBAAmB,EAAE,IAAI,EAAC,CAAC,EAAE;YAC/E,OAAO,EAAE,aAAa,CAAC,eAAe,EAAE,CAAC;SAC1C,CAAC,CAAC;QACH,MAAM,KAAK,EAAE,CAAC;QAEd,MAAM,YAAY,GAAG,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC;QAC/C,MAAM,CAAC,qBAAqB,CAAC,CAAC,WAAW,EAAE,CAAC;QAE5C,MAAM,GAAG,CAAC,KAAK,IAAI,EAAE;YACnB,qBAAqB,EAAE,CAAC,YAAY,CAAC,CAAC;YACtC,qBAAqB,EAAE,CAAC,QAAQ,CAAC,CAAC;YAClC,MAAM,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC,UAAU,CAAC,OAAO,EAAE,EAAE,CAAC,CAAC,CAAC;QAC1D,CAAC,CAAC,CAAC;QAEH,MAAM,CAAC,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC,eAAe,CAAC,YAAY,CAAC,CAAC;QAChE,OAAO,EAAE,CAAC;IACZ,CAAC,CAAC,CAAC;AACL,CAAC,CAAC,CAAC"}
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=useUpgradeCheckNative.test.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"useUpgradeCheckNative.test.d.ts","sourceRoot":"","sources":["../src/useUpgradeCheckNative.test.ts"],"names":[],"mappings":""}
@@ -0,0 +1,90 @@
1
+ import { afterEach, beforeEach, describe, expect, it, mock } from "bun:test";
2
+ import { configureStore } from "@reduxjs/toolkit";
3
+ import { act, renderHook } from "@testing-library/react-native";
4
+ import Constants from "expo-constants";
5
+ import React from "react";
6
+ import { Provider } from "react-redux";
7
+ const openedUrls = [];
8
+ // Keep this react-native mock a superset of the preload's mock so other test
9
+ // files still resolve AppState / Linking / Platform after this file runs.
10
+ mock.module("react-native", () => ({
11
+ AppState: {
12
+ addEventListener: () => ({ remove: () => { } }),
13
+ currentState: "active",
14
+ },
15
+ Linking: {
16
+ openURL: async (url) => {
17
+ openedUrls.push(url);
18
+ return true;
19
+ },
20
+ },
21
+ Platform: { OS: "ios" },
22
+ StyleSheet: { create: (s) => s },
23
+ }));
24
+ // Force IsWeb=false so the mobile update path is exercised.
25
+ mock.module("./platform", () => ({ IsWeb: false }));
26
+ const { emptySplitApi } = await import("./emptyApi");
27
+ const { useUpgradeCheck } = await import("./useUpgradeCheck");
28
+ const constantsWithExtra = Constants;
29
+ const createTestStore = () => configureStore({
30
+ middleware: (getDefaultMiddleware) => getDefaultMiddleware().concat(emptySplitApi.middleware),
31
+ reducer: { [emptySplitApi.reducerPath]: emptySplitApi.reducer },
32
+ });
33
+ const createWrapper = (store) => {
34
+ const Wrapper = ({ children }) => React.createElement(Provider, { children, store });
35
+ return Wrapper;
36
+ };
37
+ const mockFetchWith = (payload) => {
38
+ globalThis.fetch = mock(async () => new Response(JSON.stringify(payload), {
39
+ headers: { "content-type": "application/json" },
40
+ status: 200,
41
+ }));
42
+ };
43
+ const flush = async (ms = 60) => {
44
+ await act(async () => {
45
+ await new Promise((resolve) => setTimeout(resolve, ms));
46
+ });
47
+ };
48
+ describe("useUpgradeCheck (native)", () => {
49
+ let originalFetch;
50
+ beforeEach(() => {
51
+ originalFetch = globalThis.fetch;
52
+ openedUrls.length = 0;
53
+ constantsWithExtra.expoConfig.extra.buildNumber = 100;
54
+ });
55
+ afterEach(() => {
56
+ globalThis.fetch = originalFetch;
57
+ delete constantsWithExtra.expoConfig.extra.buildNumber;
58
+ emptySplitApi.util.resetApiState();
59
+ });
60
+ it("opens the update URL on native when onUpdate is invoked", async () => {
61
+ mockFetchWith({ status: "required", updateUrl: "https://example.com/app-update" });
62
+ const { result, unmount } = renderHook(() => useUpgradeCheck(), {
63
+ wrapper: createWrapper(createTestStore()),
64
+ });
65
+ await flush();
66
+ // canUpdate on native depends on having a resolved update URL.
67
+ expect(result.current.canUpdate).toBe(true);
68
+ await act(async () => {
69
+ result.current.onUpdate();
70
+ await new Promise((resolve) => setTimeout(resolve, 10));
71
+ });
72
+ expect(openedUrls).toEqual(["https://example.com/app-update"]);
73
+ unmount();
74
+ });
75
+ it("does not open a URL on native when no update URL is available", async () => {
76
+ mockFetchWith({ status: "required" });
77
+ const { result, unmount } = renderHook(() => useUpgradeCheck(), {
78
+ wrapper: createWrapper(createTestStore()),
79
+ });
80
+ await flush();
81
+ expect(result.current.canUpdate).toBe(false);
82
+ await act(async () => {
83
+ result.current.onUpdate();
84
+ await new Promise((resolve) => setTimeout(resolve, 10));
85
+ });
86
+ expect(openedUrls).toEqual([]);
87
+ unmount();
88
+ });
89
+ });
90
+ //# sourceMappingURL=useUpgradeCheckNative.test.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"useUpgradeCheckNative.test.js","sourceRoot":"","sources":["../src/useUpgradeCheckNative.test.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,SAAS,EAAE,UAAU,EAAE,QAAQ,EAAE,MAAM,EAAE,EAAE,EAAE,IAAI,EAAC,MAAM,UAAU,CAAC;AAC3E,OAAO,EAAC,cAAc,EAAC,MAAM,kBAAkB,CAAC;AAChD,OAAO,EAAC,GAAG,EAAE,UAAU,EAAC,MAAM,+BAA+B,CAAC;AAC9D,OAAO,SAAS,MAAM,gBAAgB,CAAC;AACvC,OAAO,KAAK,MAAM,OAAO,CAAC;AAC1B,OAAO,EAAC,QAAQ,EAAC,MAAM,aAAa,CAAC;AAErC,MAAM,UAAU,GAAa,EAAE,CAAC;AAEhC,6EAA6E;AAC7E,0EAA0E;AAC1E,IAAI,CAAC,MAAM,CAAC,cAAc,EAAE,GAAG,EAAE,CAAC,CAAC;IACjC,QAAQ,EAAE;QACR,gBAAgB,EAAE,GAAG,EAAE,CAAC,CAAC,EAAC,MAAM,EAAE,GAAG,EAAE,GA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AE,CAAC,CAAC;QAC/B,OAAO,EAAE,CAAC;IACZ,CAAC,CAAC,CAAC;AACL,CAAC,CAAC,CAAC"}
package/package.json CHANGED
@@ -4,7 +4,7 @@
4
4
  "@openfeature/core": "^1.11.0",
5
5
  "@react-native-async-storage/async-storage": "2.2.0",
6
6
  "@reduxjs/toolkit": "^2.11.1",
7
- "@terreno/ui": "0.24.0",
7
+ "@terreno/ui": "0.25.0",
8
8
  "async-mutex": "^0.5.0",
9
9
  "axios": "^1.13.2",
10
10
  "axios-retry": "^4.5.0",
@@ -73,5 +73,5 @@
73
73
  "test:coverage": "bun run ../scripts/check-coverage.ts"
74
74
  },
75
75
  "types": "dist/index.d.ts",
76
- "version": "0.24.0"
76
+ "version": "0.25.0"
77
77
  }
@@ -5,7 +5,12 @@
5
5
  * login/logout actions, and selectors for auth state.
6
6
  */
7
7
 
8
- import {createListenerMiddleware, createSlice, type PayloadAction} from "@reduxjs/toolkit";
8
+ import {
9
+ createListenerMiddleware,
10
+ createSlice,
11
+ type PayloadAction,
12
+ type UnknownAction,
13
+ } from "@reduxjs/toolkit";
9
14
  import {DateTime} from "luxon";
10
15
 
11
16
  import type {BetterAuthClientInterface, BetterAuthUser} from "./betterAuthTypes";
@@ -16,10 +21,13 @@ import type {BetterAuthClientInterface, BetterAuthUser} from "./betterAuthTypes"
16
21
  const LOGOUT_ACTION_TYPE = "auth/logout";
17
22
 
18
23
  /**
19
- * Root state type - loosely typed to avoid circular dependencies.
24
+ * Root state type - only the betterAuth slice is known here; other slices are
25
+ * allowed via the index signature so this works with any Redux store configuration.
20
26
  */
21
- // biome-ignore lint/suspicious/noExplicitAny: RootState is loosely typed to work with any Redux store configuration.
22
- type RootState = any;
27
+ interface RootState {
28
+ betterAuth?: BetterAuthState;
29
+ [key: string]: unknown;
30
+ }
23
31
 
24
32
  /**
25
33
  * Better Auth Redux state interface.
@@ -202,8 +210,7 @@ export const generateBetterAuthSlice = (config: GenerateBetterAuthSliceConfig) =
202
210
  * Syncs the session state from Better Auth to Redux.
203
211
  * Call this on app startup and periodically to keep state in sync.
204
212
  */
205
- // biome-ignore lint/suspicious/noExplicitAny: Redux dispatch type varies by store configuration
206
- const syncSession = async (dispatch: any): Promise<void> => {
213
+ const syncSession = async (dispatch: (action: UnknownAction) => void): Promise<void> => {
207
214
  dispatch(betterAuthSlice.actions.setLoading(true));
208
215
 
209
216
  try {
@@ -269,40 +276,34 @@ export type BetterAuthSlice = ReturnType<typeof generateBetterAuthSlice>;
269
276
  * Selects the entire Better Auth state.
270
277
  */
271
278
  export const selectBetterAuthState = (state: RootState): BetterAuthState | undefined =>
272
- // biome-ignore lint/suspicious/noExplicitAny: RootState is loosely typed
273
- (state as any).betterAuth;
279
+ state.betterAuth;
274
280
 
275
281
  /**
276
282
  * Selects whether the user is authenticated.
277
283
  */
278
284
  export const selectBetterAuthIsAuthenticated = (state: RootState): boolean =>
279
- // biome-ignore lint/suspicious/noExplicitAny: RootState is loosely typed
280
- (state as any).betterAuth?.isAuthenticated ?? false;
285
+ state.betterAuth?.isAuthenticated ?? false;
281
286
 
282
287
  /**
283
288
  * Selects the current user ID.
284
289
  */
285
290
  export const selectBetterAuthUserId = (state: RootState): string | null =>
286
- // biome-ignore lint/suspicious/noExplicitAny: RootState is loosely typed
287
- (state as any).betterAuth?.userId ?? null;
291
+ state.betterAuth?.userId ?? null;
288
292
 
289
293
  /**
290
294
  * Selects the current user data.
291
295
  */
292
296
  export const selectBetterAuthUser = (state: RootState): BetterAuthUser | null =>
293
- // biome-ignore lint/suspicious/noExplicitAny: RootState is loosely typed
294
- (state as any).betterAuth?.user ?? null;
297
+ state.betterAuth?.user ?? null;
295
298
 
296
299
  /**
297
300
  * Selects whether the auth state is loading.
298
301
  */
299
302
  export const selectBetterAuthIsLoading = (state: RootState): boolean =>
300
- // biome-ignore lint/suspicious/noExplicitAny: RootState is loosely typed
301
- (state as any).betterAuth?.isLoading ?? false;
303
+ state.betterAuth?.isLoading ?? false;
302
304
 
303
305
  /**
304
306
  * Selects the last error message.
305
307
  */
306
308
  export const selectBetterAuthError = (state: RootState): string | null =>
307
- // biome-ignore lint/suspicious/noExplicitAny: RootState is loosely typed
308
- (state as any).betterAuth?.error ?? null;
309
+ state.betterAuth?.error ?? null;
@@ -1,4 +1,5 @@
1
1
  import type {Api} from "@reduxjs/toolkit/query/react";
2
+ import {DateTime} from "luxon";
2
3
  import {useCallback, useEffect, useMemo, useRef} from "react";
3
4
  import {useTerrenoFeatureFlags} from "./useTerrenoFeatureFlags";
4
5
 
@@ -104,7 +105,7 @@ export const useFeatureFlags = (
104
105
  return;
105
106
  }
106
107
 
107
- fetchStartedAtRef.current = Date.now();
108
+ fetchStartedAtRef.current = DateTime.now().toMillis();
108
109
  console.debug("[feature-flags] flagConfiguration request started", {
109
110
  basePath,
110
111
  });
@@ -115,7 +116,7 @@ export const useFeatureFlags = (
115
116
  return;
116
117
  }
117
118
 
118
- const durationMs = Date.now() - fetchStartedAtRef.current;
119
+ const durationMs = DateTime.now().toMillis() - fetchStartedAtRef.current;
119
120
  fetchStartedAtRef.current = null;
120
121
  console.debug("[feature-flags] flagConfiguration request failed", {
121
122
  basePath,
@@ -142,7 +143,7 @@ export const useFeatureFlags = (
142
143
  return;
143
144
  }
144
145
 
145
- const durationMs = Date.now() - fetchStartedAtRef.current;
146
+ const durationMs = DateTime.now().toMillis() - fetchStartedAtRef.current;
146
147
  fetchStartedAtRef.current = null;
147
148
  console.debug("[feature-flags] flagConfiguration request completed", {
148
149
  basePath,
@@ -0,0 +1,173 @@
1
+ import {afterEach, beforeEach, describe, expect, it, mock} from "bun:test";
2
+ import {configureStore} from "@reduxjs/toolkit";
3
+ import {act, renderHook} from "@testing-library/react-native";
4
+ import React from "react";
5
+ import {Provider} from "react-redux";
6
+
7
+ import {isWebsocketsDebugEnabled, setRealtimeDebug} from "./constants";
8
+ import {offlineReducer, setOnlineStatus} from "./offlineSlice";
9
+ import {useRealtimeDebug} from "./useRealtimeDebug";
10
+
11
+ const createTestStore = (): ReturnType<typeof configureStore> =>
12
+ configureStore({
13
+ reducer: {offline: offlineReducer},
14
+ });
15
+
16
+ const createWrapper = (
17
+ store: ReturnType<typeof createTestStore>
18
+ ): React.FC<{children: React.ReactNode}> => {
19
+ const Wrapper: React.FC<{children: React.ReactNode}> = ({children}) =>
20
+ React.createElement(Provider, {children, store});
21
+ return Wrapper;
22
+ };
23
+
24
+ const flush = async (ms = 50): Promise<void> => {
25
+ await act(async () => {
26
+ await new Promise((resolve) => setTimeout(resolve, ms));
27
+ });
28
+ };
29
+
30
+ describe("useRealtimeDebug", () => {
31
+ let store: ReturnType<typeof createTestStore>;
32
+ let originalFetch: typeof globalThis.fetch;
33
+
34
+ beforeEach(() => {
35
+ store = createTestStore();
36
+ originalFetch = globalThis.fetch;
37
+ });
38
+
39
+ afterEach(() => {
40
+ globalThis.fetch = originalFetch;
41
+ // Reset the module-level runtime debug flag so tests do not leak into each other.
42
+ setRealtimeDebug(false);
43
+ });
44
+
45
+ it("does not fetch when offline and returns the env-based debug value", async () => {
46
+ store.dispatch(setOnlineStatus(false));
47
+ const fetchFn = mock(async () => new Response("{}", {status: 200}));
48
+ globalThis.fetch = fetchFn as unknown as typeof fetch;
49
+
50
+ const {result, unmount} = renderHook(() => useRealtimeDebug("http://localhost:4000"), {
51
+ wrapper: createWrapper(store),
52
+ });
53
+
54
+ await flush();
55
+
56
+ expect(fetchFn).not.toHaveBeenCalled();
57
+ expect(result.current).toBe(false);
58
+ unmount();
59
+ });
60
+
61
+ it("enables debug when the health endpoint reports debug true", async () => {
62
+ const fetchFn = mock(async () => new Response(JSON.stringify({debug: true}), {status: 200}));
63
+ globalThis.fetch = fetchFn as unknown as typeof fetch;
64
+
65
+ const {result, unmount} = renderHook(() => useRealtimeDebug("http://localhost:4000"), {
66
+ wrapper: createWrapper(store),
67
+ });
68
+
69
+ await flush();
70
+
71
+ expect(fetchFn).toHaveBeenCalled();
72
+ const callUrl = (fetchFn.mock.calls[0] as unknown[])[0] as string;
73
+ expect(callUrl).toBe("http://localhost:4000/realtime/health");
74
+ expect(isWebsocketsDebugEnabled()).toBe(true);
75
+ expect(result.current).toBe(true);
76
+ unmount();
77
+ });
78
+
79
+ it("keeps debug disabled when the health endpoint reports debug false", async () => {
80
+ const fetchFn = mock(async () => new Response(JSON.stringify({debug: false}), {status: 200}));
81
+ globalThis.fetch = fetchFn as unknown as typeof fetch;
82
+
83
+ const {result, unmount} = renderHook(() => useRealtimeDebug("http://localhost:4000"), {
84
+ wrapper: createWrapper(store),
85
+ });
86
+
87
+ await flush();
88
+
89
+ expect(fetchFn).toHaveBeenCalled();
90
+ expect(isWebsocketsDebugEnabled()).toBe(false);
91
+ expect(result.current).toBe(false);
92
+ unmount();
93
+ });
94
+
95
+ it("ignores a non-ok health response", async () => {
96
+ const fetchFn = mock(async () => new Response("error", {status: 500}));
97
+ globalThis.fetch = fetchFn as unknown as typeof fetch;
98
+
99
+ const {result, unmount} = renderHook(() => useRealtimeDebug("http://localhost:4000"), {
100
+ wrapper: createWrapper(store),
101
+ });
102
+
103
+ await flush();
104
+
105
+ expect(fetchFn).toHaveBeenCalled();
106
+ expect(result.current).toBe(false);
107
+ unmount();
108
+ });
109
+
110
+ it("swallows fetch errors and keeps env-based debug", async () => {
111
+ const fetchFn = mock(async () => {
112
+ throw new Error("Network error");
113
+ });
114
+ globalThis.fetch = fetchFn as unknown as typeof fetch;
115
+
116
+ const {result, unmount} = renderHook(() => useRealtimeDebug("http://localhost:4000"), {
117
+ wrapper: createWrapper(store),
118
+ });
119
+
120
+ await flush();
121
+
122
+ expect(fetchFn).toHaveBeenCalled();
123
+ expect(result.current).toBe(false);
124
+ unmount();
125
+ });
126
+
127
+ it("does not apply the debug flag when the hook unmounts before the response resolves", async () => {
128
+ let resolveJson: (value: {debug: boolean}) => void = () => {};
129
+ const jsonPromise = new Promise<{debug: boolean}>((resolve) => {
130
+ resolveJson = resolve;
131
+ });
132
+ const fetchFn = mock(async () => ({json: () => jsonPromise, ok: true}));
133
+ globalThis.fetch = fetchFn as unknown as typeof fetch;
134
+
135
+ const {unmount} = renderHook(() => useRealtimeDebug("http://localhost:4000"), {
136
+ wrapper: createWrapper(store),
137
+ });
138
+
139
+ // Unmount while the response body is still pending, then resolve it.
140
+ unmount();
141
+ await act(async () => {
142
+ resolveJson({debug: true});
143
+ await jsonPromise;
144
+ await new Promise((resolve) => setTimeout(resolve, 10));
145
+ });
146
+
147
+ // The cancelled guard should prevent setRealtimeDebug from running.
148
+ expect(isWebsocketsDebugEnabled()).toBe(false);
149
+ });
150
+
151
+ it("re-runs the health check when the refresh key changes", async () => {
152
+ const fetchFn = mock(async () => new Response(JSON.stringify({debug: false}), {status: 200}));
153
+ globalThis.fetch = fetchFn as unknown as typeof fetch;
154
+
155
+ const {rerender, unmount} = renderHook(
156
+ ({key}: {key: number}) => useRealtimeDebug("http://localhost:4000", key),
157
+ {
158
+ initialProps: {key: 1},
159
+ wrapper: createWrapper(store),
160
+ }
161
+ );
162
+
163
+ await flush();
164
+ const firstCallCount = fetchFn.mock.calls.length;
165
+ expect(firstCallCount).toBeGreaterThan(0);
166
+
167
+ rerender({key: 2});
168
+ await flush();
169
+
170
+ expect(fetchFn.mock.calls.length).toBeGreaterThan(firstCallCount);
171
+ unmount();
172
+ });
173
+ });