create-expo-updates-server 0.2.0 → 0.3.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 (45) hide show
  1. package/dist/template/Dockerfile +5 -0
  2. package/dist/template/docker/minio.Dockerfile +11 -0
  3. package/dist/template/docker-compose.yml +7 -9
  4. package/dist/template/docs/expo-app-setup.md +8 -12
  5. package/dist/template/docs/getting-started.md +9 -5
  6. package/dist/template/docs/getting-started.ru.md +9 -7
  7. package/dist/template/docs/ota-client-lifecycle.md +46 -42
  8. package/dist/template/package-lock.json +589 -0
  9. package/dist/template/package.json +1 -0
  10. package/dist/template/scripts/ensure-storage-bucket.mjs +25 -0
  11. package/dist/template/scripts/lib/device-identity.test.ts +2 -2
  12. package/dist/template/scripts/lib/doctor.mjs +3 -3
  13. package/dist/template/scripts/lib/doctor.test.mjs +1 -1
  14. package/dist/template/scripts/lib/ota-client-configurator.mjs +116 -34
  15. package/dist/template/scripts/lib/ota-client-configurator.test.ts +210 -61
  16. package/dist/template/scripts/lib/ota-client.test.ts +1 -1
  17. package/dist/template/scripts/lib/ota-root-hook-patcher.mjs +435 -118
  18. package/dist/template/scripts/lib/ota-root-hook-patcher.test.ts +243 -86
  19. package/dist/template/scripts/lib/ota-update-controller.test.ts +10 -9
  20. package/dist/template/scripts/lib/ota-updates-ui.test.tsx +154 -0
  21. package/dist/template/scripts/tests/fixtures/react-native-ui.tsx +34 -0
  22. package/dist/template/scripts/tests/ota-client-types.mjs +69 -0
  23. package/dist/template/templates/expo-app/ota-client/README.md +16 -2
  24. package/dist/template/templates/expo-app/ota-client/controller.ts +107 -0
  25. package/dist/template/templates/expo-app/ota-client/device-identity.ts +48 -0
  26. package/dist/template/templates/expo-app/ota-client/docs/update-lifecycle.md +18 -9
  27. package/dist/template/templates/expo-app/ota-client/index.ts +16 -0
  28. package/dist/template/templates/expo-app/ota-client/model/hooks/useOtaUpdates.ts +97 -0
  29. package/dist/template/templates/expo-app/ota-client/model/update-controller.ts +293 -0
  30. package/dist/template/templates/expo-app/ota-client/runtime.ts +153 -0
  31. package/dist/template/templates/expo-app/ota-client/types.ts +85 -0
  32. package/dist/template/templates/expo-app/ota-client/ui/ota-update-gate.tsx +25 -0
  33. package/dist/template/templates/expo-app/ota-client/ui/ota-updates.tsx +196 -0
  34. package/dist/template/tsconfig.json +3 -1
  35. package/dist/template/vitest.config.mts +3 -0
  36. package/dist/template-manifest.json +99 -69
  37. package/package.json +1 -1
  38. package/dist/template/templates/expo-app/ota-client/controller.js +0 -60
  39. package/dist/template/templates/expo-app/ota-client/device-identity.js +0 -26
  40. package/dist/template/templates/expo-app/ota-client/index.d.ts +0 -47
  41. package/dist/template/templates/expo-app/ota-client/index.js +0 -3
  42. package/dist/template/templates/expo-app/ota-client/model/hooks/useOtaUpdates.js +0 -48
  43. package/dist/template/templates/expo-app/ota-client/model/update-controller.js +0 -182
  44. package/dist/template/templates/expo-app/ota-client/runtime.js +0 -112
  45. package/dist/template/templates/expo-app/ota-client/ui/ota-update-gate.js +0 -56
@@ -0,0 +1,293 @@
1
+ import { manifestDetails } from "../types";
2
+ import type {
3
+ OtaCandidate,
4
+ OtaCheckResult,
5
+ OtaFetchResult,
6
+ OtaOptions,
7
+ OtaState,
8
+ } from "../types";
9
+
10
+ interface Dependencies {
11
+ enabled: boolean;
12
+ start(): void;
13
+ identity(): Promise<{
14
+ installationId: string | null;
15
+ deviceId: string | null;
16
+ }>;
17
+ check(): Promise<OtaCheckResult>;
18
+ fetch(): Promise<OtaFetchResult>;
19
+ reload(): Promise<void>;
20
+ isActive(): boolean;
21
+ openStore(payload: unknown): Promise<void>;
22
+ runningCandidate?(): OtaCandidate | null;
23
+ now?(): number;
24
+ }
25
+
26
+ // Pure lifecycle model. Native APIs, storage and React live in adapters.
27
+ export function createUpdateController(deps: Dependencies) {
28
+ let state: Readonly<OtaState> = Object.freeze({
29
+ enabled: deps.enabled,
30
+ status: "idle",
31
+ installationId: null,
32
+ deviceId: null,
33
+ available: false,
34
+ pending: false,
35
+ candidate: null,
36
+ policy: null,
37
+ blocked: false,
38
+ blockReason: null,
39
+ error: null,
40
+ });
41
+ const listeners = new Set<() => void>();
42
+ const owners = new Map<symbol, OtaOptions>();
43
+ let flight: Promise<unknown> | undefined;
44
+ let flightKind: OtaState["status"] | undefined;
45
+ let lastAutomaticCheck = -Infinity;
46
+ let identityReady: Promise<void> | undefined;
47
+ let pendingKey: string | undefined;
48
+ let pendingGeneration = 0;
49
+ const now = deps.now || Date.now;
50
+ function patch(value: Partial<OtaState>) {
51
+ state = Object.freeze({ ...state, ...value });
52
+ for (const listener of listeners) listener();
53
+ }
54
+ function options() {
55
+ const result: Required<OtaOptions> = {
56
+ autoCheck: false,
57
+ autoUpdate: false,
58
+ autoReload: false,
59
+ guardHandlers: {},
60
+ };
61
+ for (const owner of owners.values()) {
62
+ for (const key of ["autoCheck", "autoUpdate", "autoReload"] as const)
63
+ result[key] ||= owner[key] === true;
64
+ Object.assign(result.guardHandlers, owner.guardHandlers);
65
+ }
66
+ return result;
67
+ }
68
+ function initialize() {
69
+ deps.start();
70
+ if (!deps.enabled) return Promise.resolve();
71
+ if (!identityReady)
72
+ identityReady = deps
73
+ .identity()
74
+ .then(async (identity) => {
75
+ patch(identity);
76
+ await inspectRunning();
77
+ })
78
+ .catch((error) => {
79
+ identityReady = undefined;
80
+ patch({ error });
81
+ throw error;
82
+ });
83
+ return identityReady;
84
+ }
85
+ function run<T>(
86
+ kind: OtaState["status"],
87
+ task: () => Promise<T>,
88
+ ): Promise<T> {
89
+ if (!deps.enabled)
90
+ return Promise.reject(
91
+ new Error("OTA updates are unavailable in this build"),
92
+ );
93
+ if (flight) {
94
+ if (flightKind === kind) return flight as Promise<T>;
95
+ return Promise.reject(new Error("Another OTA operation is in progress"));
96
+ }
97
+ flightKind = kind;
98
+ patch({ status: kind, error: null });
99
+ const operation = Promise.resolve()
100
+ .then(initialize)
101
+ .then(task)
102
+ .catch((error) => {
103
+ patch({ error });
104
+ throw error;
105
+ })
106
+ .finally(() => {
107
+ flight = undefined;
108
+ flightKind = undefined;
109
+ patch({ status: "idle" });
110
+ });
111
+ flight = operation;
112
+ return operation;
113
+ }
114
+ async function inspect(candidate: OtaCandidate | null) {
115
+ const policy =
116
+ manifestDetails(candidate?.manifest)?.extra?.updatePolicy ?? null;
117
+ patch({ candidate, policy, blocked: false, blockReason: null });
118
+ if (!policy) return;
119
+ if (
120
+ policy.schemaVersion !== 1 ||
121
+ !["manual", "background"].includes(policy.delivery)
122
+ ) {
123
+ patch({ blocked: true, blockReason: "unsupported-policy" });
124
+ return;
125
+ }
126
+ const guard = policy.guard;
127
+ if (!guard) return;
128
+ // Fail closed while an asynchronous application guard is being evaluated.
129
+ patch({ blocked: true, blockReason: guard.action || "unsupported-policy" });
130
+ if (
131
+ guard.action === "ota-force-update" ||
132
+ guard.action === "ota-force-store-update"
133
+ )
134
+ return;
135
+ const handler = options().guardHandlers[guard.action];
136
+ if (!handler) return;
137
+ const decision = await handler({
138
+ action: guard.action,
139
+ payload: guard.payload,
140
+ manifest: candidate?.manifest,
141
+ });
142
+ if (decision === "allow") patch({ blocked: false, blockReason: null });
143
+ }
144
+ async function inspectRunning() {
145
+ const running = deps.runningCandidate?.();
146
+ // Force OTA is fulfilled by launching it. Store/custom guards still apply
147
+ // after a native cold start, including a bundle fetched during a release race.
148
+ if (
149
+ manifestDetails(running?.manifest)?.extra?.updatePolicy?.guard?.action ===
150
+ "ota-force-update"
151
+ )
152
+ return inspect(null);
153
+ return inspect(running || null);
154
+ }
155
+ function canDownload() {
156
+ return !state.blocked || state.blockReason === "ota-force-update";
157
+ }
158
+ async function downloadInternal() {
159
+ if (!state.available && !state.pending)
160
+ throw new Error("Check for an update before downloading");
161
+ if (!canDownload()) throw new Error("Update is blocked by its guard");
162
+ patch({ status: "downloading" });
163
+ const result = await deps.fetch();
164
+ if (result.isNew || result.isRollBackToEmbedded) {
165
+ const candidate = target(result);
166
+ pendingKey = key(candidate);
167
+ pendingGeneration += 1;
168
+ // Fetch performs another manifest request: its policy can differ from check's.
169
+ patch({ pending: true, available: true });
170
+ await inspect(candidate);
171
+ }
172
+ return result;
173
+ }
174
+ async function reloadInternal() {
175
+ if (!state.pending) throw new Error("No downloaded update is ready");
176
+ if (!canDownload()) throw new Error("Update is blocked by its guard");
177
+ if (!deps.isActive())
178
+ throw new Error("Reload is only allowed while the app is active");
179
+ patch({ status: "reloading" });
180
+ return deps.reload();
181
+ }
182
+ async function automate(allowDownload = true) {
183
+ const settings = options();
184
+ if (
185
+ allowDownload &&
186
+ !state.pending &&
187
+ state.available &&
188
+ canDownload() &&
189
+ (settings.autoUpdate ||
190
+ state.policy?.delivery === "background" ||
191
+ state.blockReason === "ota-force-update")
192
+ ) {
193
+ await downloadInternal();
194
+ }
195
+ // A background policy always wins over autoReload. Guards are re-evaluated after fetch.
196
+ if (
197
+ state.pending &&
198
+ canDownload() &&
199
+ settings.autoReload &&
200
+ state.policy?.delivery !== "background" &&
201
+ deps.isActive()
202
+ )
203
+ await reloadInternal();
204
+ }
205
+ function check() {
206
+ return run("checking", async () => {
207
+ const result = await deps.check();
208
+ if (result.isAvailable || result.isRollBackToEmbedded) {
209
+ patch({ available: true });
210
+ // Never replace the policy governing an already downloaded bundle with a different candidate.
211
+ if (!state.pending) await inspect(target(result));
212
+ } else if (!state.pending) {
213
+ patch({ available: false });
214
+ await inspectRunning();
215
+ }
216
+ if (state.pending) await inspect(state.candidate);
217
+ await automate();
218
+ return result;
219
+ });
220
+ }
221
+ function automaticCheck() {
222
+ if (
223
+ !deps.enabled ||
224
+ !options().autoCheck ||
225
+ !deps.isActive() ||
226
+ flight ||
227
+ now() - lastAutomaticCheck < 60000
228
+ )
229
+ return;
230
+ lastAutomaticCheck = now();
231
+ void check().catch(() => undefined);
232
+ }
233
+ const api = {
234
+ getSnapshot: () => state,
235
+ subscribe(listener: () => void) {
236
+ listeners.add(listener);
237
+ return () => listeners.delete(listener);
238
+ },
239
+ initialize,
240
+ configure(owner: symbol, value: OtaOptions) {
241
+ owners.set(owner, value);
242
+ },
243
+ removeOwner(owner: symbol) {
244
+ owners.delete(owner);
245
+ },
246
+ automaticCheck,
247
+ check,
248
+ download: () =>
249
+ run("downloading", async () => {
250
+ const result = await downloadInternal();
251
+ await automate(false);
252
+ return result;
253
+ }),
254
+ reload: () => run("reloading", reloadInternal),
255
+ retry: () => check(),
256
+ openStore: () =>
257
+ run("opening-store", async () => {
258
+ if (state.blockReason !== "ota-force-store-update")
259
+ throw new Error("No store upgrade is required");
260
+ await deps.openStore(state.policy?.guard?.payload);
261
+ }),
262
+ syncPending(candidate: OtaCandidate | null): Promise<void> {
263
+ if (!candidate || key(candidate) === pendingKey) return Promise.resolve();
264
+ if (flight) {
265
+ const observedGeneration = pendingGeneration;
266
+ return flight
267
+ .catch(() => undefined)
268
+ .then(() => {
269
+ if (pendingGeneration === observedGeneration)
270
+ return api.syncPending(candidate);
271
+ });
272
+ }
273
+ return run("checking", async () => {
274
+ pendingKey = key(candidate);
275
+ pendingGeneration += 1;
276
+ patch({ pending: true, available: true });
277
+ await inspect(candidate);
278
+ // Synchronizing native state never implicitly reloads a restored bundle.
279
+ });
280
+ },
281
+ };
282
+ return api;
283
+ }
284
+
285
+ function target(result: OtaCheckResult | OtaFetchResult): OtaCandidate {
286
+ if (result.isRollBackToEmbedded) return { type: "rollback", manifest: null };
287
+ return { type: "new", manifest: result.manifest };
288
+ }
289
+ function key(candidate: OtaCandidate) {
290
+ return candidate.type === "rollback"
291
+ ? "rollback"
292
+ : manifestDetails(candidate.manifest)?.id;
293
+ }
@@ -0,0 +1,153 @@
1
+ import AsyncStorage from "@react-native-async-storage/async-storage";
2
+ import * as Application from "expo-application";
3
+ import * as Crypto from "expo-crypto";
4
+ import * as SecureStore from "expo-secure-store";
5
+ import { createDeviceIdentity } from "./device-identity";
6
+ import * as Updates from "expo-updates";
7
+ import { AppState, Platform } from "react-native";
8
+ import { createInstallationClient } from "./controller";
9
+ import config from "./config.json";
10
+ import { manifestDetails } from "./types";
11
+
12
+ class HeartbeatError extends Error {
13
+ constructor(
14
+ message: string,
15
+ readonly permanent: boolean,
16
+ ) {
17
+ super(message);
18
+ }
19
+ }
20
+
21
+ const STORAGE_KEY = "@ota-client/installation-v1";
22
+ export const enabled = Platform.OS !== "web" && !__DEV__ && Updates.isEnabled;
23
+ const resolveDeviceId = createDeviceIdentity({
24
+ platform: Platform.OS,
25
+ scope: `${Application.applicationId}:${config.identityNamespace}`,
26
+ androidId: () => Application.getAndroidId(),
27
+ readSecure: (key) => SecureStore.getItemAsync(key),
28
+ writeSecure: (key, value) =>
29
+ SecureStore.setItemAsync(key, value, {
30
+ keychainAccessible: SecureStore.WHEN_UNLOCKED_THIS_DEVICE_ONLY,
31
+ }),
32
+ uuid: () => Crypto.randomUUID(),
33
+ digest: (value) =>
34
+ Crypto.digestStringAsync(Crypto.CryptoDigestAlgorithm.SHA256, value),
35
+ });
36
+ let deviceId: string | null = null;
37
+ const client = createInstallationClient({
38
+ read: () => AsyncStorage.getItem(STORAGE_KEY),
39
+ write: (value) => AsyncStorage.setItem(STORAGE_KEY, value),
40
+ uuid: () => Crypto.randomUUID(),
41
+ setIdentity: async (id) => {
42
+ await Updates.setExtraParamAsync("installation_id", id);
43
+ // Temporary Keychain failure must not stop installation telemetry or keep a stale identity.
44
+ deviceId = await resolveDeviceId().catch(() => null);
45
+ await Updates.setExtraParamAsync("device_id", deviceId);
46
+ },
47
+ snapshot: () => ({
48
+ ...(deviceId ? { deviceId } : {}),
49
+ platform: Platform.OS,
50
+ channel:
51
+ manifestDetails(Updates.manifest)?.metadata?.channel || config.channel,
52
+ runtimeVersion: Updates.runtimeVersion,
53
+ updateId: Updates.updateId,
54
+ nativeVersion: Application.nativeApplicationVersion,
55
+ nativeBuild: Application.nativeBuildVersion,
56
+ isEmbeddedLaunch: Updates.isEmbeddedLaunch,
57
+ isEmergencyLaunch: Updates.isEmergencyLaunch,
58
+ }),
59
+ send: async (event) => {
60
+ const abort = new AbortController();
61
+ const timeout = setTimeout(() => abort.abort(), 8000);
62
+ try {
63
+ const response = await fetch(config.heartbeatUrl, {
64
+ method: "POST",
65
+ headers: { "Content-Type": "application/json" },
66
+ body: JSON.stringify(event),
67
+ signal: abort.signal,
68
+ });
69
+ if (!response.ok) {
70
+ const error = new HeartbeatError(
71
+ `Heartbeat HTTP ${response.status}`,
72
+ response.status === 400 || response.status === 409,
73
+ );
74
+ throw error;
75
+ }
76
+ const result = await response.json();
77
+ if (!["accepted", "duplicate", "stale"].includes(result.status))
78
+ throw new Error("Invalid heartbeat response");
79
+ } finally {
80
+ clearTimeout(timeout);
81
+ }
82
+ },
83
+ });
84
+
85
+ let started = false;
86
+ let timer: ReturnType<typeof setTimeout> | undefined;
87
+ let lastObservation = 0;
88
+ let failures = 0;
89
+ let ticking: Promise<void> | undefined;
90
+ function schedule() {
91
+ clearTimeout(timer);
92
+ if (AppState.currentState !== "active") return;
93
+ timer = setTimeout(tick, Math.min(60000 * 2 ** failures, 300000));
94
+ }
95
+ async function performTick() {
96
+ clearTimeout(timer);
97
+ try {
98
+ // Retry the exact durable event before replacing it with a fresh observation.
99
+ try {
100
+ await client.flush();
101
+ } catch (error) {
102
+ if (!(error instanceof HeartbeatError) || !error.permanent) throw error;
103
+ }
104
+ if (Date.now() - lastObservation >= 60000) {
105
+ await client.observe();
106
+ lastObservation = Date.now();
107
+ }
108
+ failures = 0;
109
+ } catch {
110
+ failures = Math.min(failures + 1, 3);
111
+ } finally {
112
+ schedule();
113
+ }
114
+ }
115
+ function tick() {
116
+ if (ticking) return ticking;
117
+ ticking = performTick().finally(() => {
118
+ ticking = undefined;
119
+ });
120
+ return ticking;
121
+ }
122
+ export function start() {
123
+ if (started || !enabled) return;
124
+ started = true;
125
+ // Registration of the original application entry never waits for telemetry.
126
+ void client
127
+ .observe()
128
+ .then(() => {
129
+ lastObservation = Date.now();
130
+ })
131
+ .catch(() => undefined)
132
+ .finally(schedule);
133
+ AppState.addEventListener("change", (state) => {
134
+ if (state === "active") void tick();
135
+ else clearTimeout(timer);
136
+ });
137
+ }
138
+ export async function getInstallationId() {
139
+ if (!enabled) return null;
140
+ return client.ready();
141
+ }
142
+ export async function getDeviceId() {
143
+ await getInstallationId();
144
+ return deviceId;
145
+ }
146
+ export async function checkForUpdateAsync() {
147
+ await getInstallationId();
148
+ return Updates.checkForUpdateAsync();
149
+ }
150
+ export async function fetchUpdateAsync() {
151
+ await getInstallationId();
152
+ return Updates.fetchUpdateAsync();
153
+ }
@@ -0,0 +1,85 @@
1
+ import type { ReactNode } from "react";
2
+
3
+ export interface OtaPolicy {
4
+ schemaVersion: number;
5
+ delivery: "manual" | "background";
6
+ guard?: { action: string; payload?: unknown };
7
+ }
8
+
9
+ export interface OtaManifest {
10
+ id?: string;
11
+ extra?: { updatePolicy?: OtaPolicy };
12
+ metadata?: { channel?: string };
13
+ }
14
+
15
+ export interface OtaCandidate {
16
+ type: "new" | "rollback";
17
+ manifest: unknown;
18
+ }
19
+
20
+ export interface OtaCheckResult {
21
+ isAvailable: boolean;
22
+ isRollBackToEmbedded?: boolean;
23
+ manifest?: unknown;
24
+ }
25
+
26
+ export interface OtaFetchResult {
27
+ isNew: boolean;
28
+ isRollBackToEmbedded?: boolean;
29
+ manifest?: unknown;
30
+ }
31
+
32
+ export interface OtaOptions {
33
+ /** Check on mount/foreground, at most once per minute. Default false in the hook. */
34
+ autoCheck?: boolean;
35
+ /** Download ordinary releases automatically; does not control their visibility. */
36
+ autoUpdate?: boolean;
37
+ /** Reload non-background updates while the application is active. */
38
+ autoReload?: boolean;
39
+ guardHandlers?: Record<
40
+ string,
41
+ (context: {
42
+ action: string;
43
+ payload: unknown;
44
+ manifest: unknown;
45
+ }) => "allow" | "block" | Promise<"allow" | "block">
46
+ >;
47
+ }
48
+
49
+ export interface OtaState {
50
+ enabled: boolean;
51
+ status: "idle" | "checking" | "downloading" | "reloading" | "opening-store";
52
+ installationId: string | null;
53
+ deviceId: string | null;
54
+ available: boolean;
55
+ pending: boolean;
56
+ candidate: OtaCandidate | null;
57
+ policy: OtaPolicy | null;
58
+ blocked: boolean;
59
+ blockReason: string | null;
60
+ error: Error | null;
61
+ }
62
+
63
+ export interface OtaController extends OtaState {
64
+ isBusy: boolean;
65
+ check(): Promise<OtaCheckResult>;
66
+ download(): Promise<OtaFetchResult>;
67
+ reload(): Promise<void>;
68
+ retry(): Promise<OtaCheckResult>;
69
+ openStore(): Promise<void>;
70
+ }
71
+
72
+ export interface OtaUpdatesProps extends OtaOptions {
73
+ renderBlocked?: (controller: OtaController) => ReactNode;
74
+ renderAvailable?: (
75
+ controller: OtaController,
76
+ dismiss: () => void,
77
+ ) => ReactNode;
78
+ }
79
+
80
+ /** Native manifests are data, not necessarily the full Expo manifest schema. */
81
+ export function manifestDetails(manifest: unknown): OtaManifest | null {
82
+ return manifest && typeof manifest === "object"
83
+ ? (manifest as OtaManifest)
84
+ : null;
85
+ }
@@ -0,0 +1,25 @@
1
+ import type { ReactNode } from "react";
2
+ import type { OtaController, OtaUpdatesProps } from "../types";
3
+ import { OtaUpdateOverlay } from "./ota-updates";
4
+
5
+ /** Compatibility for existing layouts; new integrations render OtaUpdates beside navigation. */
6
+ export function OtaUpdateGate({
7
+ controller,
8
+ children,
9
+ renderBlocked,
10
+ }: {
11
+ controller: OtaController;
12
+ children?: ReactNode;
13
+ renderBlocked?: OtaUpdatesProps["renderBlocked"];
14
+ }) {
15
+ return (
16
+ <>
17
+ {children}
18
+ <OtaUpdateOverlay
19
+ controller={controller}
20
+ renderBlocked={renderBlocked}
21
+ showAvailable={false}
22
+ />
23
+ </>
24
+ );
25
+ }