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

app-updates.ts

245 lines7.5 KB

1import * as Updates from "expo-updates";
2​
3import {
4 type AtomCommandResult,
5 isAtomCommandInterrupted,
6 reportAtomCommandResult,
7 settlePromise,
8 squashAtomCommandFailure,
9} from "@t3tools/client-runtime/state/runtime";
10​
11export type AppUpdateCheckState = "idle" | "checking" | "downloading" | "restarting" | "current";
12​
13export interface AppUpdateClient {
14 readonly isEnabled: boolean;
15 readonly checkForUpdateAsync: () => Promise<{
16 readonly isAvailable: boolean;
17 readonly isRollBackToEmbedded: boolean;
18 }>;
19 readonly fetchUpdateAsync: () => Promise<{
20 readonly isNew: boolean;
21 readonly isRollBackToEmbedded: boolean;
22 }>;
23 readonly reloadAsync: () => Promise<void>;
25​
26interface AppUpdateCheckOptions {
27 readonly client?: AppUpdateClient;
28 readonly onFailure?: (message: string) => void;
29 readonly onStateChange?: (state: AppUpdateCheckState) => void;
31​
32interface AppUpdateCheckProgress {
33 failure: string | undefined;
34 state: AppUpdateCheckState | undefined;
36​
37interface AppUpdateCheckInFlight {
38 readonly failureListeners: Set<NonNullable<AppUpdateCheckOptions["onFailure"]>>;
39 readonly progress: AppUpdateCheckProgress;
40 readonly promise: Promise<void>;
41 readonly stateListeners: Set<NonNullable<AppUpdateCheckOptions["onStateChange"]>>;
43​
44interface Deferred {
45 readonly promise: Promise<void>;
46 readonly reject: (cause: unknown) => void;
47 readonly resolve: () => void;
49​
50const HIDDEN_UPDATE_TAP_COUNT = 5;
51const UPDATE_CHECK_UNAVAILABLE_ERROR_CODES = new Set([
52 "ERR_NOT_AVAILABLE_IN_DEV_CLIENT",
53 "ERR_UPDATES_DISABLED",
54]);
55let appUpdateCheckInFlight: AppUpdateCheckInFlight | undefined;
56​
57/** Expo's development launcher reports updates as enabled even though its OTA APIs reject. */
58export function isAppUpdateCheckAvailable(client: Pick<AppUpdateClient, "isEnabled"> = Updates) {
59 return client.isEnabled && !(typeof __DEV__ !== "undefined" && __DEV__);
61​
62/**
63 * Keeps the manual update affordance discoverable only to someone deliberately
64 * tapping the version row five times.
65 */
66export function registerHiddenUpdateTap(count: number): {
67 readonly nextCount: number;
68 readonly shouldCheck: boolean;
69} {
70 const nextCount = count + 1;
71 if (nextCount >= HIDDEN_UPDATE_TAP_COUNT) {
72 return {
73 nextCount: 0,
74 shouldCheck: true,
75 };
76 }
77 return {
78 nextCount,
79 shouldCheck: false,
80 };
82​
83export async function runAppUpdateCheck(options: AppUpdateCheckOptions = {}): Promise<void> {
84 const client = options.client ?? Updates;
85 if (!isAppUpdateCheckAvailable(client)) return;
86​
87 if (appUpdateCheckInFlight) {
88 await observeAppUpdateCheck(appUpdateCheckInFlight, options);
89 return;
90 }
91​
92 const progress: AppUpdateCheckProgress = {
93 failure: undefined,
94 state: undefined,
95 };
96 const failureListeners = new Set<NonNullable<AppUpdateCheckOptions["onFailure"]>>();
97 const stateListeners = new Set<NonNullable<AppUpdateCheckOptions["onStateChange"]>>();
98 if (options.onFailure) failureListeners.add(options.onFailure);
99 if (options.onStateChange) stateListeners.add(options.onStateChange);
100​
101 const deferred = createDeferred();
102 const inFlight: AppUpdateCheckInFlight = {
103 failureListeners,
104 progress,
105 promise: deferred.promise,
106 stateListeners,
107 };
108 // Publish the operation before any state listener can synchronously re-enter.
109 appUpdateCheckInFlight = inFlight;
110​
111 const execution = performAppUpdateCheck(client, {
112 onFailure: (message) => {
113 progress.failure = message;
114 notifyListeners(failureListeners, message);
115 },
116 onStateChange: (state) => {
117 progress.state = state;
118 notifyListeners(stateListeners, state);
119 },
120 });
121 void execution.then(deferred.resolve, deferred.reject);
122​
123 try {
124 await deferred.promise;
125 } finally {
126 if (appUpdateCheckInFlight === inFlight) {
127 appUpdateCheckInFlight = undefined;
128 }
129 }
131​
132function createDeferred(): Deferred {
133 let reject!: Deferred["reject"];
134 let resolve!: Deferred["resolve"];
135 const promise = new Promise<void>((resolvePromise, rejectPromise) => {
136 resolve = () => resolvePromise();
137 reject = rejectPromise;
138 });
139 return { promise, reject, resolve };
141​
142function notifyListeners<A>(listeners: ReadonlySet<(value: A) => void>, value: A): void {
143 // A listener can synchronously subscribe another caller. Snapshot so that
144 // caller receives only observeAppUpdateCheck's explicit current-value replay.
145 const snapshot = Array.from(listeners);
146 for (const listener of snapshot) listener(value);
148​
149async function observeAppUpdateCheck(
150 inFlight: AppUpdateCheckInFlight,
151 options: AppUpdateCheckOptions,
152): Promise<void> {
153 const onFailure = options.onFailure;
154 const onStateChange = options.onStateChange;
155​
156 if (onFailure) {
157 inFlight.failureListeners.add(onFailure);
158 if (inFlight.progress.failure) onFailure(inFlight.progress.failure);
159 }
160 if (onStateChange) {
161 inFlight.stateListeners.add(onStateChange);
162 if (inFlight.progress.state) onStateChange(inFlight.progress.state);
163 }
164​
165 try {
166 await inFlight.promise;
167 } finally {
168 if (onFailure) inFlight.failureListeners.delete(onFailure);
169 if (onStateChange) inFlight.stateListeners.delete(onStateChange);
170 }
172​
173async function performAppUpdateCheck(
174 client: AppUpdateClient,
175 options: AppUpdateCheckOptions,
176): Promise<void> {
177 const setState = options.onStateChange ?? (() => {});
178​
179 setState("checking");
180 const check = await settlePromise(() => client.checkForUpdateAsync());
181 if (check._tag === "Failure") {
182 reportUpdateFailure(check, "Could not check for updates.", options.onFailure);
183 setState("idle");
184 return;
185 }
186 // A rollback directive (`eas update:rollback`) arrives as isAvailable: false
187 // with isRollBackToEmbedded: true. The running OTA still has to be dropped.
188 if (!check.value.isAvailable && !check.value.isRollBackToEmbedded) {
189 setState("current");
190 return;
191 }
192​
193 setState("downloading");
194 const fetched = await settlePromise(() => client.fetchUpdateAsync());
195 if (fetched._tag === "Failure") {
196 reportUpdateFailure(fetched, "Could not download the update.", options.onFailure);
197 setState("idle");
198 return;
199 }
200 // isNew is always false for a rollback, so it cannot be the sole gate.
201 if (!fetched.value.isNew && !fetched.value.isRollBackToEmbedded) {
202 setState("current");
203 return;
204 }
205​
206 setState("restarting");
207 const reloaded = await settlePromise(() => client.reloadAsync());
208 if (reloaded._tag === "Failure") {
209 reportUpdateFailure(reloaded, "Downloaded, but could not restart the app.", options.onFailure);
210 setState("idle");
211 }
213​
214function reportUpdateFailure(
215 result: AtomCommandResult<unknown, unknown>,
216 fallback: string,
217 onFailure: AppUpdateCheckOptions["onFailure"],
218): void {
219 if (result._tag !== "Failure" || isAtomCommandInterrupted(result)) return;
220 const error = squashAtomCommandFailure(result);
221 if (isAppUpdateUnavailableError(error)) return;
222​
223 reportAtomCommandResult(result, { label: "app update check" });
224 onFailure?.(error instanceof Error ? error.message : fallback);
226​
227function isAppUpdateUnavailableError(error: unknown): boolean {
228 if (typeof error !== "object" || error === null || !("code" in error)) return false;
229 const code = error.code;
230 return typeof code === "string" && UPDATE_CHECK_UNAVAILABLE_ERROR_CODES.has(code);
232​
233export function createAppUpdateLaunchCheck(
234 client: AppUpdateClient = Updates,
235): () => Promise<void> | undefined {
236 let started = false;
237​
238 return () => {
239 if (started || !isAppUpdateCheckAvailable(client)) return undefined;
240 started = true;
241 return runAppUpdateCheck({ client });
242 };
244​
245export const checkForAppUpdateOnLaunch = createAppUpdateLaunchCheck();