Open History to see the last commit
1import * as Arr from "effect/Array";
2import { pipe } from "effect/Function";
3import * as Schema from "effect/Schema";
4import * as SecureStore from "expo-secure-store";
5import { EnvironmentId } from "@t3tools/contracts";
6
7import {
8 isRelayManagedConnection,
9 type SavedRemoteConnection,
10 toStableSavedRemoteConnection,
11} from "./connection";
12
13const CONNECTIONS_KEY = "t3code.connections";
14const PREFERENCES_KEY = "t3code.preferences";
15const AGENT_AWARENESS_DEVICE_ID_KEY = "t3code.agent-awareness.device-id";
16const MobileStorageKey = Schema.Literals([
17 CONNECTIONS_KEY,
18 PREFERENCES_KEY,
19 AGENT_AWARENESS_DEVICE_ID_KEY,
20]);
21type MobileStorageKeyValue = typeof MobileStorageKey.Type;
22
23export class MobileSecureStorageError extends Schema.TaggedErrorClass<MobileSecureStorageError>()(
24 "MobileSecureStorageError",
25 {
26 operation: Schema.Literals(["read", "write", "generate-device-id"]),
27 key: MobileStorageKey,
28 cause: Schema.Defect(),
29 },
30) {
31 override get message(): string {
32 return `Mobile secure storage operation ${this.operation} failed for key ${this.key}.`;
33 }
34}
35
36export class MobileStorageDecodeError extends Schema.TaggedErrorClass<MobileStorageDecodeError>()(
37 "MobileStorageDecodeError",
38 {
39 key: MobileStorageKey,
40 cause: Schema.Defect(),
41 },
42) {
43 override get message(): string {
44 return `Failed to decode mobile storage value for key ${this.key}.`;
45 }
46}
47
48export class MobileStorageEncodeError extends Schema.TaggedErrorClass<MobileStorageEncodeError>()(
49 "MobileStorageEncodeError",
50 {
51 key: MobileStorageKey,
52 cause: Schema.Defect(),
53 },
54) {
55 override get message(): string {
56 return `Failed to encode mobile storage value for key ${this.key}.`;
57 }
58}
59
60export interface Preferences {
61 readonly liveActivitiesEnabled?: boolean;
62 readonly terminalFontSize?: number;
63}
64
65async function readStorageItem(key: MobileStorageKeyValue): Promise<string | null> {
66 try {
67 return await SecureStore.getItemAsync(key);
68 } catch (cause) {
69 throw new MobileSecureStorageError({ operation: "read", key, cause });
70 }
71}
72
73async function writeStorageItem(key: MobileStorageKeyValue, value: string): Promise<void> {
74 try {
75 await SecureStore.setItemAsync(key, value);
76 } catch (cause) {
77 throw new MobileSecureStorageError({ operation: "write", key, cause });
78 }
79}
80
81async function readJsonStorageItem<T>(key: MobileStorageKeyValue): Promise<T | null> {
82 const raw = (await readStorageItem(key)) ?? "";
83 if (!raw.trim()) {
84 return null;
85 }
86
87 try {
88 return JSON.parse(raw) as T;
89 } catch (cause) {
90 console.warn(
91 "[mobile-storage] ignored invalid JSON",
92 new MobileStorageDecodeError({ key, cause }),
93 );
94 return null;
95 }
96}
97
98async function writeJsonStorageItem(key: MobileStorageKeyValue, value: unknown) {
99 let encoded: string;
100 try {
101 encoded = JSON.stringify(value);
102 } catch (cause) {
103 throw new MobileStorageEncodeError({ key, cause });
104 }
105 await writeStorageItem(key, encoded);
106}
107
108export async function loadSavedConnections(): Promise<ReadonlyArray<SavedRemoteConnection>> {
109 const parsed = await readJsonStorageItem<{
110 readonly connections?: ReadonlyArray<SavedRemoteConnection>;
111 }>(CONNECTIONS_KEY);
112 if (!parsed) {
113 return [];
114 }
115
116 return pipe(
117 parsed.connections ?? [],
118 Arr.filter(
119 (c) => !!c.environmentId && (!!c.bearerToken?.trim() || isRelayManagedConnection(c)),
120 ),
121 );
122}
123
124export async function saveConnection(connection: SavedRemoteConnection): Promise<void> {
125 const current = await loadSavedConnections();
126 const stableConnection = toStableSavedRemoteConnection(connection);
127 const next = current.some((entry) => entry.environmentId === connection.environmentId)
128 ? pipe(
129 current,
130 Arr.map((entry) =>
131 entry.environmentId === connection.environmentId ? stableConnection : entry,
132 ),
133 )
134 : pipe(current, Arr.append(stableConnection));
135
136 await writeJsonStorageItem(CONNECTIONS_KEY, { connections: next });
137}
138
139export async function clearSavedConnection(environmentId: EnvironmentId): Promise<void> {
140 const current = await loadSavedConnections();
141 const next = pipe(
142 current,
143 Arr.filter((entry) => entry.environmentId !== environmentId),
144 );
145 await writeJsonStorageItem(CONNECTIONS_KEY, { connections: next });
146}
147
148export async function loadPreferences(): Promise<Preferences> {
149 const parsed = await readJsonStorageItem<Preferences>(PREFERENCES_KEY);
150 if (!parsed || typeof parsed !== "object") {
151 return {};
152 }
153
154 const preferences: {
155 liveActivitiesEnabled?: boolean;
156 terminalFontSize?: number;
157 } = {};
158
159 if (typeof parsed.liveActivitiesEnabled === "boolean") {
160 preferences.liveActivitiesEnabled = parsed.liveActivitiesEnabled;
161 }
162 if (typeof parsed.terminalFontSize === "number") {
163 preferences.terminalFontSize = parsed.terminalFontSize;
164 }
165
166 return preferences;
167}
168
169export async function savePreferencesPatch(patch: Partial<Preferences>): Promise<Preferences> {
170 const current = await loadPreferences();
171 const next: Preferences = {
172 ...current,
173 ...patch,
174 };
175 await writeJsonStorageItem(PREFERENCES_KEY, next);
176 return next;
177}
178
179export async function loadOrCreateAgentAwarenessDeviceId(): Promise<string> {
180 const existing = await readStorageItem(AGENT_AWARENESS_DEVICE_ID_KEY);
181 if (existing?.trim()) {
182 return existing;
183 }
184
185 const deviceId = await import("./uuid")
186 .then(({ uuidv4 }) => uuidv4())
187 .catch((cause) => {
188 throw new MobileSecureStorageError({
189 operation: "generate-device-id",
190 key: AGENT_AWARENESS_DEVICE_ID_KEY,
191 cause,
192 });
193 });
194 await writeStorageItem(AGENT_AWARENESS_DEVICE_ID_KEY, deviceId);
195 return deviceId;
196}
197
198export async function loadAgentAwarenessDeviceId(): Promise<string | null> {
199 const existing = await readStorageItem(AGENT_AWARENESS_DEVICE_ID_KEY);
200 return existing?.trim() ? existing : null;
201}