create-expo-updates-server 0.3.0 → 0.6.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 (191) hide show
  1. package/README.md +4 -2
  2. package/dist/template/Dockerfile +4 -6
  3. package/dist/template/README.md +5 -10
  4. package/dist/template/app/api/admin/device-favorites/route.test.ts +125 -0
  5. package/dist/template/app/api/admin/device-favorites/route.ts +91 -0
  6. package/dist/template/app/api/admin/distribution-history/restore/route.ts +39 -0
  7. package/dist/template/app/api/admin/distribution-history/route.test.ts +55 -0
  8. package/dist/template/app/api/admin/distribution-history/route.ts +24 -0
  9. package/dist/template/app/api/admin/updates/[encodedKey]/deactivate/route.ts +2 -1
  10. package/dist/template/app/api/admin/updates/[encodedKey]/promote/route.ts +2 -1
  11. package/dist/template/app/api/admin/updates/[encodedKey]/rollback/route.ts +2 -1
  12. package/dist/template/app/api/admin/updates/[encodedKey]/route.ts +2 -1
  13. package/dist/template/app/api/admin/updates/route.test.ts +21 -0
  14. package/dist/template/app/api/admin/updates/route.ts +12 -1
  15. package/dist/template/app/globals.css +65 -68
  16. package/dist/template/app/login/page.tsx +66 -42
  17. package/dist/template/app/updates/[encodedKey]/page.tsx +382 -248
  18. package/dist/template/app/updates/devices/page.tsx +187 -145
  19. package/dist/template/app/updates/embedded/page.tsx +80 -34
  20. package/dist/template/app/updates/emergency-redirects/page.tsx +138 -71
  21. package/dist/template/app/updates/layout.tsx +2 -1
  22. package/dist/template/app/updates/page.tsx +385 -274
  23. package/dist/template/app/updates/releases.test.tsx +156 -0
  24. package/dist/template/components/admin/admin-role.ts +5 -0
  25. package/dist/template/components/admin/admin-shell.tsx +166 -95
  26. package/dist/template/components/admin/confirm-action.tsx +123 -0
  27. package/dist/template/components/admin/language-switcher.tsx +27 -16
  28. package/dist/template/components/admin/release-badges.test.tsx +50 -0
  29. package/dist/template/components/admin/release-badges.tsx +101 -0
  30. package/dist/template/components/ui/alert.tsx +10 -3
  31. package/dist/template/components/ui/avatar.tsx +108 -0
  32. package/dist/template/components/ui/badge.tsx +2 -2
  33. package/dist/template/components/ui/breadcrumb.tsx +108 -0
  34. package/dist/template/components/ui/button.tsx +5 -5
  35. package/dist/template/components/ui/card.tsx +2 -2
  36. package/dist/template/components/ui/chart.tsx +1 -1
  37. package/dist/template/components/ui/collapsible.tsx +7 -0
  38. package/dist/template/components/ui/dialog.tsx +13 -4
  39. package/dist/template/components/ui/empty.tsx +103 -0
  40. package/dist/template/components/ui/field.tsx +248 -0
  41. package/dist/template/components/ui/input-group.tsx +170 -0
  42. package/dist/template/components/ui/input.tsx +1 -1
  43. package/dist/template/components/ui/native-select.tsx +1 -1
  44. package/dist/template/components/ui/radio-group.tsx +41 -0
  45. package/dist/template/components/ui/sheet.tsx +6 -2
  46. package/dist/template/components/ui/sidebar.tsx +62 -17
  47. package/dist/template/components/ui/status-tones.ts +15 -0
  48. package/dist/template/components/ui/table.tsx +1 -1
  49. package/dist/template/components/ui/textarea.tsx +1 -1
  50. package/dist/template/docs/admin-ui.md +22 -24
  51. package/dist/template/docs/device-targeting.md +6 -12
  52. package/dist/template/docs/doctor.md +2 -2
  53. package/dist/template/docs/expo-app-setup.md +9 -27
  54. package/dist/template/docs/getting-started.md +3 -4
  55. package/dist/template/docs/getting-started.ru.md +11 -544
  56. package/dist/template/docs/index.md +1 -1
  57. package/dist/template/docs/installation-telemetry.md +6 -12
  58. package/dist/template/docs/migrations/2026-10-16-manifest-identity.sql +5 -0
  59. package/dist/template/docs/migrations/2026-11-25-device-favorites.sql +53 -0
  60. package/dist/template/docs/migrations/2026-11-25-download-on-postpone.sql +5 -0
  61. package/dist/template/docs/migrations/2026-11-25-public-distribution-history.sql +283 -0
  62. package/dist/template/docs/migrations/schema.sql +349 -0
  63. package/dist/template/docs/npm-installer.md +3 -3
  64. package/dist/template/docs/operations-guide.md +9 -7
  65. package/dist/template/docs/ota-client-lifecycle.md +30 -68
  66. package/dist/template/docs/ota-emergency-recovery.md +34 -57
  67. package/dist/template/docs/ota-update-policy.md +9 -20
  68. package/dist/template/docs/ru/admin-ui.md +33 -0
  69. package/dist/template/docs/ru/device-targeting.md +59 -0
  70. package/dist/template/docs/ru/doctor.md +98 -0
  71. package/dist/template/docs/ru/expo-app-setup.md +497 -0
  72. package/dist/template/docs/ru/getting-started.md +391 -0
  73. package/dist/template/docs/ru/index.md +50 -0
  74. package/dist/template/docs/ru/installation-telemetry.md +125 -0
  75. package/dist/template/docs/ru/npm-installer.md +71 -0
  76. package/dist/template/docs/ru/operations-guide.md +322 -0
  77. package/dist/template/docs/ru/ota-client-lifecycle.md +162 -0
  78. package/dist/template/docs/ru/ota-emergency-recovery.md +108 -0
  79. package/dist/template/docs/ru/ota-update-policy.md +69 -0
  80. package/dist/template/docs/ru/publishing-npm-installer.md +49 -0
  81. package/dist/template/docs/ru/supabase-setup.md +120 -0
  82. package/dist/template/docs/uk/admin-ui.md +33 -0
  83. package/dist/template/docs/uk/device-targeting.md +59 -0
  84. package/dist/template/docs/uk/doctor.md +98 -0
  85. package/dist/template/docs/uk/expo-app-setup.md +497 -0
  86. package/dist/template/docs/uk/getting-started.md +391 -0
  87. package/dist/template/docs/uk/index.md +50 -0
  88. package/dist/template/docs/uk/installation-telemetry.md +125 -0
  89. package/dist/template/docs/uk/npm-installer.md +71 -0
  90. package/dist/template/docs/uk/operations-guide.md +322 -0
  91. package/dist/template/docs/uk/ota-client-lifecycle.md +162 -0
  92. package/dist/template/docs/uk/ota-emergency-recovery.md +108 -0
  93. package/dist/template/docs/uk/ota-update-policy.md +69 -0
  94. package/dist/template/docs/uk/publishing-npm-installer.md +49 -0
  95. package/dist/template/docs/uk/supabase-setup.md +120 -0
  96. package/dist/template/lib/audience-ids.ts +4 -0
  97. package/dist/template/package-lock.json +46 -0
  98. package/dist/template/package.json +4 -1
  99. package/dist/template/scripts/configure-expo-app.mjs +3 -3
  100. package/dist/template/scripts/create-access-token.mjs +1 -1
  101. package/dist/template/scripts/lib/doctor.mjs +10 -7
  102. package/dist/template/scripts/lib/doctor.test.mjs +7 -5
  103. package/dist/template/scripts/lib/embedded-update-registrar.test.ts +22 -7
  104. package/dist/template/scripts/lib/expo-app-configurator.mjs +25 -22
  105. package/dist/template/scripts/lib/expo-app-configurator.test.ts +37 -2
  106. package/dist/template/scripts/lib/ota-client-configurator.mjs +152 -55
  107. package/dist/template/scripts/lib/ota-client-configurator.test.ts +60 -20
  108. package/dist/template/scripts/lib/ota-client-package.mjs +25 -0
  109. package/dist/template/scripts/lib/ota-root-hook-patcher.mjs +90 -32
  110. package/dist/template/scripts/lib/ota-root-hook-patcher.test.ts +49 -6
  111. package/dist/template/scripts/tests/device-analytics-migrations.mjs +12 -1
  112. package/dist/template/scripts/tests/device-targeting-activation.mjs +2 -3
  113. package/dist/template/scripts/tests/e2e/client-lifecycle.mjs +161 -0
  114. package/dist/template/scripts/tests/e2e/client-lifecycle.scenario.jsx +465 -0
  115. package/dist/template/scripts/tests/e2e/client-vitest.mts +18 -0
  116. package/dist/template/scripts/tests/e2e/console.mjs +86 -0
  117. package/dist/template/scripts/tests/e2e/delivery.mjs +296 -0
  118. package/dist/template/scripts/tests/e2e/device-favorites.mjs +309 -0
  119. package/dist/template/scripts/tests/e2e/installations.mjs +132 -0
  120. package/dist/template/scripts/tests/e2e/policy.mjs +253 -0
  121. package/dist/template/scripts/tests/e2e/registrar-token.mjs +59 -0
  122. package/dist/template/scripts/tests/e2e/release-matrix.mjs +307 -0
  123. package/dist/template/scripts/tests/e2e/releases.mjs +162 -0
  124. package/dist/template/scripts/tests/e2e/run.mjs +224 -0
  125. package/dist/template/scripts/tests/manifest-identity.sql +7 -5
  126. package/dist/template/scripts/tests/public-distribution-history.mjs +102 -0
  127. package/dist/template/src/client/admin-api.ts +45 -10
  128. package/dist/template/src/client/admin-types.ts +35 -1
  129. package/dist/template/src/client/devices/analytics.tsx +169 -219
  130. package/dist/template/src/client/devices/cohorts.tsx +181 -0
  131. package/dist/template/src/client/devices/device-name.tsx +37 -21
  132. package/dist/template/src/client/devices/favorite-targets.tsx +381 -0
  133. package/dist/template/src/client/devices/registry.tsx +265 -233
  134. package/dist/template/src/client/devices/use-devices-report.test.tsx +98 -0
  135. package/dist/template/src/client/devices/use-devices-report.ts +53 -82
  136. package/dist/template/src/client/devices/version-adoption-chart.tsx +48 -38
  137. package/dist/template/src/client/distribution-control.tsx +98 -53
  138. package/dist/template/src/client/distribution-history.tsx +353 -0
  139. package/dist/template/src/client/guard-action-catalog.tsx +183 -0
  140. package/dist/template/src/client/guard-action-combobox.test.ts +16 -22
  141. package/dist/template/src/client/guard-action-combobox.tsx +134 -234
  142. package/dist/template/src/client/guard-action-options.ts +4 -6
  143. package/dist/template/src/client/i18n/en.json +335 -2
  144. package/dist/template/src/client/i18n/language-switching.test.tsx +233 -0
  145. package/dist/template/src/client/i18n/messages.test.ts +102 -19
  146. package/dist/template/src/client/i18n/messages.ts +31 -16
  147. package/dist/template/src/client/i18n/provider.tsx +6 -3
  148. package/dist/template/src/client/i18n/ru.json +619 -0
  149. package/dist/template/src/client/i18n/uk.json +619 -0
  150. package/dist/template/src/client/i18n/use-formatters.ts +5 -0
  151. package/dist/template/src/client/logout-button.tsx +3 -3
  152. package/dist/template/src/client/policy-draft.ts +138 -0
  153. package/dist/template/src/client/update-audience-editor.tsx +597 -199
  154. package/dist/template/src/client/update-policy-editor.test.ts +101 -29
  155. package/dist/template/src/client/update-policy-editor.tsx +466 -307
  156. package/dist/template/src/client/use-filtered-results.ts +55 -0
  157. package/dist/template/src/server/controllers/manifest.test.ts +23 -3
  158. package/dist/template/src/server/controllers/manifest.ts +15 -1
  159. package/dist/template/src/server/devices/audience.ts +9 -5
  160. package/dist/template/src/server/lib/admin-audience-activation.test.ts +37 -90
  161. package/dist/template/src/server/lib/admin-release-history.test.ts +138 -0
  162. package/dist/template/src/server/lib/admin-updates.ts +160 -534
  163. package/dist/template/src/server/lib/distribution-history.ts +97 -0
  164. package/dist/template/src/server/lib/supabase.js +24 -0
  165. package/dist/template/src/server/lib/supabase.test.ts +38 -1
  166. package/dist/template/src/server/lib/update-policy.test.ts +20 -0
  167. package/dist/template/src/server/lib/update-policy.ts +23 -10
  168. package/dist/template/src/server/manifest/manifest-repository.ts +11 -3
  169. package/dist/template/src/server/manifest/manifest-values.test.ts +2 -0
  170. package/dist/template/src/server/manifest/manifest-values.ts +21 -13
  171. package/dist/template/templates/expo-app/scripts/ota-publish/api/database-client.mjs +7 -30
  172. package/dist/template/templates/expo-app/scripts/ota-register-embedded/index.mjs +2 -1
  173. package/dist/template/tsconfig.json +2 -2
  174. package/dist/template-manifest.json +571 -271
  175. package/package.json +1 -1
  176. package/dist/template/scripts/lib/device-identity.test.ts +0 -29
  177. package/dist/template/scripts/lib/ota-client.test.ts +0 -55
  178. package/dist/template/scripts/lib/ota-update-controller.test.ts +0 -232
  179. package/dist/template/scripts/lib/ota-updates-ui.test.tsx +0 -154
  180. package/dist/template/scripts/tests/ota-client-types.mjs +0 -69
  181. package/dist/template/templates/expo-app/ota-client/README.md +0 -73
  182. package/dist/template/templates/expo-app/ota-client/controller.ts +0 -107
  183. package/dist/template/templates/expo-app/ota-client/device-identity.ts +0 -48
  184. package/dist/template/templates/expo-app/ota-client/docs/update-lifecycle.md +0 -61
  185. package/dist/template/templates/expo-app/ota-client/index.ts +0 -16
  186. package/dist/template/templates/expo-app/ota-client/model/hooks/useOtaUpdates.ts +0 -97
  187. package/dist/template/templates/expo-app/ota-client/model/update-controller.ts +0 -293
  188. package/dist/template/templates/expo-app/ota-client/runtime.ts +0 -153
  189. package/dist/template/templates/expo-app/ota-client/types.ts +0 -85
  190. package/dist/template/templates/expo-app/ota-client/ui/ota-update-gate.tsx +0 -25
  191. package/dist/template/templates/expo-app/ota-client/ui/ota-updates.tsx +0 -196
@@ -0,0 +1,55 @@
1
+ "use client";
2
+
3
+ import { useCallback, useEffect, useRef, useState } from "react";
4
+
5
+ // Cancel as soon as input changes, including while a text search is waiting
6
+ // for its debounce. Keep the last successful result and its matching query.
7
+ export function useFilteredResults<Q, R>(
8
+ initial: Q,
9
+ load: (query: Q, signal: AbortSignal) => Promise<R>,
10
+ ) {
11
+ const [query, setQuery] = useState(initial);
12
+ const [success, setSuccess] = useState<{ query: Q; data: R } | null>(null);
13
+ const [loading, setLoading] = useState(true);
14
+ const [error, setError] = useState("");
15
+ const current = useRef<AbortController | null>(null);
16
+ const timer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);
17
+
18
+ const cancel = useCallback(() => {
19
+ clearTimeout(timer.current);
20
+ current.current?.abort();
21
+ }, []);
22
+
23
+ const start = useCallback(
24
+ async (next: Q) => {
25
+ const controller = new AbortController();
26
+ current.current = controller;
27
+ try {
28
+ const data = await load(next, controller.signal);
29
+ if (!controller.signal.aborted) setSuccess({ query: next, data });
30
+ } catch (cause) {
31
+ if (!controller.signal.aborted)
32
+ setError(cause instanceof Error ? cause.message : String(cause));
33
+ } finally {
34
+ if (!controller.signal.aborted) setLoading(false);
35
+ }
36
+ },
37
+ [load],
38
+ );
39
+
40
+ useEffect(() => {
41
+ void start(initial);
42
+ return cancel;
43
+ }, [cancel, initial, start]);
44
+
45
+ function request(next: Q, delayText = false) {
46
+ cancel();
47
+ setQuery(next);
48
+ setError("");
49
+ setLoading(true);
50
+ if (delayText) timer.current = setTimeout(() => void start(next), 300);
51
+ else void start(next);
52
+ }
53
+
54
+ return { query, success, loading, error, request };
55
+ }
@@ -1,4 +1,5 @@
1
- import { beforeEach, describe, expect, it, vi } from "vitest";
1
+ import { generateKeyPairSync } from "node:crypto";
2
+ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
2
3
  import { NextRequest } from "next/server";
3
4
  import { createServedManifestId } from "../manifest/manifest-identity";
4
5
 
@@ -196,6 +197,7 @@ function seedCurrentUpdate() {
196
197
  }
197
198
 
198
199
  describe("GET /api/manifest", () => {
200
+ afterEach(() => vi.unstubAllEnvs());
199
201
  beforeEach(() => {
200
202
  vi.resetModules();
201
203
  database.channels = [];
@@ -366,8 +368,9 @@ describe("GET /api/manifest", () => {
366
368
  it("returns signed noUpdateAvailable before redirect or update selection when globally blocked", async () => {
367
369
  distributionControl.blocked = true;
368
370
  vi.stubEnv(
369
- "CODE_SIGNING_PRIVATE_KEY_PATH",
370
- `${process.cwd()}/src/server/cert/codeSigningPrivateKey.pem`,
371
+ "CODE_SIGNING_PRIVATE_KEY",
372
+ generateKeyPairSync("rsa", { modulusLength: 2048 }).privateKey
373
+ .export({ type: "pkcs8", format: "pem" }).toString(),
371
374
  );
372
375
  database.emergencyRedirects.push({
373
376
  id: "redirect-id",
@@ -1042,6 +1045,23 @@ describe("GET /api/manifest", () => {
1042
1045
  expect(body).toContain(createServedManifestId(servedManifestId, previousUpdateId));
1043
1046
  });
1044
1047
 
1048
+ it.each([
1049
+ ["a still-active OTA", { is_active: true }],
1050
+ ["a disabled OTA on another channel", { channel: "beta" }],
1051
+ ["a disabled OTA on another runtime", { runtime_version: "2.0.0" }],
1052
+ ])("preserves the installed version floor for %s", async (_label, overrides) => {
1053
+ seedCurrentUpdate();
1054
+ database.updates.push(makeUpdate({
1055
+ update_id: previousUpdateId,
1056
+ is_active: false,
1057
+ created_at: "2026-08-29T08:00:00Z",
1058
+ manifest: { expoClient: { version: "3.0.0" } },
1059
+ ...overrides,
1060
+ }));
1061
+ const response = await requestManifest(makeRequest({ "expo-current-update-id": previousUpdateId }));
1062
+ expect(await response.text()).toContain('{"type":"noUpdateAvailable"}');
1063
+ });
1064
+
1045
1065
  it("does not grant rollback downgrade privileges to a device outside its audience", async () => {
1046
1066
  seedCurrentUpdate();
1047
1067
  database.channels[0].active_update_id = previousUpdateId;
@@ -302,8 +302,21 @@ const manifestController = async (req: NextRequest) => {
302
302
  )
303
303
  : null;
304
304
  const embeddedVersionBlocks = embeddedAppVersionComparison === 1;
305
+ // A disabled, previously installed OTA can return to an older eligible
306
+ // release in its own scope. An embedded floor and a rollback targeting
307
+ // somebody else still take precedence.
308
+ const recoveringDisabledOta =
309
+ !rollbackUpdateId &&
310
+ currentInstalledUpdateMeta?.ota?.is_active === false &&
311
+ currentInstalledUpdateMeta.ota.runtime_version === runtimeVersion &&
312
+ currentInstalledUpdateMeta.platform === platform &&
313
+ currentInstalledUpdateMeta.channel === channel &&
314
+ isSameOrNewerDate(
315
+ normalizeExpoManifestDate(currentInstalledUpdateMeta.created_at),
316
+ selectedCreatedAt,
317
+ );
305
318
  const currentInstalledVersionBlocks =
306
- currentInstalledAppVersionComparison === 1;
319
+ !recoveringDisabledOta && currentInstalledAppVersionComparison === 1;
307
320
 
308
321
  const embeddedTimestampBlocks = Boolean(
309
322
  embeddedUpdateMeta &&
@@ -317,6 +330,7 @@ const manifestController = async (req: NextRequest) => {
317
330
  ),
318
331
  );
319
332
  const currentInstalledTimestampBlocks = Boolean(
333
+ !recoveringDisabledOta &&
320
334
  currentInstalledUpdateMeta &&
321
335
  currentInstalledUpdateMeta.platform === platform &&
322
336
  currentInstalledUpdateMeta.channel === channel &&
@@ -1,8 +1,11 @@
1
1
  import { parseDictionary } from "structured-headers";
2
2
 
3
- export const installationIdPattern =
4
- /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
5
- export const deviceIdPattern = /^[0-9a-f]{64}$/;
3
+ import {
4
+ deviceIdPattern,
5
+ installationIdPattern,
6
+ maxIdsPerKind,
7
+ } from "@/lib/audience-ids";
8
+ export { deviceIdPattern, installationIdPattern } from "@/lib/audience-ids";
6
9
  export type Audience = {
7
10
  audience_mode: "all" | "devices";
8
11
  audience_installation_ids: string[];
@@ -47,7 +50,8 @@ export function eligibleForAudience(
47
50
  return Boolean(
48
51
  (identity.installationId &&
49
52
  row.audience_installation_ids?.includes(identity.installationId)) ||
50
- (identity.deviceId && row.audience_device_ids?.includes(identity.deviceId)),
53
+ (identity.deviceId &&
54
+ row.audience_device_ids?.includes(identity.deviceId)),
51
55
  );
52
56
  }
53
57
 
@@ -58,7 +62,7 @@ export function parseAudience(value: unknown): Audience {
58
62
  const list = v[key];
59
63
  if (
60
64
  !Array.isArray(list) ||
61
- list.length > 100 ||
65
+ list.length > maxIdsPerKind ||
62
66
  list.some((id) => typeof id !== "string" || !pattern.test(id))
63
67
  )
64
68
  throw new Error("Invalid target IDs (maximum 100 per type)");
@@ -1,94 +1,41 @@
1
- import { beforeEach, expect, it, vi } from 'vitest';
2
- type Row = Record<string, unknown>;
3
- const db = vi.hoisted(() => ({ updates: [] as Row[], channels: [] as Row[], blocked: false }));
4
- vi.mock('./distribution-control', () => ({ assertOtaDistributionAllowed: async () => undefined }));
5
- vi.mock('./supabase.js', () => {
6
- class Query {
7
- filters: Array<(r: Row) => boolean> = [];
8
- patch: Row | null = null;
9
- limitCount = Infinity;
10
- upsertRow: Row | null = null;
11
- orderFields: string[] = [];
12
- constructor(private table: string) {}
13
- select() { return this; }
14
- eq(k: string, v: unknown) { this.filters.push(r => r[k] === v); return this; }
15
- neq(k: string, v: unknown) { this.filters.push(r => r[k] !== v); return this; }
16
- not(k: string, op: string, v: unknown) { void op; this.filters.push(r => r[k] !== v); return this; }
17
- order(k: string) { this.orderFields.push(k); return this; }
18
- limit(n: number) { this.limitCount = n; return this; }
19
- update(p: Row) { this.patch = p; return this; }
20
- upsert(p: Row) { this.upsertRow = p; return this; }
21
- async execute() {
22
- const rows = this.table === 'ota_updates' ? db.updates : db.channels;
23
- if (this.upsertRow) {
24
- if (this.table === 'ota_update_channels' && db.blocked) return { data: [], error: { message: 'OTA_DISTRIBUTION_BLOCKED: INSERT guard runs before ON CONFLICT' } };
25
- const row = rows.find(r => r.runtime_version === this.upsertRow!.runtime_version && r.channel === this.upsertRow!.channel && r.platform === this.upsertRow!.platform);
26
- if (row) Object.assign(row, this.upsertRow); else rows.push(this.upsertRow);
27
- return { data: [row || this.upsertRow], error: null };
28
- }
29
- let found = rows.filter(r => this.filters.every(f => f(r)));
30
- if (this.orderFields.length) found = found.sort((a, b) => {
31
- for (const field of this.orderFields) {
32
- const compared = String(b[field]).localeCompare(String(a[field]));
33
- if (compared) return compared;
34
- }
35
- return 0;
36
- });
37
- found = found.slice(0, this.limitCount);
38
- if (this.patch) found.forEach(r => {
39
- // Mirror the activation trigger here; its atomic/concurrent behavior is
40
- // exercised against PostgreSQL by device-targeting-activation.mjs.
41
- if (this.table === 'ota_updates' && this.patch!.is_active === true && r.audience_mode === 'all') {
42
- rows.filter(other => other !== r && other.runtime_version === r.runtime_version && other.channel === r.channel && other.platform === r.platform)
43
- .forEach(other => Object.assign(other, { is_active: false, disabled_at: 'now' }));
44
- }
45
- Object.assign(r, this.patch);
46
- });
47
- return { data: found, error: null };
48
- }
49
- async maybeSingle() { const r = await this.execute(); return { ...r, data: r.data[0] || null }; }
50
- single() { return this.maybeSingle(); }
51
- then(resolve: (r: unknown) => unknown, reject: (e: unknown) => unknown) { return this.execute().then(resolve, reject); }
52
- }
53
- return { supabase: { from: (table: string) => new Query(table) }, jsonb: (v: unknown) => v, SUPABASE_BUCKET: 'test' };
54
- });
55
- import { setUpdateDisabledByKey, promoteLatestByKey, rollbackToUpdateByKey } from './admin-updates';
56
- const older = '11111111-1111-4111-8111-111111111111', newer = '22222222-2222-4222-8222-222222222222';
57
- const scope = { runtime_version: 'r1', channel: 'test', platform: 'android' };
58
- beforeEach(() => {
59
- db.blocked = false;
60
- db.updates = [
61
- { ...scope, update_id: older, created_at: '2026-10-20', created_at_path: 'old', is_active: true, audience_mode: 'all' },
62
- { ...scope, update_id: newer, created_at: '2026-10-21', created_at_path: 'new', is_active: false, audience_mode: 'devices' },
63
- ];
64
- db.channels = [{ ...scope, latest_update_id: newer, active_update_id: null, latest_created_at: '2026-10-21' }];
65
- });
66
- it('preserves public fallback on targeted activation and removes it on normal public activation', async () => {
67
- await setUpdateDisabledByKey(newer, false);
68
- expect(db.updates.map(r => r.is_active)).toEqual([true, true]);
69
- db.updates[1].audience_mode = 'all';
70
- await setUpdateDisabledByKey(newer, false);
71
- expect(db.updates.map(r => r.is_active)).toEqual([false, true]);
72
- });
73
- it('promotes targeted latest out of rollback without disabling the public fallback', async () => {
74
- db.channels[0].active_update_id = older;
75
- await promoteLatestByKey(newer);
76
- expect(db.updates.map(r => r.is_active)).toEqual([true, true]);
77
- expect(db.channels[0].active_update_id).toBeNull();
1
+ import { beforeEach, expect, it, vi } from "vitest";
2
+
3
+ const rpc = vi.hoisted(() => vi.fn());
4
+ vi.mock("./supabase.js", () => ({ supabase: { rpc } }));
5
+ vi.mock("./distribution-control", async (importOriginal) => ({
6
+ ...(await importOriginal<typeof import("./distribution-control")>()),
7
+ assertOtaDistributionAllowed: async () => undefined,
8
+ }));
9
+
10
+ import { setUpdateDisabledByKey, promoteLatestByKey, rollbackToUpdateByKey } from "./admin-updates";
11
+ import { changeDistribution, DistributionHistoryConflictError } from "./distribution-history";
12
+ import { OtaDistributionBlockedError } from "./distribution-control";
13
+
14
+ const id = "11111111-1111-4111-8111-111111111111";
15
+ beforeEach(() => rpc.mockReset());
16
+
17
+ it.each([
18
+ ["activate", () => setUpdateDisabledByKey(id, false)],
19
+ ["stop", () => setUpdateDisabledByKey(id, true)],
20
+ ["promote", () => promoteLatestByKey(id)],
21
+ ["rollback", () => rollbackToUpdateByKey(id)],
22
+ ])("submits %s as one transactional operation", async (action, mutate) => {
23
+ rpc.mockResolvedValue({ data: [{ result: { updated: true } }] });
24
+ await expect(mutate()).resolves.toMatchObject({ updated: true });
25
+ expect(rpc).toHaveBeenCalledExactlyOnceWith("ota_change_distribution", {
26
+ p_update: id, p_action: action, p_revision: null,
27
+ });
78
28
  });
79
- it('keeps other audiences live when rolling back selected devices', async () => {
80
- Object.assign(db.updates[0], { audience_mode: 'devices', is_active: false });
81
- Object.assign(db.updates[1], { audience_mode: 'all', is_active: true });
82
- await rollbackToUpdateByKey(older);
83
- expect(db.updates.map(r => r.is_active)).toEqual([true, true]);
84
- expect(db.channels[0].active_update_id).toBe(older);
29
+
30
+ it("requires the observed revision for history restore and maps a stale target to a conflict", async () => {
31
+ rpc.mockResolvedValue({ error: { message: "DISTRIBUTION_CONFLICT: refresh" } });
32
+ await expect(changeDistribution(id, "restore", "17")).rejects.toBeInstanceOf(DistributionHistoryConflictError);
33
+ expect(rpc).toHaveBeenCalledExactlyOnceWith("ota_change_distribution", {
34
+ p_update: id, p_action: "restore", p_revision: "17",
35
+ });
85
36
  });
86
37
 
87
- it('repairs an existing channel with UPDATE when deactivating under the global stop', async () => {
88
- db.updates[1].is_active = true;
89
- db.blocked = true;
90
- const result = await setUpdateDisabledByKey(newer, true);
91
- expect(db.updates.map(r => r.is_active)).toEqual([true, false]);
92
- expect(result.disabled).toBe(true);
93
- expect(db.channels[0].latest_update_id).toBe(older);
38
+ it("maps a concurrent emergency stop to the same blocked response as the initial check", async () => {
39
+ rpc.mockResolvedValue({ error: { message: "OTA_DISTRIBUTION_BLOCKED: restore" } });
40
+ await expect(changeDistribution(id, "restore", "17")).rejects.toBeInstanceOf(OtaDistributionBlockedError);
94
41
  });
@@ -0,0 +1,138 @@
1
+ import { describe, expect, it, vi } from "vitest";
2
+ import { getUpdatesPage } from "./admin-updates";
3
+
4
+ const database = vi.hoisted(() => ({
5
+ ota_updates: [] as Array<Record<string, unknown>>,
6
+ ota_update_channels: [] as Array<Record<string, unknown>>,
7
+ }));
8
+ vi.mock("./supabase.js", () => ({
9
+ supabase: {
10
+ from(table: keyof typeof database) {
11
+ let cursor: string | number = "";
12
+ const builder = {
13
+ select: () => builder,
14
+ order: () => builder,
15
+ limit: () => builder,
16
+ gt(_key: string, after: string | number) {
17
+ cursor = after;
18
+ return builder;
19
+ },
20
+ async execute() {
21
+ // Simulate a PostgREST row cap below the requested batch size.
22
+ const data = database[table]
23
+ .filter((row) => String(row.id) > String(cursor))
24
+ .slice(0, 2);
25
+ return { data, error: null };
26
+ },
27
+ };
28
+ return builder;
29
+ },
30
+ },
31
+ }));
32
+
33
+ const defaults = {
34
+ page: 1,
35
+ pageSize: 1,
36
+ sortBy: "createdAt",
37
+ order: "desc",
38
+ } as const;
39
+ function release(n: number, options: Record<string, unknown> = {}) {
40
+ return {
41
+ id: String(n),
42
+ update_id: `22222222-2222-4222-8222-22222222222${n}`,
43
+ is_active: true,
44
+ comment: `Release ${n}`,
45
+ runtime_version: "1.0",
46
+ channel: "main",
47
+ platform: "android",
48
+ app_version: " 2.0 ",
49
+ legacy_version: null,
50
+ created_at: `2026-03-0${n}T00:00:00Z`,
51
+ audience_mode: "all",
52
+ storage_base_path: "test",
53
+ ...options,
54
+ };
55
+ }
56
+
57
+ describe("release history", () => {
58
+ it("combines full-history search, filters and complete channel pointers before paging", async () => {
59
+ database.ota_updates = [
60
+ release(1),
61
+ release(2),
62
+ release(3, { channel: "old" }),
63
+ release(4, {
64
+ channel: "preview",
65
+ platform: "ios",
66
+ audience_mode: "devices",
67
+ runtime_version: "2.1",
68
+ app_version: null,
69
+ legacy_version: " 4.2 ",
70
+ }),
71
+ release(5, {
72
+ channel: "preview",
73
+ platform: "ios",
74
+ audience_mode: "devices",
75
+ runtime_version: "2.1",
76
+ app_version: "4.2",
77
+ is_active: false,
78
+ }),
79
+ ];
80
+ database.ota_update_channels = [
81
+ { id: 1, channel: "main", runtime_version: "1.0", platform: "android" },
82
+ { id: 2, channel: "old", runtime_version: "1.0", platform: "android" },
83
+ {
84
+ id: 3,
85
+ channel: "preview",
86
+ runtime_version: "2.1",
87
+ platform: "ios",
88
+ active_update_id: database.ota_updates[3].update_id,
89
+ latest_update_id: database.ota_updates[4].update_id,
90
+ },
91
+ ];
92
+
93
+ const filters = {
94
+ q: " 4.2 ",
95
+ platform: "ios",
96
+ channel: "preview",
97
+ audience: "devices",
98
+ runtime: "2.1",
99
+ };
100
+ const page = await getUpdatesPage({ ...defaults, ...filters, page: 99 });
101
+ expect(page).toMatchObject({
102
+ total: 2,
103
+ totalPages: 2,
104
+ page: 2,
105
+ items: [
106
+ { comment: "Release 4", isRollbackActive: true, appVersion: "4.2" },
107
+ ],
108
+ filters: {
109
+ channels: ["main", "old", "preview"],
110
+ runtimes: ["1.0", "2.1"],
111
+ },
112
+ });
113
+ expect(page.rollbackLockByScope.at(-1)).toMatchObject({
114
+ channel: "preview",
115
+ rollbackActive: true,
116
+ });
117
+ const draft = await getUpdatesPage({
118
+ ...defaults,
119
+ ...filters,
120
+ q: "RELEASE",
121
+ status: "draft",
122
+ });
123
+ expect(draft.items.map((item) => item.comment)).toEqual(["Release 5"]);
124
+ const disabled = await getUpdatesPage({
125
+ ...defaults,
126
+ ...filters,
127
+ status: "disabled",
128
+ });
129
+ expect(disabled.total).toBe(0);
130
+ const rollback = await getUpdatesPage({
131
+ ...defaults,
132
+ ...filters,
133
+ q: "222222222224",
134
+ status: "rollback",
135
+ });
136
+ expect(rollback.total).toBe(1);
137
+ });
138
+ });