Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

storage.test.ts

217 lines7.4 KB

1import { EnvironmentId } from "@t3tools/contracts";
2import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
3​
4const mocks = vi.hoisted(() => {
5 const values = new Map<string, string>();
6 let preferencesJson: string | null = null;
7 let preferencesUpdatedAt = 0;
8 let loadPreferencesFails = false;
9 let savePreferencesFails = false;
10 return {
11 clear: () => {
12 values.clear();
13 preferencesJson = null;
14 preferencesUpdatedAt = 0;
15 loadPreferencesFails = false;
16 savePreferencesFails = false;
17 },
18 getStoredValue: (key: string) => values.get(key) ?? null,
19 getPreferencesJson: () => preferencesJson,
20 setPreferencesJson: (value: string, updatedAt: number) => {
21 preferencesJson = value;
22 preferencesUpdatedAt = updatedAt;
23 },
24 setDatabaseFailures: (load: boolean, save: boolean) => {
25 loadPreferencesFails = load;
26 savePreferencesFails = save;
27 },
28 getItemAsync: vi.fn((key: string) => Promise.resolve(values.get(key) ?? null)),
29 setItemAsync: vi.fn((key: string, value: string) => {
30 values.set(key, value);
31 return Promise.resolve();
32 }),
33 deleteItemAsync: vi.fn((key: string) => {
34 values.delete(key);
35 return Promise.resolve();
36 }),
37 database: {
38 closeAsync: vi.fn(() => Promise.resolve()),
39 execAsync: vi.fn(() => Promise.resolve()),
40 withExclusiveTransactionAsync: vi.fn(
41 (run: (transaction: { execAsync: () => Promise<void> }) => Promise<void>) =>
42 run({ execAsync: () => Promise.resolve() }),
43 ),
44 getFirstAsync: vi.fn((sql: string) => {
45 if (sql.includes("PRAGMA user_version")) {
46 return Promise.resolve({ user_version: 1 });
47 }
48 if (loadPreferencesFails) {
49 return Promise.reject(new Error("database unavailable"));
50 }
51 return Promise.resolve(
52 preferencesJson === null
53 ? null
54 : { payload: preferencesJson, updatedAt: preferencesUpdatedAt },
55 );
56 }),
57 runAsync: vi.fn((_sql: string, payload?: unknown, updatedAt?: unknown) => {
58 if (savePreferencesFails) {
59 return Promise.reject(new Error("database unavailable"));
60 }
61 if (typeof payload === "string") {
62 preferencesJson = payload;
63 }
64 if (typeof updatedAt === "number") {
65 preferencesUpdatedAt = updatedAt;
66 }
67 return Promise.resolve();
68 }),
69 },
70 };
71});
72​
73vi.mock("expo", () => ({
74 requireOptionalNativeModule: () => null,
75}));
76​
77vi.mock("expo-secure-store", () => ({
78 deleteItemAsync: mocks.deleteItemAsync,
79 getItemAsync: mocks.getItemAsync,
80 setItemAsync: mocks.setItemAsync,
81}));
82​
83vi.mock("expo-sqlite", () => ({
84 openDatabaseAsync: vi.fn(() => Promise.resolve(mocks.database)),
85}));
86​
87vi.mock("expo-crypto", () => ({
88 getRandomBytes: vi.fn(() => new Uint8Array(16)),
89}));
90​
91vi.mock("expo-constants", () => ({
92 default: { expoConfig: { extra: {} } },
93}));
94​
95vi.mock("react-native", () => ({
96 AppState: { currentState: "active" },
97 Platform: {
98 OS: "ios",
99 },
100}));
101​
102import { loadPreferences, saveConnection, savePreferencesPatch } from "../persistence/imperative";
103import { toStableSavedRemoteConnection } from "./connection";
104​
105const managedConnection = {
106 environmentId: EnvironmentId.make("environment-1"),
107 environmentLabel: "Desktop",
108 pairingUrl: "https://desktop.example/",
109 displayUrl: "https://desktop.example/",
110 httpBaseUrl: "https://desktop.example/",
111 wsBaseUrl: "wss://desktop.example/",
112 bearerToken: null,
113 authenticationMethod: "dpop",
114 dpopAccessToken: "short-lived-token",
115 relayManaged: true,
116} as const;
117​
118describe("mobile connection storage", () => {
119 beforeEach(() => {
120 mocks.clear();
121 vi.clearAllMocks();
122 });
123​
124 it("persists relay-managed connections without their ephemeral access token", async () => {
125 await saveConnection(managedConnection);
126​
127 const savedValue = mocks.setItemAsync.mock.calls[0]?.[1];
128 expect(savedValue).toBeDefined();
129 expect(JSON.parse(savedValue ?? "")).toEqual({
130 connections: [toStableSavedRemoteConnection(managedConnection)],
131 });
132 });
133​
134 it("persists tab order locally and retains it when another preference changes", async () => {
135 const navigationTabOrder = ["usage", "threads", "pullRequests"];
136 const hiddenNavigationTabs = ["issues", "home"];
137 await savePreferencesPatch({ navigationTabOrder, hiddenNavigationTabs });
138 await savePreferencesPatch({ baseFontSize: 19 });
139 await expect(loadPreferences()).resolves.toEqual({
140 navigationTabOrder,
141 hiddenNavigationTabs,
142 baseFontSize: 19,
143 });
144 });
145​
146 it("ignores invalid tab-order entries without dropping other saved preferences", async () => {
147 mocks.setPreferencesJson(
148 JSON.stringify({
149 navigationTabOrder: ["usage", null, 4, "threads"],
150 hiddenNavigationTabs: ["home", null],
151 baseFontSize: 18,
152 }),
153 1,
154 );
155 await expect(loadPreferences()).resolves.toEqual({
156 navigationTabOrder: ["usage", "threads"],
157 hiddenNavigationTabs: ["home"],
158 baseFontSize: 18,
159 });
160 });
161​
162 it("loads legacy preferences when SQLite is unavailable", async () => {
163 mocks.setDatabaseFailures(true, true);
164 await mocks.setItemAsync("t3code.preferences", JSON.stringify({ baseFontSize: 17 }));
165​
166 await expect(loadPreferences()).resolves.toEqual({ baseFontSize: 17 });
167 });
168​
169 it("falls back to secure storage when SQLite cannot save preferences", async () => {
170 mocks.setDatabaseFailures(true, true);
171 await expect(savePreferencesPatch({ baseFontSize: 19 })).resolves.toEqual({ baseFontSize: 19 });
172 const fallback = JSON.parse(mocks.getStoredValue("t3code.preferences.fallback") ?? "") as {
173 readonly payload: string;
174 readonly updatedAt: number;
175 };
176 expect(JSON.parse(fallback.payload)).toEqual({ baseFontSize: 19 });
177 expect(fallback.updatedAt).toEqual(expect.any(Number));
178 });
179​
180 it("reconciles fallback preferences after SQLite recovers", async () => {
181 mocks.setPreferencesJson(JSON.stringify({ baseFontSize: 15 }), 10);
182 await mocks.setItemAsync(
183 "t3code.preferences.fallback",
184 JSON.stringify({
185 payload: JSON.stringify({ baseFontSize: 19 }),
186 updatedAt: 20,
187 }),
188 );
189​
190 await expect(loadPreferences()).resolves.toEqual({ baseFontSize: 19 });
191 expect(JSON.parse(mocks.getPreferencesJson() ?? "")).toEqual({ baseFontSize: 19 });
192 expect(mocks.getStoredValue("t3code.preferences.fallback")).toBeNull();
193 });
194​
195 it("ignores a stale fallback when its previous deletion failed", async () => {
196 mocks.setPreferencesJson(JSON.stringify({ baseFontSize: 21 }), 30);
197 await mocks.setItemAsync(
198 "t3code.preferences.fallback",
199 JSON.stringify({
200 payload: JSON.stringify({ baseFontSize: 19 }),
201 updatedAt: 20,
202 }),
203 );
204​
205 await expect(loadPreferences()).resolves.toEqual({ baseFontSize: 21 });
206 expect(JSON.parse(mocks.getPreferencesJson() ?? "")).toEqual({ baseFontSize: 21 });
207 expect(mocks.getStoredValue("t3code.preferences.fallback")).toBeNull();
208 });
209​
210 it("keeps SQLite authoritative when stale legacy preferences remain", async () => {
211 mocks.setPreferencesJson(JSON.stringify({ baseFontSize: 21 }), 30);
212 await mocks.setItemAsync("t3code.preferences", JSON.stringify({ baseFontSize: 19 }));
213​
214 await expect(loadPreferences()).resolves.toEqual({ baseFontSize: 21 });
215 expect(JSON.parse(mocks.getPreferencesJson() ?? "")).toEqual({ baseFontSize: 21 });
216 });
217});