create-expo-updates-server 0.1.5 → 0.2.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 (141) hide show
  1. package/dist/template/.dockerignore +16 -0
  2. package/dist/template/README.md +51 -660
  3. package/dist/template/app/api/admin/device-targets/route.test.ts +43 -0
  4. package/dist/template/app/api/admin/device-targets/route.ts +91 -0
  5. package/dist/template/app/api/admin/devices/route.test.ts +41 -0
  6. package/dist/template/app/api/admin/devices/route.ts +15 -0
  7. package/dist/template/app/api/admin/updates/[encodedKey]/audience/route.ts +75 -0
  8. package/dist/template/app/api/device-heartbeat/route.ts +2 -0
  9. package/dist/template/app/globals.css +114 -15
  10. package/dist/template/app/layout.tsx +12 -4
  11. package/dist/template/app/login/page.tsx +22 -18
  12. package/dist/template/app/updates/[encodedKey]/page.tsx +112 -88
  13. package/dist/template/app/updates/devices/page.tsx +264 -0
  14. package/dist/template/app/updates/embedded/page.tsx +102 -68
  15. package/dist/template/app/updates/emergency-redirects/page.tsx +144 -111
  16. package/dist/template/app/updates/layout.tsx +6 -1
  17. package/dist/template/app/updates/page.tsx +262 -212
  18. package/dist/template/components/admin/admin-shell.tsx +196 -0
  19. package/dist/template/components/admin/language-switcher.tsx +25 -0
  20. package/dist/template/components/admin/theme-provider.tsx +15 -0
  21. package/dist/template/components/ui/alert.tsx +65 -0
  22. package/dist/template/components/ui/badge.tsx +47 -0
  23. package/dist/template/components/ui/button.tsx +63 -0
  24. package/dist/template/components/ui/card.tsx +91 -0
  25. package/dist/template/components/ui/chart.tsx +373 -0
  26. package/dist/template/components/ui/checkbox.tsx +31 -0
  27. package/dist/template/components/ui/dialog.tsx +158 -0
  28. package/dist/template/components/ui/dropdown-menu.tsx +256 -0
  29. package/dist/template/components/ui/input.tsx +20 -0
  30. package/dist/template/components/ui/label.tsx +23 -0
  31. package/dist/template/components/ui/native-select.tsx +61 -0
  32. package/dist/template/components/ui/popover.tsx +88 -0
  33. package/dist/template/components/ui/scroll-area.tsx +57 -0
  34. package/dist/template/components/ui/select.tsx +189 -0
  35. package/dist/template/components/ui/separator.tsx +27 -0
  36. package/dist/template/components/ui/sheet.tsx +142 -0
  37. package/dist/template/components/ui/sidebar.tsx +736 -0
  38. package/dist/template/components/ui/skeleton.tsx +13 -0
  39. package/dist/template/components/ui/switch.tsx +34 -0
  40. package/dist/template/components/ui/table.tsx +115 -0
  41. package/dist/template/components/ui/tabs.tsx +90 -0
  42. package/dist/template/components/ui/textarea.tsx +17 -0
  43. package/dist/template/components/ui/tooltip.tsx +56 -0
  44. package/dist/template/components.json +22 -0
  45. package/dist/template/docs/admin-ui.md +35 -0
  46. package/dist/template/docs/device-targeting.md +129 -0
  47. package/dist/template/docs/doctor.md +137 -0
  48. package/dist/template/docs/expo-app-setup.md +174 -47
  49. package/dist/template/docs/getting-started.md +105 -146
  50. package/dist/template/docs/getting-started.ru.md +106 -191
  51. package/dist/template/docs/index.md +14 -33
  52. package/dist/template/docs/installation-telemetry.md +233 -0
  53. package/dist/template/docs/migrations/2026-10-16-manifest-identity.sql +89 -0
  54. package/dist/template/docs/migrations/2026-10-19-device-heartbeat.sql +131 -0
  55. package/dist/template/docs/migrations/2026-10-22-device-analytics.sql +264 -0
  56. package/dist/template/docs/migrations/2026-10-22-device-targeting-activation.sql +108 -0
  57. package/dist/template/docs/migrations/2026-10-22-device-targeting.sql +130 -0
  58. package/dist/template/docs/migrations/2026-10-22-device-version-metadata.sql +154 -0
  59. package/dist/template/docs/migrations/schema.sql +868 -6
  60. package/dist/template/docs/npm-installer.md +15 -30
  61. package/dist/template/docs/operations-guide.md +87 -0
  62. package/dist/template/docs/ota-client-lifecycle.md +263 -0
  63. package/dist/template/docs/ota-update-policy.md +36 -2
  64. package/dist/template/docs/supabase-setup.md +4 -0
  65. package/dist/template/hooks/use-mobile.ts +21 -0
  66. package/dist/template/lib/utils.ts +6 -0
  67. package/dist/template/package-lock.json +2325 -101
  68. package/dist/template/package.json +13 -3
  69. package/dist/template/scripts/configure-expo-app.mjs +11 -15
  70. package/dist/template/scripts/doctor.mjs +51 -0
  71. package/dist/template/scripts/ensure-test-bucket.mjs +21 -0
  72. package/dist/template/scripts/lib/device-identity.test.ts +29 -0
  73. package/dist/template/scripts/lib/doctor-probes.mjs +139 -0
  74. package/dist/template/scripts/lib/doctor.mjs +208 -0
  75. package/dist/template/scripts/lib/doctor.test.mjs +262 -0
  76. package/dist/template/scripts/lib/expo-app-configurator.mjs +14 -9
  77. package/dist/template/scripts/lib/expo-app-configurator.test.ts +3 -2
  78. package/dist/template/scripts/lib/ota-client-configurator.mjs +69 -0
  79. package/dist/template/scripts/lib/ota-client-configurator.test.ts +88 -0
  80. package/dist/template/scripts/lib/ota-client.test.ts +55 -0
  81. package/dist/template/scripts/lib/ota-root-hook-patcher.mjs +173 -0
  82. package/dist/template/scripts/lib/ota-root-hook-patcher.test.ts +123 -0
  83. package/dist/template/scripts/lib/ota-update-controller.test.ts +231 -0
  84. package/dist/template/scripts/tests/device-analytics-migrations.mjs +80 -0
  85. package/dist/template/scripts/tests/device-analytics.mjs +126 -0
  86. package/dist/template/scripts/tests/device-heartbeat.mjs +86 -0
  87. package/dist/template/scripts/tests/device-targeting-activation.mjs +111 -0
  88. package/dist/template/scripts/tests/device-targeting.mjs +39 -0
  89. package/dist/template/scripts/tests/device-version-metadata.mjs +31 -0
  90. package/dist/template/scripts/tests/manifest-identity-concurrency.mjs +106 -0
  91. package/dist/template/scripts/tests/manifest-identity.sql +204 -0
  92. package/dist/template/src/client/admin-types.ts +1 -0
  93. package/dist/template/src/client/devices/analytics.tsx +429 -0
  94. package/dist/template/src/client/devices/device-name.tsx +82 -0
  95. package/dist/template/src/client/devices/registry.tsx +399 -0
  96. package/dist/template/src/client/devices/use-devices-report.ts +108 -0
  97. package/dist/template/src/client/devices/version-adoption-chart.tsx +269 -0
  98. package/dist/template/src/client/devices/version-groups.test.ts +57 -0
  99. package/dist/template/src/client/devices/version-groups.ts +101 -0
  100. package/dist/template/src/client/distribution-control.tsx +135 -81
  101. package/dist/template/src/client/guard-action-combobox.tsx +13 -24
  102. package/dist/template/src/client/i18n/en.json +286 -0
  103. package/dist/template/src/client/i18n/messages.test.ts +42 -0
  104. package/dist/template/src/client/i18n/messages.ts +31 -0
  105. package/dist/template/src/client/i18n/provider.tsx +55 -0
  106. package/dist/template/src/client/i18n/use-formatters.ts +38 -0
  107. package/dist/template/src/client/logout-button.tsx +3 -1
  108. package/dist/template/src/client/update-audience-editor.tsx +285 -0
  109. package/dist/template/src/client/update-policy-editor.tsx +53 -41
  110. package/dist/template/src/server/controllers/manifest.test.ts +250 -7
  111. package/dist/template/src/server/controllers/manifest.ts +39 -31
  112. package/dist/template/src/server/devices/audience.test.ts +48 -0
  113. package/dist/template/src/server/devices/audience.ts +86 -0
  114. package/dist/template/src/server/devices/heartbeat.test.ts +39 -0
  115. package/dist/template/src/server/devices/heartbeat.ts +75 -0
  116. package/dist/template/src/server/devices/report-types.ts +114 -0
  117. package/dist/template/src/server/devices/report.test.ts +29 -0
  118. package/dist/template/src/server/devices/report.ts +27 -0
  119. package/dist/template/src/server/lib/admin-audience-activation.test.ts +94 -0
  120. package/dist/template/src/server/lib/admin-updates.ts +32 -168
  121. package/dist/template/src/server/lib/distribution-control.test.ts +23 -2
  122. package/dist/template/src/server/lib/distribution-control.ts +13 -4
  123. package/dist/template/src/server/lib/supabase.js +10 -10
  124. package/dist/template/src/server/lib/supabase.test.ts +11 -0
  125. package/dist/template/src/server/manifest/manifest-identity.test.ts +30 -0
  126. package/dist/template/src/server/manifest/manifest-identity.ts +24 -0
  127. package/dist/template/src/server/manifest/manifest-repository.ts +31 -102
  128. package/dist/template/src/server/manifest/manifest-response.ts +1 -1
  129. package/dist/template/templates/expo-app/ota-client/README.md +59 -0
  130. package/dist/template/templates/expo-app/ota-client/controller.js +60 -0
  131. package/dist/template/templates/expo-app/ota-client/device-identity.js +26 -0
  132. package/dist/template/templates/expo-app/ota-client/docs/update-lifecycle.md +52 -0
  133. package/dist/template/templates/expo-app/ota-client/index.d.ts +47 -0
  134. package/dist/template/templates/expo-app/ota-client/index.js +3 -0
  135. package/dist/template/templates/expo-app/ota-client/model/hooks/useOtaUpdates.js +48 -0
  136. package/dist/template/templates/expo-app/ota-client/model/update-controller.js +182 -0
  137. package/dist/template/templates/expo-app/ota-client/runtime.js +112 -0
  138. package/dist/template/templates/expo-app/ota-client/ui/ota-update-gate.js +56 -0
  139. package/dist/template-manifest.json +582 -77
  140. package/lib/cli.mjs +4 -6
  141. package/package.json +1 -1
@@ -0,0 +1,262 @@
1
+ import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest';
2
+ import fs from 'node:fs/promises';
3
+ import path from 'node:path';
4
+ import os from 'node:os';
5
+ import { execFileSync } from 'node:child_process';
6
+ import { createServer } from 'node:http';
7
+ import { generateKeyPairSync } from 'node:crypto';
8
+ import { parseDoctorArgs, readDoctorEnv, runDoctor } from './doctor.mjs';
9
+ import { probeServer } from './doctor-probes.mjs';
10
+ let root, key, certificate;
11
+ const secret = 'do-not-print-password#private';
12
+ const check = (result, id) => result.checks.find((item) => item.id === id);
13
+ async function fixture() {
14
+ const dir = await fs.mkdtemp(path.join(root, 'case-'));
15
+ await fs.symlink(path.resolve('node_modules'), path.join(dir, 'node_modules'));
16
+ await fs.writeFile(path.join(dir, 'package.json'), '{}');
17
+ await fs.writeFile(path.join(dir, 'server.env'), `CODE_SIGNING_PRIVATE_KEY_PATH=${key}\nOTA_PUBLIC_BASE_URL=https://ota.test\nDATABASE_PROVIDER=pg\nDATABASE_URL=postgresql://tester:${encodeURIComponent(secret)}@127.0.0.1:1/ota\nR2_ENDPOINT=http://127.0.0.1:1\nR2_ACCESS_KEY_ID=test\nR2_SECRET_ACCESS_KEY='${secret}'\nR2_BUCKET=test\n`);
18
+ return dir;
19
+ }
20
+ const offline = (cwd, extra = {}) => runDoctor({ cwd, mode: 'remote', serverEnv: 'server.env', offline: true, certificate, ...extra });
21
+ beforeAll(async () => {
22
+ root = await fs.mkdtemp(path.join(os.tmpdir(), 'ota-doctor-'));
23
+ key = path.join(root, 'key.pem'); certificate = path.join(root, 'certificate.pem');
24
+ execFileSync('openssl', ['req', '-x509', '-newkey', 'rsa:2048', '-nodes', '-sha256', '-days', '2', '-subj', '/CN=doctor-test', '-addext', 'basicConstraints=critical,CA:FALSE', '-addext', 'keyUsage=critical,digitalSignature', '-addext', 'extendedKeyUsage=codeSigning', '-keyout', key, '-out', certificate], { stdio: 'ignore', timeout: 10000 });
25
+ });
26
+ afterAll(async () => { await fs.rm(root, { recursive: true, force: true }); });
27
+
28
+ describe('doctor read-only contract', () => {
29
+ it('checks a valid offline setup and matching cert without networking or modifying files/env', async () => {
30
+ const cwd = await fixture();
31
+ const before = await fs.readFile(path.join(cwd, 'server.env'), 'utf8');
32
+ const ambient = process.env.DATABASE_URL;
33
+ process.env.DATABASE_URL = 'postgresql://ambient-secret@production.invalid/db';
34
+ try {
35
+ const result = await offline(cwd);
36
+ expect(result.status).toBe('pass');
37
+ expect(check(result, 'signing.match').status).toBe('pass');
38
+ expect(check(result, 'database.connection').status).toBe('skip');
39
+ expect(await fs.readFile(path.join(cwd, 'server.env'), 'utf8')).toBe(before);
40
+ expect(process.env.DATABASE_URL).toContain('ambient-secret');
41
+ expect(JSON.stringify(result)).not.toContain(secret);
42
+ expect(JSON.stringify(result)).not.toContain('PRIVATE KEY');
43
+ } finally { if (ambient === undefined) delete process.env.DATABASE_URL; else process.env.DATABASE_URL = ambient; }
44
+ });
45
+ it('parses quoted credentials without shell execution or ambient expansion', async () => {
46
+ const file = path.join(await fixture(), 'quoted.env');
47
+ await fs.writeFile(file, `PASSWORD="hash#value"\nLITERAL='$(touch nope)\u0024{HOME}'\n`);
48
+ expect(await readDoctorEnv(file)).toEqual({ PASSWORD: 'hash#value', LITERAL: '$(touch nope)${HOME}' });
49
+ });
50
+ it('reports missing key and wrong certificate as distinct problems', async () => {
51
+ const cwd = await fixture();
52
+ await fs.appendFile(path.join(cwd, 'server.env'), '\nCODE_SIGNING_PRIVATE_KEY_PATH=/nonexistent-doctor-key\n');
53
+ const missing = await offline(cwd);
54
+ expect(check(missing, 'signing.key').status).toBe('fail');
55
+ expect(check(missing, 'signing.match').status).toBe('skip');
56
+ const other = generateKeyPairSync('rsa', { modulusLength: 2048 }).privateKey.export({ type: 'pkcs8', format: 'pem' });
57
+ const second = await fixture();
58
+ await fs.writeFile(path.join(second, 'other.pem'), other);
59
+ await fs.appendFile(path.join(second, 'server.env'), `\nCODE_SIGNING_PRIVATE_KEY_PATH=${path.join(second, 'other.pem')}\n`);
60
+ expect(check(await offline(second), 'signing.match').status).toBe('fail');
61
+ });
62
+ it('does not fall back to ambient env when selected file is missing', async () => {
63
+ const result = await offline(await fixture(), { serverEnv: 'absent.env' });
64
+ expect(result.status).toBe('fail');
65
+ expect(check(result, 'server.env').status).toBe('fail');
66
+ });
67
+ it('reports database and bucket failures without leaking credentials', async () => {
68
+ const env = await readDoctorEnv(path.join(await fixture(), 'server.env'));
69
+ const result = await probeServer({ env, timeout: 500 });
70
+ expect(check(result, 'database.connection').status).toBe('fail');
71
+ expect(check(result, 'storage.bucket').status).toBe('fail');
72
+ expect(JSON.stringify(result)).not.toContain(secret);
73
+ expect(JSON.stringify(result)).not.toContain(encodeURIComponent(secret));
74
+ });
75
+ it('uses only read-only requests against a missing S3 bucket', async () => {
76
+ const methods = [];
77
+ const server = createServer((req, res) => { methods.push(req.method); res.writeHead(404); res.end(); });
78
+ await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
79
+ try {
80
+ const env = await readDoctorEnv(path.join(await fixture(), 'server.env'));
81
+ env.R2_ENDPOINT = `http://127.0.0.1:${server.address().port}`;
82
+ env.R2_REGION = 'us-east-1'; env.S3_FORCE_PATH_STYLE = 'true'; env.DATABASE_URL = '';
83
+ const result = await probeServer({ env, timeout: 1000 });
84
+ expect(check(result, 'storage.bucket').status).toBe('fail');
85
+ expect(methods).toEqual(['HEAD']);
86
+ } finally { server.closeAllConnections(); await new Promise((resolve) => server.close(resolve)); }
87
+ });
88
+ it('bounds a stalled storage request', async () => {
89
+ const server = createServer(() => {});
90
+ await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
91
+ try {
92
+ const env = await readDoctorEnv(path.join(await fixture(), 'server.env'));
93
+ env.R2_ENDPOINT = `http://127.0.0.1:${server.address().port}`;
94
+ env.R2_REGION = 'us-east-1'; env.S3_FORCE_PATH_STYLE = 'true'; env.DATABASE_URL = '';
95
+ const before = Date.now();
96
+ expect(check(await probeServer({ env, timeout: 500 }), 'storage.bucket').status).toBe('fail');
97
+ expect(Date.now() - before).toBeLessThan(2500);
98
+ } finally { server.closeAllConnections(); await new Promise((resolve) => server.close(resolve)); }
99
+ });
100
+ it('selects the requested Docker project/files, contains no secrets in argv and reports drift', async () => {
101
+ const cwd = await fixture();
102
+ let invocation;
103
+ const result = await runDoctor({ cwd, serverEnv: 'server.env', project: 'isolated', composeFiles: ['docker-compose.yml', 'override.yml'] }, {
104
+ exec: async (...args) => { invocation = args; return { stdout: JSON.stringify({ checks: [], publicUrl: 'https://stale.test' }) }; },
105
+ fetch: async () => new Response(JSON.stringify({ status: 'ok', checks: { database: 'ok' } })),
106
+ });
107
+ expect(invocation[1]).toContain('isolated');
108
+ expect(invocation[1]).toContain(path.join(cwd, 'override.yml'));
109
+ expect(invocation[1]).toContain('-T');
110
+ expect(JSON.stringify(invocation)).not.toContain(secret);
111
+ expect(check(result, 'docker.env-drift').status).toBe('fail');
112
+ });
113
+ it('does not expose Docker stderr or exception text', async () => {
114
+ const result = await runDoctor({ cwd: await fixture(), serverEnv: 'server.env' }, {
115
+ exec: async () => { throw new Error(`Credentials ${secret}`); },
116
+ fetch: async () => { throw new Error(secret); },
117
+ });
118
+ expect(check(result, 'docker.app').status).toBe('fail');
119
+ expect(JSON.stringify(result)).not.toContain(secret);
120
+ });
121
+ it('never executes dynamic Expo config', async () => {
122
+ const cwd = await fixture();
123
+ const app = path.join(cwd, 'app'); await fs.mkdir(app);
124
+ await fs.writeFile(path.join(app, 'app.config.js'), 'throw new Error("must never execute")');
125
+ const result = await offline(cwd, { app });
126
+ expect(check(result, 'app.config').status).toBe('fail');
127
+ expect(JSON.stringify(result)).not.toContain('must never execute');
128
+ });
129
+ it('reports URL mismatch and missing client/root without modifying an app', async () => {
130
+ const cwd = await fixture(); const app = path.join(cwd, 'app'); await fs.mkdir(app);
131
+ const contents = JSON.stringify({ expo: { runtimeVersion: 'one', updates: { url: 'https://wrong.test/api/manifest', checkAutomatically: 'NEVER', requestHeaders: { 'expo-channel-name': 'test' } } } });
132
+ await fs.writeFile(path.join(app, 'app.json'), contents);
133
+ await fs.writeFile(path.join(app, 'package.json'), JSON.stringify({ main: 'expo-router/entry' }));
134
+ await fs.mkdir(path.join(app, 'app'));
135
+ await fs.writeFile(path.join(app, 'app/_layout.tsx'), 'export default function Layout() { return null; }');
136
+ const result = await offline(cwd, { app });
137
+ expect(check(result, 'app.url').status).toBe('fail');
138
+ expect(check(result, 'app.identity').status).toBe('fail');
139
+ expect(check(result, 'app.root').status).toBe('fail');
140
+ expect(await fs.readFile(path.join(app, 'app.json'), 'utf8')).toBe(contents);
141
+ expect(await fs.readFile(path.join(app, 'app/_layout.tsx'), 'utf8')).toBe('export default function Layout() { return null; }');
142
+ });
143
+ it('rejects TLS-only certificates even when the RSA key matches', async () => {
144
+ const cwd = await fixture();
145
+ const tls = path.join(cwd, 'tls.pem');
146
+ execFileSync('openssl', ['req', '-new', '-x509', '-key', key, '-days', '2', '-subj', '/CN=tls-only', '-addext', 'basicConstraints=critical,CA:FALSE', '-addext', 'keyUsage=critical,keyEncipherment', '-addext', 'extendedKeyUsage=serverAuth', '-out', tls], { stdio: 'ignore', timeout: 10000 });
147
+ const result = await offline(cwd, { certificate: tls });
148
+ expect(check(result, 'signing.certificate').status).toBe('fail');
149
+ });
150
+ it('rejects ambient PG identity fallback and makes the default port explicit', async () => {
151
+ const env = await readDoctorEnv(path.join(await fixture(), 'server.env'));
152
+ env.DATABASE_URL = 'postgresql://127.0.0.1/ota';
153
+ const result = await probeServer({ env, network: false });
154
+ expect(check(result, 'database.config').status).toBe('fail');
155
+ env.DATABASE_URL = 'postgresql://tester:password@127.0.0.1/ota?password=';
156
+ expect(check(await probeServer({ env, network: false }), 'database.config').status).toBe('fail');
157
+ });
158
+ it('detects missing migration objects and uses read-only queries with isolated connection options', async () => {
159
+ let config;
160
+ const statements = [];
161
+ vi.doMock('pg', () => ({ default: { Client: class {
162
+ constructor(value) { config = value; }
163
+ on() {}
164
+ async connect() {}
165
+ async end() {}
166
+ async query(sql) { statements.push(sql); return { rows: [{ ready: false }] }; }
167
+ } } }));
168
+ try {
169
+ const env = await readDoctorEnv(path.join(await fixture(), 'server.env'));
170
+ env.DATABASE_URL = 'postgresql://tester:password@127.0.0.1/ota'; env.R2_ENDPOINT = '';
171
+ const result = await probeServer({ env, timeout: 500 });
172
+ expect(check(result, 'database.connection').status).toBe('pass');
173
+ expect(check(result, 'database.schema').status).toBe('fail');
174
+ expect(new URL(config.connectionString).port).toBe('5432');
175
+ expect(config.options).toBe('-c default_transaction_read_only=on');
176
+ expect(config.query_timeout).toBe(500);
177
+ const ambientKeys = ['PGUSER', 'PGPASSWORD', 'PGHOST', 'PGDATABASE', 'PGPORT', 'PGREPLICATION', 'PGCLIENT_ENCODING'];
178
+ const previous = Object.fromEntries(ambientKeys.map((name) => [name, process.env[name]]));
179
+ try {
180
+ for (const name of ambientKeys) process.env[name] = name === 'PGPORT' ? '9999' : 'ambient-unwanted';
181
+ const actualPg = await vi.importActual('pg');
182
+ const actual = new actualPg.default.Client(config).connectionParameters;
183
+ expect({ user: actual.user, password: actual.password, host: actual.host, database: actual.database, port: actual.port, replication: actual.replication, encoding: actual.client_encoding }).toEqual({ user: 'tester', password: 'password', host: '127.0.0.1', database: 'ota', port: 5432, replication: 'false', encoding: 'utf8' });
184
+ } finally {
185
+ for (const name of ambientKeys) { if (previous[name] === undefined) delete process.env[name]; else process.env[name] = previous[name]; }
186
+ }
187
+ expect(statements.every((sql) => sql.trim().startsWith('SELECT'))).toBe(true);
188
+ expect(statements.at(-1)).toContain('trg_ota_updates_activate_audience');
189
+ } finally { vi.doUnmock('pg'); }
190
+ });
191
+ it('validates a complete generated app, then detects missing client files and noncanonical scope', async () => {
192
+ const cwd = await fixture(); const app = path.join(cwd, 'app'); await fs.mkdir(app);
193
+ const deps = ['expo', 'expo-updates', 'expo-application', 'expo-crypto', 'expo-secure-store', '@react-native-async-storage/async-storage'];
194
+ for (const name of deps) {
195
+ const dir = path.join(app, 'node_modules', name); await fs.mkdir(dir, { recursive: true });
196
+ await fs.writeFile(path.join(dir, 'index.js'), '');
197
+ }
198
+ await fs.writeFile(path.join(app, 'package.json'), JSON.stringify({ main: 'ota-entry.js', dependencies: Object.fromEntries(deps.map((name) => [name, '1'])), scripts: { 'ota:publish': 'node scripts/ota-publish/index.mjs' } }));
199
+ const config = { expo: { runtimeVersion: 'v1', updates: { url: 'https://ota.test/api/manifest', checkAutomatically: 'NEVER', requestHeaders: { 'expo-channel-name': 'test' }, codeSigningCertificate: certificate, codeSigningMetadata: { keyid: 'main', alg: 'rsa-v1_5-sha256' } } } };
200
+ await fs.writeFile(path.join(app, 'app.json'), JSON.stringify(config));
201
+ await fs.cp(path.resolve('templates/expo-app/ota-client'), path.join(app, 'ota-client'), { recursive: true });
202
+ await fs.writeFile(path.join(app, 'ota-client/config.json'), JSON.stringify({ channel: 'test', heartbeatUrl: 'https://ota.test/api/device-heartbeat', identityNamespace: 'stable-test' }));
203
+ await fs.writeFile(path.join(app, 'ota-entry.js'), "require('./ota-client').start(); require('expo/AppEntry');");
204
+ await fs.writeFile(path.join(app, 'ota-client-entry.json'), JSON.stringify({ originalEntry: 'expo/AppEntry' }));
205
+ const { patchOtaRootHook } = await import('./ota-root-hook-patcher.mjs');
206
+ const source = patchOtaRootHook('export default function App() { return null; }', path.join(app, 'App.tsx'), app);
207
+ await fs.writeFile(path.join(app, 'App.tsx'), source);
208
+ await fs.writeFile(path.join(app, '.env.ota'), 'EXPO_UPDATE_CHANNEL=test\nOTA_SERVER_URL=https://ota.test\nOTA_DATABASE_URL=postgresql://user:pass@127.0.0.1/db\nR2_ENDPOINT=http://127.0.0.1:9000\nR2_ACCESS_KEY_ID=key\nR2_SECRET_ACCESS_KEY=secret\nR2_BUCKET=test\n');
209
+ const valid = await offline(cwd, { app });
210
+ expect(valid.checks.filter((item) => item.status === 'fail')).toEqual([]);
211
+ expect(check(valid, 'app.root').status).toBe('pass');
212
+ expect(await fs.readFile(path.join(app, 'App.tsx'), 'utf8')).toBe(source);
213
+ await fs.unlink(path.join(app, 'ota-client/runtime.js'));
214
+ expect(check(await offline(cwd, { app }), 'app.client').status).toBe('fail');
215
+ config.expo.updates.requestHeaders['expo-channel-name'] = 'Test'; config.expo.runtimeVersion = ' v1 ';
216
+ await fs.writeFile(path.join(app, 'app.json'), JSON.stringify(config));
217
+ const invalid = await offline(cwd, { app });
218
+ expect(check(invalid, 'app.scope').status).toBe('fail');
219
+ expect(check(invalid, 'app.publisher-channel').status).toBe('fail');
220
+ });
221
+ it('checks Supabase with GET only and reports missing REST tables', async () => {
222
+ const requests = []; let missing = false;
223
+ const server = createServer((req, res) => {
224
+ requests.push(req.method);
225
+ res.writeHead(missing && req.url.includes('ota_named_devices') ? 404 : 200, { 'content-type': 'application/json' }); res.end('[]');
226
+ });
227
+ await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
228
+ try {
229
+ const env = { CODE_SIGNING_PRIVATE_KEY_PATH: key, OTA_PUBLIC_BASE_URL: 'https://ota.test', DATABASE_PROVIDER: 'supabase', SUPABASE_PROJECT_URL: `http://127.0.0.1:${server.address().port}`, SUPABASE_SERVICE_ROLE_KEY: secret };
230
+ const valid = await probeServer({ env, timeout: 500 });
231
+ expect(check(valid, 'database.schema').status).toBe('pass');
232
+ expect(check(valid, 'database.schema-functions').status).toBe('warn');
233
+ expect(check(valid, 'storage.bucket').status).toBe('pass');
234
+ missing = true;
235
+ expect(check(await probeServer({ env, timeout: 500 }), 'database.schema').status).toBe('fail');
236
+ expect(requests.every((method) => method === 'GET')).toBe(true);
237
+ expect(JSON.stringify(valid)).not.toContain(secret);
238
+ } finally { server.closeAllConnections(); await new Promise((resolve) => server.close(resolve)); }
239
+ });
240
+ it('reports a private-key file that cannot be read as a signing failure', async () => {
241
+ const cwd = await fixture(); const unreadable = path.join(cwd, 'unreadable.pem');
242
+ await fs.copyFile(key, unreadable); await fs.chmod(unreadable, 0);
243
+ try {
244
+ // Root can bypass Unix permissions; a directory still exercises a read failure there.
245
+ const inaccessible = process.getuid?.() === 0 ? cwd : unreadable;
246
+ await fs.appendFile(path.join(cwd, 'server.env'), `\nCODE_SIGNING_PRIVATE_KEY_PATH=${inaccessible}\n`);
247
+ expect(check(await offline(cwd), 'signing.key').status).toBe('fail');
248
+ } finally { await fs.chmod(unreadable, 0o600); }
249
+ });
250
+ it('validates CLI options and produces parseable JSON/exit codes', async () => {
251
+ expect(parseDoctorArgs(['--offline', '--compose-file', 'a', '--compose-file', 'b']).composeFiles).toEqual(['a', 'b']);
252
+ expect(() => parseDoctorArgs(['--timeout', '0'])).toThrow();
253
+ expect(() => parseDoctorArgs(['--mode', 'remote', '--project', 'test'])).toThrow();
254
+ expect(() => parseDoctorArgs(['--server-env'])).toThrow();
255
+ const cli = path.resolve('scripts/doctor.mjs');
256
+ const cwd = await fixture();
257
+ const valid = execFileSync(process.execPath, [cli, '--mode', 'remote', '--server-env', 'server.env', '--offline', '--json'], { cwd, encoding: 'utf8' });
258
+ expect(JSON.parse(valid).status).toBe('pass');
259
+ try { execFileSync(process.execPath, [cli, '--server-env', 'missing', '--json'], { cwd, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }); expect.unreachable(); }
260
+ catch (error) { expect(error.status).toBe(1); expect(JSON.parse(error.stdout).status).toBe('fail'); }
261
+ });
262
+ });
@@ -1,3 +1,4 @@
1
+ import { planOtaClient } from './ota-client-configurator.mjs';
1
2
  import { execFileSync } from "node:child_process";
2
3
  import crypto from "node:crypto";
3
4
  import fs from "node:fs";
@@ -143,7 +144,7 @@ function getPackageCommands(packageManager, platform) {
143
144
 
144
145
  if (packageManager === "pnpm") {
145
146
  return {
146
- installExpoUpdates: ["pnpm", ["exec", "expo", "install", "expo-updates"]],
147
+ installExpoUpdates: ["pnpm", ["exec", "expo", "install", "expo-updates", "expo-application", "expo-crypto", "expo-secure-store", "@react-native-async-storage/async-storage"]],
147
148
  installPublisherDependencies: [
148
149
  "pnpm",
149
150
  ["add", "--save-dev", ...PUBLISHER_DEPENDENCIES],
@@ -154,7 +155,7 @@ function getPackageCommands(packageManager, platform) {
154
155
 
155
156
  if (packageManager === "yarn") {
156
157
  return {
157
- installExpoUpdates: ["yarn", ["expo", "install", "expo-updates"]],
158
+ installExpoUpdates: ["yarn", ["expo", "install", "expo-updates", "expo-application", "expo-crypto", "expo-secure-store", "@react-native-async-storage/async-storage"]],
158
159
  installPublisherDependencies: [
159
160
  "yarn",
160
161
  ["add", "--dev", ...PUBLISHER_DEPENDENCIES],
@@ -165,7 +166,7 @@ function getPackageCommands(packageManager, platform) {
165
166
 
166
167
  if (packageManager === "bun") {
167
168
  return {
168
- installExpoUpdates: ["bunx", ["expo", "install", "expo-updates"]],
169
+ installExpoUpdates: ["bunx", ["expo", "install", "expo-updates", "expo-application", "expo-crypto", "expo-secure-store", "@react-native-async-storage/async-storage"]],
169
170
  installPublisherDependencies: [
170
171
  "bun",
171
172
  ["add", "--dev", ...PUBLISHER_DEPENDENCIES],
@@ -175,7 +176,7 @@ function getPackageCommands(packageManager, platform) {
175
176
  }
176
177
 
177
178
  return {
178
- installExpoUpdates: ["npx", ["expo", "install", "expo-updates"]],
179
+ installExpoUpdates: ["npx", ["expo", "install", "expo-updates", "expo-application", "expo-crypto", "expo-secure-store", "@react-native-async-storage/async-storage"]],
179
180
  installPublisherDependencies: [
180
181
  "npm",
181
182
  ["install", "--save-dev", ...PUBLISHER_DEPENDENCIES],
@@ -327,6 +328,7 @@ function getLocalDockerPublisherEnv({
327
328
  channel,
328
329
  serverRoot,
329
330
  serverUrl,
331
+ serverEnv,
330
332
  }) {
331
333
  const hostname = new URL(serverUrl).hostname;
332
334
  const usesLocalDocker =
@@ -337,7 +339,7 @@ function getLocalDockerPublisherEnv({
337
339
  return null;
338
340
  }
339
341
 
340
- const serverEnvPath = path.join(serverRoot, ".env");
342
+ const serverEnvPath = serverEnv ? path.resolve(serverEnv) : path.join(serverRoot, ".env");
341
343
  if (!fs.existsSync(serverEnvPath)) {
342
344
  return null;
343
345
  }
@@ -451,9 +453,9 @@ function patchPackageJson(packageJson, platform) {
451
453
  }
452
454
  }
453
455
  if (platform !== "ios") {
454
- packageJson.scripts["ota:build:android:apk"] =
456
+ packageJson.scripts["ota:build:android:apk"] ||=
455
457
  `cd android && ./gradlew app:assembleRelease && cd .. && OTA_EMBEDDED_REGISTER_STRICT=true sh ${ANDROID_REGISTER_SCRIPT}`;
456
- packageJson.scripts["ota:build:android:aab"] =
458
+ packageJson.scripts["ota:build:android:aab"] ||=
457
459
  `cd android && ./gradlew app:bundleRelease && cd .. && OTA_EMBEDDED_REGISTER_STRICT=true sh ${ANDROID_REGISTER_SCRIPT}`;
458
460
  }
459
461
  return packageJson;
@@ -559,6 +561,7 @@ export function configureExpoApp(
559
561
  validateCertificate(certificatePath);
560
562
  const manifestUrl = resolveManifestUrl(rawOptions.serverUrl);
561
563
  const project = validateProject(appRoot);
564
+ const clientPlan = planOtaClient({ appRoot, templateRoot, packageJson: project.packageJson, manifestUrl, channel, force });
562
565
  const packageManager = detectPackageManager(appRoot);
563
566
  const commands = getPackageCommands(packageManager, platform);
564
567
  const certificateDestination = path.join(
@@ -663,6 +666,7 @@ export function configureExpoApp(
663
666
  );
664
667
  const publisherEnvDestination = path.join(appRoot, ".env.ota");
665
668
  const localPublisherEnv = getLocalDockerPublisherEnv({
669
+ serverEnv: rawOptions.serverEnv,
666
670
  channel,
667
671
  serverRoot,
668
672
  serverUrl: manifestUrl,
@@ -683,7 +687,7 @@ export function configureExpoApp(
683
687
  ),
684
688
  }),
685
689
  );
686
- const migrationWarnings = [];
690
+ const migrationWarnings = [...clientPlan.warnings];
687
691
  const legacyFileMigrations = [
688
692
  planLegacyFileMigration(
689
693
  legacyAndroidRegistrarDestination,
@@ -766,6 +770,7 @@ export function configureExpoApp(
766
770
  }),
767
771
  );
768
772
 
773
+ clientPlan.apply();
769
774
  copyFile(certificatePath, certificateDestination);
770
775
  copyFile(publisherSource, publisherDestination);
771
776
  copyFile(exportCommandSource, exportCommandDestination);
@@ -792,7 +797,7 @@ export function configureExpoApp(
792
797
  const installedPackageJson = readJson(project.packagePath);
793
798
  writeJson(
794
799
  project.packagePath,
795
- patchPackageJson(installedPackageJson, platform),
800
+ clientPlan.patchPackage(patchPackageJson(installedPackageJson, platform)),
796
801
  );
797
802
 
798
803
  commandRunner(...commands.installPublisherDependencies, appRoot);
@@ -334,6 +334,7 @@ function createFixture() {
334
334
 
335
335
  const appRoot = path.join(root, "app");
336
336
  fs.mkdirSync(appRoot, { recursive: true });
337
+ fs.writeFileSync(path.join(appRoot, "App.tsx"), "export default function App() { return null; }\n");
337
338
  fs.writeFileSync(
338
339
  path.join(appRoot, "package.json"),
339
340
  JSON.stringify(
@@ -403,7 +404,7 @@ function createRunner() {
403
404
  const commandRunner = (command: string, args: string[], cwd: string) => {
404
405
  calls.push({ command, args, cwd });
405
406
 
406
- if (args.join(" ") === "expo install expo-updates") {
407
+ if (args.join(" ").startsWith("expo install expo-updates")) {
407
408
  const packagePath = path.join(cwd, "package.json");
408
409
  const packageJson = JSON.parse(fs.readFileSync(packagePath, "utf8"));
409
410
  packageJson.dependencies["expo-updates"] = "~56.0.0";
@@ -586,7 +587,7 @@ describe("configureExpoApp", () => {
586
587
  expect(calls).toEqual([
587
588
  {
588
589
  command: "npx",
589
- args: ["expo", "install", "expo-updates"],
590
+ args: ["expo", "install", "expo-updates", "expo-application", "expo-crypto", "expo-secure-store", "@react-native-async-storage/async-storage"],
590
591
  cwd: appRoot,
591
592
  },
592
593
  {
@@ -0,0 +1,69 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { planOtaRootHook } from './ota-root-hook-patcher.mjs';
4
+ const ENTRY = 'ota-entry.js';
5
+ const META = 'ota-client-entry.json';
6
+ const extensions = ['tsx', 'ts', 'jsx', 'js', 'mjs', 'cjs'];
7
+ function hasEntry(root, entry, platform) {
8
+ const suffixes = platform === 'web' ? ['web', ''] : [platform, 'native', ''];
9
+ return suffixes.some((suffix) => extensions.some((ext) => fs.existsSync(path.join(root, `${entry}${suffix ? `.${suffix}` : ''}.${ext}`))));
10
+ }
11
+
12
+ // Preflight every generated file before the main configurator changes the project.
13
+ export function planOtaClient({ appRoot, templateRoot, packageJson, manifestUrl, channel, force }) {
14
+ let entry = packageJson.main;
15
+ if (entry === ENTRY || entry === `./${ENTRY}`) {
16
+ const metadata = JSON.parse(fs.readFileSync(path.join(appRoot, META), 'utf8'));
17
+ entry = metadata.originalEntry;
18
+ if (typeof entry !== 'string' || entry.includes('ota-entry')) throw new Error('Invalid original OTA entry metadata');
19
+ } else if (!entry) {
20
+ entry = '__platform_default__';
21
+ } else if (typeof entry !== 'string' || entry.includes('ota-entry')) {
22
+ throw new Error('Invalid application main entry');
23
+ } else if (!entry.startsWith('.') && (fs.existsSync(path.join(appRoot, entry)) || ['android', 'ios', 'web'].some((platform) => hasEntry(appRoot, entry, platform)))) {
24
+ entry = `./${entry}`;
25
+ }
26
+ const heartbeatUrl = new URL(manifestUrl);
27
+ heartbeatUrl.pathname = heartbeatUrl.pathname.replace(/\/manifest\/?$/, '/device-heartbeat');
28
+ heartbeatUrl.search = '';
29
+ heartbeatUrl.hash = '';
30
+ const existingConfigPath = path.join(appRoot, 'ota-client/config.json');
31
+ const existingConfig = fs.existsSync(existingConfigPath) ? JSON.parse(fs.readFileSync(existingConfigPath, 'utf8')) : {};
32
+ // Preserve the namespace when a tunnel URL changes; runtime/channel are deliberately excluded.
33
+ const identityNamespace = existingConfig.identityNamespace || new URL(manifestUrl).origin;
34
+ const defaultEntries = [];
35
+ if (entry === '__platform_default__') {
36
+ for (const platform of ['android', 'ios', 'web']) {
37
+ const source = hasEntry(appRoot, 'index', platform) ? 'require("./index");' : "require('expo').registerRootComponent(require('./App').default);";
38
+ defaultEntries.push([`ota-original-entry.${platform}.js`, `// Generated default ${platform} entry.\n${source}\n`]);
39
+ }
40
+ }
41
+ const original = entry === '__platform_default__' ? "require('./ota-original-entry');" : entry === '__app_fallback__'
42
+ ? "require('expo').registerRootComponent(require('./App').default);"
43
+ : `require(${JSON.stringify(entry)});`;
44
+ const rootHookPlan = planOtaRootHook({ appRoot, originalEntry: entry });
45
+ const files = [
46
+ ...defaultEntries,
47
+ [ENTRY, `// Generated by configure-app. Original entry is preserved in ${META}.\nrequire('./ota-client').start();\n${original}\n`],
48
+ [META, `${JSON.stringify({ originalEntry: entry }, null, 2)}\n`],
49
+ ['ota-client/config.json', `${JSON.stringify({ channel, heartbeatUrl: heartbeatUrl.toString(), identityNamespace }, null, 2)}\n`],
50
+ ...['index.js', 'index.d.ts', 'runtime.js', 'controller.js', 'device-identity.js', 'model/update-controller.js', 'model/hooks/useOtaUpdates.js', 'ui/ota-update-gate.js', 'docs/update-lifecycle.md', 'README.md'].map((name) => [`ota-client/${name}`, fs.readFileSync(path.join(templateRoot, 'ota-client', name), 'utf8')]),
51
+ ];
52
+ for (const [name, content] of files) {
53
+ const destination = path.join(appRoot, name);
54
+ if (fs.existsSync(destination) && fs.readFileSync(destination, 'utf8') !== content && !force) {
55
+ throw new Error(`Refusing to overwrite ${destination}. Re-run with --force.`);
56
+ }
57
+ }
58
+ return {
59
+ warnings: rootHookPlan.warnings,
60
+ apply() {
61
+ for (const [name, content] of [...files, ...rootHookPlan.files]) {
62
+ const destination = path.join(appRoot, name);
63
+ fs.mkdirSync(path.dirname(destination), { recursive: true });
64
+ fs.writeFileSync(destination, content);
65
+ }
66
+ },
67
+ patchPackage(packageJson) { return { ...packageJson, main: ENTRY }; },
68
+ };
69
+ }
@@ -0,0 +1,88 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import os from 'node:os';
4
+ import { afterEach, describe, expect, it } from 'vitest';
5
+ import { planOtaClient } from './ota-client-configurator.mjs';
6
+ const roots: string[] = [];
7
+ afterEach(() => { for (const root of roots.splice(0)) fs.rmSync(root, { recursive: true, force: true }); });
8
+ function setup(main?: string) {
9
+ const appRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'ota-entry-')); roots.push(appRoot);
10
+ const options = { appRoot, templateRoot: path.resolve('templates/expo-app'), packageJson: main ? { main } : {}, manifestUrl: 'https://example.org/prefix/api/manifest', channel: 'test', force: false };
11
+ return { options, entry: () => fs.readFileSync(path.join(appRoot, 'ota-entry.js'), 'utf8') };
12
+ }
13
+ describe('configure-only bootstrap', () => {
14
+ it('preserves Router entry across repeated configurations and keeps URL prefix', () => {
15
+ const f = setup('expo-router/entry'); const plan = planOtaClient(f.options); plan.apply();
16
+ expect(f.entry()).toContain('require("expo-router/entry")');
17
+ planOtaClient({ ...f.options, packageJson: plan.patchPackage(f.options.packageJson) }).apply();
18
+ expect(f.entry()).toContain('require("expo-router/entry")');
19
+ expect(JSON.parse(fs.readFileSync(path.join(f.options.appRoot, 'ota-client/config.json'), 'utf8')).heartbeatUrl).toBe('https://example.org/prefix/api/device-heartbeat');
20
+ });
21
+ it('uses platform-aware root index when main is missing', () => {
22
+ const f = setup(); fs.writeFileSync(path.join(f.options.appRoot, 'index.android.ts'), '');
23
+ planOtaClient(f.options).apply(); expect(fs.readFileSync(path.join(f.options.appRoot, 'ota-original-entry.android.js'), 'utf8')).toContain('require("./index")');
24
+ expect(fs.readFileSync(path.join(f.options.appRoot, 'ota-original-entry.ios.js'), 'utf8')).toContain("require('./App')");
25
+ });
26
+ it('registers root App fallback without depending on hoisted expo/AppEntry', () => {
27
+ const f = setup(); planOtaClient(f.options).apply(); expect(fs.readFileSync(path.join(f.options.appRoot, 'ota-original-entry.ios.js'), 'utf8')).toContain("registerRootComponent(require('./App').default)");
28
+ planOtaClient({ ...f.options, packageJson: { main: 'ota-entry.js' } }).apply();
29
+ });
30
+ it('resolves extensionless local main', () => {
31
+ const f = setup('bootstrap'); fs.writeFileSync(path.join(f.options.appRoot, 'bootstrap.tsx'), '');
32
+ planOtaClient(f.options).apply(); expect(f.entry()).toContain('require("./bootstrap")');
33
+ });
34
+ it('normalizes an existing local custom main and refuses edits without force', () => {
35
+ const f = setup('entry.js'); fs.writeFileSync(path.join(f.options.appRoot, 'entry.js'), '');
36
+ planOtaClient(f.options).apply(); expect(f.entry()).toContain('require("./entry.js")');
37
+ fs.writeFileSync(path.join(f.options.appRoot, 'ota-client/index.js'), 'user changes');
38
+ expect(() => planOtaClient({ ...f.options, packageJson: { main: 'ota-entry.js' } })).toThrow('Refusing');
39
+ });
40
+ it('automatically starts the client, preserves namespace when URL/channel changes, and copies identity model', () => {
41
+ const f = setup('expo-router/entry'); planOtaClient(f.options).apply();
42
+ expect(f.entry().indexOf("require('./ota-client').start()")).toBeLessThan(f.entry().indexOf('require("expo-router/entry")'));
43
+ expect(fs.existsSync(path.join(f.options.appRoot, 'ota-client/device-identity.js'))).toBe(true);
44
+ planOtaClient({ ...f.options, packageJson: { main: 'ota-entry.js' }, manifestUrl: 'https://new-tunnel.example/api/manifest', channel: 'another', force: true }).apply();
45
+ expect(JSON.parse(fs.readFileSync(path.join(f.options.appRoot, 'ota-client/config.json'), 'utf8')).identityNamespace).toBe('https://example.org');
46
+ });
47
+
48
+ it('patches the Router layout without force and preserves custom hook modes on rerun', () => {
49
+ const f = setup('expo-router/entry');
50
+ const layout = path.join(f.options.appRoot, 'src/app/_layout.tsx');
51
+ fs.mkdirSync(path.dirname(layout), { recursive: true });
52
+ fs.writeFileSync(layout, 'export default function Root() { return null; }\n');
53
+ const plan = planOtaClient(f.options);
54
+ expect(plan.warnings).toEqual([]);
55
+ plan.apply();
56
+ expect(fs.readFileSync(layout, 'utf8')).toContain('useOtaUpdates({ autoCheck: true');
57
+ expect(fs.existsSync(path.join(f.options.appRoot, 'ota-client/model/hooks/useOtaUpdates.js'))).toBe(true);
58
+ const customized = fs.readFileSync(layout, 'utf8').replace('autoCheck: true', 'autoCheck: false');
59
+ fs.writeFileSync(layout, customized);
60
+ planOtaClient({ ...f.options, packageJson: plan.patchPackage(f.options.packageJson) }).apply();
61
+ expect(fs.readFileSync(layout, 'utf8')).toBe(customized);
62
+ });
63
+
64
+ it('preflights an unsupported root without mutating application or generated files', () => {
65
+ const f = setup('expo-router/entry');
66
+ const layout = path.join(f.options.appRoot, 'app/_layout.tsx');
67
+ const original = 'export default memo(() => null);\n';
68
+ fs.mkdirSync(path.dirname(layout), { recursive: true });
69
+ fs.writeFileSync(layout, original);
70
+ expect(() => planOtaClient(f.options)).toThrow('unsupported default root');
71
+ expect(fs.readFileSync(layout, 'utf8')).toBe(original);
72
+ expect(fs.existsSync(path.join(f.options.appRoot, 'ota-entry.js'))).toBe(false);
73
+ expect(fs.existsSync(path.join(f.options.appRoot, 'ota-client'))).toBe(false);
74
+ });
75
+
76
+ it('preserves all files if an aliased existing OTA hook cannot be safely resolved', () => {
77
+ const f = setup('expo-router/entry');
78
+ const layout = path.join(f.options.appRoot, 'app/_layout.tsx');
79
+ const original = "import { useOtaUpdates } from '@/ota-client'; export default function Root() { const ota = useOtaUpdates({ autoCheck: false }); return null; }\n";
80
+ fs.mkdirSync(path.dirname(layout), { recursive: true });
81
+ fs.writeFileSync(layout, original);
82
+ expect(() => planOtaClient(f.options)).toThrow('use a relative import to ota-client');
83
+ expect(fs.readFileSync(layout, 'utf8')).toBe(original);
84
+ expect(fs.existsSync(path.join(f.options.appRoot, 'ota-entry.js'))).toBe(false);
85
+ expect(fs.existsSync(path.join(f.options.appRoot, 'ota-client'))).toBe(false);
86
+ });
87
+
88
+ });
@@ -0,0 +1,55 @@
1
+ import { describe, expect, it, vi } from 'vitest';
2
+ import { createInstallationClient } from '../../templates/expo-app/ota-client/controller.js';
3
+ function fixture() {
4
+ let stored: string | null = null;
5
+ let counter = 0;
6
+ const send = vi.fn(async (event: { eventId: string; sequence: number }) => { void event; });
7
+ const write = vi.fn(async (value: string) => { stored = value; });
8
+ const deps = { read: async () => stored, write, uuid: () => `uuid-${++counter}`, snapshot: () => ({ updateId: 'launched' }), send, setIdentity: vi.fn(async (id: string) => { void id; }), now: () => '2026-10-19T12:00:00.000Z' };
9
+ return { deps, send, write, state: () => JSON.parse(stored!), client: createInstallationClient(deps) };
10
+ }
11
+ describe('durable installation client', () => {
12
+ it('keeps identity across controller restarts and increments sequence', async () => {
13
+ const f = fixture(); const id = await f.client.ready(); await f.client.observe();
14
+ const restarted = createInstallationClient(f.deps);
15
+ expect(await restarted.ready()).toBe(id); await restarted.observe();
16
+ expect(f.send.mock.calls.map(([e]) => e.sequence)).toEqual([1, 2]);
17
+ expect(f.state().pending).toBeNull();
18
+ });
19
+ it('retries the identical durable event after offline/restart', async () => {
20
+ const f = fixture(); f.send.mockRejectedValueOnce(new Error('offline'));
21
+ await expect(f.client.observe()).rejects.toThrow('offline');
22
+ const pending = f.state().pending;
23
+ await createInstallationClient(f.deps).flush();
24
+ expect(f.send.mock.calls[1][0]).toEqual(pending);
25
+ expect(f.state().pending).toBeNull();
26
+ });
27
+ it('does not send or expose ephemeral identity when storage fails', async () => {
28
+ const f = fixture(); f.write.mockRejectedValueOnce(new Error('disk'));
29
+ await expect(f.client.observe()).rejects.toThrow('disk'); expect(f.send).not.toHaveBeenCalled();
30
+ expect(f.deps.setIdentity).not.toHaveBeenCalled();
31
+ await f.client.observe(); expect(f.send).toHaveBeenCalledOnce();
32
+ });
33
+ it('never clears a newer pending event when an old request completes', async () => {
34
+ const f = fixture(); let resolve!: () => void;
35
+ f.send.mockImplementationOnce(() => new Promise<void>((r) => { resolve = r; }));
36
+ const first = f.client.observe();
37
+ await vi.waitFor(() => expect(f.send).toHaveBeenCalledOnce());
38
+ const second = f.client.observe();
39
+ await vi.waitFor(() => expect(f.state().sequence).toBe(2));
40
+ resolve(); await Promise.all([first, second]);
41
+ expect(f.state().pending.sequence).toBe(2);
42
+ await f.client.flush(); expect(f.send.mock.calls[1][0].sequence).toBe(2);
43
+ });
44
+ it('serializes concurrent observations with unique sequences', async () => {
45
+ const f = fixture(); await Promise.all(Array.from({ length: 10 }, () => f.client.observe()));
46
+ expect(f.state().sequence).toBe(10); await f.client.flush();
47
+ expect(f.state().pending).toBeNull();
48
+ });
49
+ it('does not lose the outbox when acknowledgement cannot persist', async () => {
50
+ const g = fixture(); let writes = 0; const original = g.deps.write;
51
+ const c = createInstallationClient({ ...g.deps, write: async (v: string) => { if (++writes === 3) throw new Error('ack disk'); await original(v); } });
52
+ await expect(c.observe()).rejects.toThrow('ack disk'); expect(g.state().pending.sequence).toBe(1);
53
+ await c.flush(); expect(g.send.mock.calls[0][0]).toEqual(g.send.mock.calls[1][0]);
54
+ });
55
+ });