Open History to see the last commit
1#!/usr/bin/env node
2// @effect-diagnostics nodeBuiltinImport:off globalTimers:off globalDate:off - Host-side simulator and emulator automation uses Node subprocess and timing APIs directly.
3
4import * as NodeChildProcess from "node:child_process";
5import * as NodeFSP from "node:fs/promises";
6import * as NodeNet from "node:net";
7import * as NodeOS from "node:os";
8import * as NodePath from "node:path";
9import * as NodeProcess from "node:process";
10import * as NodeURL from "node:url";
11
12import { PNG } from "pngjs";
13
14import showcaseConfig, {
15 type ShowcaseAppearance,
16 type ShowcaseAndroidDevice,
17 type ShowcaseConfig,
18 type ShowcaseDevice,
19 type ShowcaseIosDevice,
20 type ShowcaseStoreAssetSpec,
21 SHOWCASE_SCENES,
22 type ShowcaseScene,
23} from "./mobile-showcase.config.ts";
24import {
25 SHOWCASE_ENVIRONMENTS,
26 SHOWCASE_PROJECTS,
27 SHOWCASE_TERMINAL_ID,
28 SHOWCASE_THREAD_ID,
29 seedShowcaseEnvironment,
30} from "./mobile-showcase-environment.ts";
31
32const REPO_ROOT = NodePath.resolve(NodePath.dirname(NodeURL.fileURLToPath(import.meta.url)), "..");
33const MOBILE_ROOT = NodePath.join(REPO_ROOT, "apps/mobile");
34const ANDROID_PACKAGE = "com.t3tools.t3code.dev";
35const APP_SCHEME = "t3code-dev";
36const IOS_READY_FILENAME = "T3ShowcaseReadyScene";
37const SERVER_HOST = "0.0.0.0";
38const IOS_SIMULATOR_ARCH = NodeProcess.arch === "arm64" ? "arm64" : "x86_64";
39const IOS_APP_PATH = NodePath.join(
40 MOBILE_ROOT,
41 ".showcase/ios-derived-data/Build/Products/Debug-iphonesimulator/T3CodeDev.app",
42);
43const ANDROID_APK_PATH = NodePath.join(
44 MOBILE_ROOT,
45 "android/app/build/outputs/apk/debug/app-debug.apk",
46);
47export function resolveAndroidSdkRoot(
48 environment: Readonly<Record<string, string | undefined>>,
49 platform: NodeJS.Platform = NodeProcess.platform,
50): string {
51 const configured = environment.ANDROID_HOME ?? environment.ANDROID_SDK_ROOT;
52 if (configured) return configured;
53 const home = environment.HOME ?? environment.USERPROFILE ?? "";
54 return NodePath.join(home, platform === "darwin" ? "Library/Android/sdk" : "Android/Sdk");
55}
56
57const ANDROID_SDK_ROOT = resolveAndroidSdkRoot(NodeProcess.env);
58const MOBILE_BUILD_ENV = {
59 ...NodeProcess.env,
60 ANDROID_HOME: ANDROID_SDK_ROOT,
61 APP_VARIANT: "development",
62 EXPO_NO_GIT_STATUS: "1",
63 JAVA_HOME:
64 NodeProcess.env.JAVA_HOME ??
65 (NodeProcess.platform === "darwin"
66 ? "/Applications/Android Studio.app/Contents/jbr/Contents/Home"
67 : undefined),
68 NODE_ENV: "development",
69};
70
71interface CliOptions {
72 readonly platforms: ReadonlySet<ShowcaseDevice["platform"]>;
73 readonly deviceIds: ReadonlySet<string>;
74 readonly scenes: ReadonlySet<ShowcaseScene>;
75 readonly appearances: ReadonlySet<ShowcaseAppearance>;
76 readonly skipBuild: boolean;
77 readonly skipMetro: boolean;
78 readonly keepRunning: boolean;
79 readonly validateOnly: boolean;
80 readonly list: boolean;
81}
82
83export interface ShowcaseCapture {
84 readonly device: ShowcaseDevice;
85 readonly scenes: ReadonlyArray<ShowcaseScene>;
86 readonly appearance: ShowcaseAppearance;
87}
88
89interface IosCaptureCleanup {
90 readonly udid: string;
91 readonly startedByRunner: boolean;
92 readonly createdByRunner: boolean;
93}
94
95interface AndroidCaptureCleanup {
96 readonly device: ShowcaseAndroidDevice;
97 readonly serial: string;
98 readonly startedByRunner: boolean;
99}
100
101interface NetworkAddress {
102 readonly address: string;
103 readonly family: string;
104 readonly internal: boolean;
105}
106
107export function selectLanIpv4Address(addresses: ReadonlyArray<NetworkAddress>): string | null {
108 return (
109 addresses.find(
110 ({ address, family, internal }) =>
111 family === "IPv4" && !internal && !address.startsWith("169.254."),
112 )?.address ?? null
113 );
114}
115
116function lanIpv4Address(): string {
117 const address = selectLanIpv4Address(
118 Object.values(NodeOS.networkInterfaces()).flatMap((addresses) => addresses ?? []),
119 );
120 if (!address) {
121 throw new Error("No LAN IPv4 address is available for the iOS Simulator to reach Metro.");
122 }
123 return address;
124}
125
126export interface PngMetadata {
127 readonly width: number;
128 readonly height: number;
129 readonly bitDepth: number;
130 readonly colorType: number;
131 readonly hasAlpha: boolean;
132}
133
134export function readPngMetadata(bytes: Uint8Array): PngMetadata {
135 const pngSignature = [137, 80, 78, 71, 13, 10, 26, 10];
136 if (bytes.byteLength < 26 || !pngSignature.every((value, index) => bytes[index] === value)) {
137 throw new Error("Captured file is not a valid PNG.");
138 }
139 const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
140 const colorType = view.getUint8(25);
141 return {
142 width: view.getUint32(16),
143 height: view.getUint32(20),
144 bitDepth: view.getUint8(24),
145 colorType,
146 hasAlpha: colorType === 4 || colorType === 6,
147 };
148}
149
150export function readPngDimensions(bytes: Uint8Array): {
151 readonly width: number;
152 readonly height: number;
153} {
154 const { width, height } = readPngMetadata(bytes);
155 return { width, height };
156}
157
158export function normalizeStorePng(bytes: Uint8Array): Buffer {
159 const png = PNG.sync.read(Buffer.from(bytes));
160 return PNG.sync.write(png, {
161 bitDepth: 8,
162 colorType: 2,
163 inputColorType: 6,
164 inputHasAlpha: true,
165 });
166}
167
168export function validateStoreAsset(
169 spec: ShowcaseStoreAssetSpec,
170 bytes: Uint8Array,
171 label = "Screenshot",
172): PngMetadata {
173 const metadata = readPngMetadata(bytes);
174 if (metadata.width !== spec.width || metadata.height !== spec.height) {
175 throw new Error(
176 `${label} is ${metadata.width}×${metadata.height}; ${spec.store} requires ${spec.width}×${spec.height}.`,
177 );
178 }
179 if (metadata.bitDepth !== 8 || metadata.colorType !== 2 || metadata.hasAlpha) {
180 throw new Error(
181 `${label} must be an 8-bit, 24-bit RGB PNG without alpha (found bit depth ${metadata.bitDepth}, color type ${metadata.colorType}).`,
182 );
183 }
184 if (spec.maximumFileSizeBytes && bytes.byteLength > spec.maximumFileSizeBytes) {
185 throw new Error(
186 `${label} is ${bytes.byteLength} bytes; ${spec.store} allows at most ${spec.maximumFileSizeBytes} bytes.`,
187 );
188 }
189 if (spec.store === "google-play") {
190 const shortestSide = Math.min(metadata.width, metadata.height);
191 const longestSide = Math.max(metadata.width, metadata.height);
192 if (shortestSide < 320 || longestSide > 3_840 || longestSide > shortestSide * 2) {
193 throw new Error(
194 `${label} does not meet Google Play's 320–3,840 px bounds and 2:1 maximum aspect ratio.`,
195 );
196 }
197 if (metadata.width * 16 !== metadata.height * 9) {
198 throw new Error(`${label} must use Google Play's recommended portrait 9:16 aspect ratio.`);
199 }
200 }
201 return metadata;
202}
203
204export function validateStoreAssetCount(
205 spec: ShowcaseStoreAssetSpec,
206 count: number,
207 requireMinimum: boolean,
208): void {
209 if (count > spec.maximumUploadCount) {
210 throw new Error(
211 `${spec.directory} contains ${count} screenshots; ${spec.store} allows at most ${spec.maximumUploadCount}.`,
212 );
213 }
214 if (requireMinimum && count < spec.minimumUploadCount) {
215 throw new Error(
216 `${spec.directory} contains ${count} screenshots; ${spec.store} requires at least ${spec.minimumUploadCount}.`,
217 );
218 }
219}
220
221export function showcaseCaptureDirectory(
222 outputDirectory: string,
223 capture: Pick<ShowcaseCapture, "device" | "appearance">,
224): string {
225 return NodePath.join(outputDirectory, capture.device.storeAsset.directory, capture.appearance);
226}
227
228async function finalizeCapture(destination: string, device: ShowcaseDevice): Promise<void> {
229 const normalized = normalizeStorePng(await NodeFSP.readFile(destination));
230 await NodeFSP.writeFile(destination, normalized);
231 const metadata = validateStoreAsset(
232 device.storeAsset,
233 normalized,
234 NodePath.basename(destination),
235 );
236 NodeProcess.stdout.write(
237 `Captured ${NodePath.relative(REPO_ROOT, destination)} (${metadata.width}×${metadata.height}, 24-bit RGB, validated for ${device.storeAsset.store})\n`,
238 );
239}
240
241async function validateCaptureSet(
242 capture: ShowcaseCapture,
243 outputDirectory: string,
244 requireMinimum: boolean,
245): Promise<void> {
246 const directory = showcaseCaptureDirectory(outputDirectory, capture);
247 const files = (await NodeFSP.readdir(directory)).filter((file) => file.endsWith(".png")).sort();
248 const expectedFiles = capture.scenes.map((scene) => `${scene}.png`).sort();
249 const missingFiles = expectedFiles.filter((file) => !files.includes(file));
250 if (missingFiles.length > 0) {
251 throw new Error(`${capture.device.id} is missing ${missingFiles.join(", ")} in ${directory}.`);
252 }
253 validateStoreAssetCount(capture.device.storeAsset, files.length, requireMinimum);
254 for (const file of files) {
255 const bytes = await NodeFSP.readFile(NodePath.join(directory, file));
256 validateStoreAsset(capture.device.storeAsset, bytes, `${capture.device.id}/${file}`);
257 }
258 NodeProcess.stdout.write(
259 `Validated ${files.length} upload-ready ${capture.device.storeAsset.store} screenshots in ${NodePath.relative(REPO_ROOT, directory)}/\n`,
260 );
261}
262
263function argumentValue(args: ReadonlyArray<string>, index: number, flag: string): string {
264 const value = args[index + 1];
265 if (!value || value.startsWith("--")) {
266 throw new Error(`${flag} requires a value.`);
267 }
268 return value;
269}
270
271export function parseShowcaseCliArgs(args: ReadonlyArray<string>): CliOptions {
272 const platforms = new Set<ShowcaseDevice["platform"]>();
273 const deviceIds = new Set<string>();
274 const scenes = new Set<ShowcaseScene>();
275 const appearances = new Set<ShowcaseAppearance>();
276 let skipBuild = false;
277 let skipMetro = false;
278 let keepRunning = false;
279 let validateOnly = false;
280 let list = false;
281
282 for (let index = 0; index < args.length; index += 1) {
283 const argument = args[index];
284 if (argument === "--platform") {
285 const value = argumentValue(args, index, argument);
286 if (value !== "ios" && value !== "android" && value !== "all") {
287 throw new Error(`Unsupported platform '${value}'. Use ios, android, or all.`);
288 }
289 if (value === "all") {
290 platforms.add("ios");
291 platforms.add("android");
292 } else {
293 platforms.add(value);
294 }
295 index += 1;
296 } else if (argument === "--device") {
297 deviceIds.add(argumentValue(args, index, argument));
298 index += 1;
299 } else if (argument === "--scene") {
300 const value = argumentValue(args, index, argument);
301 if (!SHOWCASE_SCENES.includes(value as ShowcaseScene)) {
302 throw new Error(`Unsupported scene '${value}'. Use ${SHOWCASE_SCENES.join(", ")}.`);
303 }
304 scenes.add(value as ShowcaseScene);
305 index += 1;
306 } else if (argument === "--appearance") {
307 const value = argumentValue(args, index, argument);
308 if (value !== "light" && value !== "dark" && value !== "both") {
309 throw new Error(`Unsupported appearance '${value}'. Use light, dark, or both.`);
310 }
311 if (value === "both") {
312 appearances.add("light");
313 appearances.add("dark");
314 } else {
315 appearances.add(value);
316 }
317 index += 1;
318 } else if (argument === "--skip-build") {
319 skipBuild = true;
320 } else if (argument === "--skip-metro") {
321 skipMetro = true;
322 } else if (argument === "--keep-running") {
323 keepRunning = true;
324 } else if (argument === "--validate-only") {
325 validateOnly = true;
326 } else if (argument === "--list") {
327 list = true;
328 } else if (argument === "--help" || argument === "-h") {
329 list = true;
330 } else {
331 throw new Error(`Unknown option '${argument}'.`);
332 }
333 }
334
335 return {
336 platforms,
337 deviceIds,
338 scenes,
339 appearances,
340 skipBuild,
341 skipMetro,
342 keepRunning,
343 validateOnly,
344 list,
345 };
346}
347
348export function planShowcaseCaptures(
349 config: ShowcaseConfig,
350 options: Pick<CliOptions, "platforms" | "deviceIds" | "scenes" | "appearances">,
351): ReadonlyArray<ShowcaseCapture> {
352 const captures = config.devices
353 .filter((device) => options.platforms.size === 0 || options.platforms.has(device.platform))
354 .filter((device) => options.deviceIds.size === 0 || options.deviceIds.has(device.id))
355 .flatMap((device) => {
356 const appearances =
357 options.appearances.size === 0 ? [device.appearance] : options.appearances;
358 return [...appearances].map((appearance) => ({
359 device,
360 appearance,
361 scenes:
362 options.scenes.size === 0
363 ? device.scenes
364 : device.scenes.filter((scene) => options.scenes.has(scene)),
365 }));
366 })
367 .filter((capture) => capture.scenes.length > 0);
368
369 const knownDeviceIds = new Set(config.devices.map((device) => device.id));
370 for (const id of options.deviceIds) {
371 if (!knownDeviceIds.has(id)) {
372 throw new Error(`Unknown device '${id}'. Run with --list to see configured devices.`);
373 }
374 }
375 if (captures.length === 0) {
376 throw new Error("No captures match the selected platform, device, and scene filters.");
377 }
378 return captures;
379}
380
381function printUsage(config: ShowcaseConfig): void {
382 NodeProcess.stdout.write(`App screenshot showcase
383
384Usage:
385 pnpm --filter @t3tools/mobile screenshots [options]
386
387Options:
388 --platform ios|android|all Capture one platform (repeatable)
389 --device <id> Capture one configured device (repeatable)
390 --scene <name> Capture one scene (repeatable)
391 --appearance light|dark|both
392 Override the configured appearance
393 --skip-build Reuse the existing simulator app / debug APK
394 --skip-metro Reuse an already running showcase Metro server
395 --keep-running Leave devices and Metro running after capture
396 --validate-only Validate existing upload assets without capturing
397 --list Print this help and the configured matrix
398
399Scenes: ${SHOWCASE_SCENES.join(", ")}
400
401Configured devices:
402${config.devices
403 .map((device) => {
404 const target = device.platform === "ios" ? device.simulator : device.avd;
405 return ` ${device.id.padEnd(18)} ${device.platform.padEnd(8)} ${target} -> ${device.storeAsset.directory}/{light|dark} (${device.storeAsset.width}×${device.storeAsset.height}, default ${device.appearance}) [${device.scenes.join(", ")}]`;
406 })
407 .join("\n")}
408`);
409}
410
411function spawnProcess(
412 command: string,
413 args: ReadonlyArray<string>,
414 options: NodeChildProcess.SpawnOptions = {},
415): NodeChildProcess.ChildProcess {
416 return NodeChildProcess.spawn(command, args, {
417 cwd: REPO_ROOT,
418 env: NodeProcess.env,
419 stdio: "inherit",
420 ...options,
421 });
422}
423
424async function runCommand(
425 command: string,
426 args: ReadonlyArray<string>,
427 options: NodeChildProcess.SpawnOptions = {},
428): Promise<void> {
429 await new Promise<void>((resolve, reject) => {
430 const child = spawnProcess(command, args, options);
431 child.once("error", reject);
432 child.once("exit", (code, signal) => {
433 if (code === 0) {
434 resolve();
435 } else {
436 reject(
437 new Error(
438 `${command} ${args.join(" ")} failed ${signal ? `with signal ${signal}` : `with code ${String(code)}`}.`,
439 ),
440 );
441 }
442 });
443 });
444}
445
446async function commandOutput(
447 command: string,
448 args: ReadonlyArray<string>,
449 options: NodeChildProcess.ExecFileOptions = {},
450): Promise<string> {
451 return await new Promise<string>((resolve, reject) => {
452 NodeChildProcess.execFile(
453 command,
454 [...args],
455 { cwd: REPO_ROOT, encoding: "utf8", maxBuffer: 10 * 1024 * 1024, ...options },
456 (error, stdout) => {
457 if (error) reject(error);
458 else resolve(String(stdout));
459 },
460 );
461 });
462}
463
464function delay(milliseconds: number): Promise<void> {
465 return new Promise((resolve) => setTimeout(resolve, milliseconds));
466}
467
468async function stopProcess(child: NodeChildProcess.ChildProcess): Promise<void> {
469 if (child.exitCode !== null || child.signalCode !== null) return;
470
471 const exited = new Promise<void>((resolve) => {
472 child.once("exit", () => resolve());
473 });
474 child.kill("SIGTERM");
475 await Promise.race([exited, delay(5_000)]);
476 if (child.exitCode !== null || child.signalCode !== null) return;
477
478 child.kill("SIGKILL");
479 await Promise.race([exited, delay(1_000)]);
480}
481
482async function waitForPort(port: number, label = "Process", timeoutMs = 60_000): Promise<void> {
483 const deadline = Date.now() + timeoutMs;
484 while (Date.now() < deadline) {
485 const open = await new Promise<boolean>((resolve) => {
486 const socket = NodeNet.createConnection({ host: "127.0.0.1", port });
487 socket.once("connect", () => {
488 socket.destroy();
489 resolve(true);
490 });
491 socket.once("error", () => resolve(false));
492 socket.setTimeout(500, () => {
493 socket.destroy();
494 resolve(false);
495 });
496 });
497 if (open) return;
498 await delay(500);
499 }
500 throw new Error(`${label} did not begin listening on port ${port} within ${timeoutMs}ms.`);
501}
502
503async function reserveAvailablePort(): Promise<number> {
504 return await new Promise<number>((resolve, reject) => {
505 const server = NodeNet.createServer();
506 server.once("error", reject);
507 server.listen(0, "127.0.0.1", () => {
508 const address = server.address();
509 if (!address || typeof address === "string") {
510 server.close();
511 reject(new Error("Could not reserve a local port for the showcase environment."));
512 return;
513 }
514 server.close((error) => (error ? reject(error) : resolve(address.port)));
515 });
516 });
517}
518
519async function createShowcaseShell(baseDir: string): Promise<string> {
520 const shellPath = NodePath.join(baseDir, "showcase-shell");
521 await NodeFSP.writeFile(
522 shellPath,
523 `#!/bin/sh
524if [ "$1" = "-ilc" ] || [ "$1" = "-lic" ]; then
525 exec /bin/sh -c "$2"
526fi
527exec /bin/cat
528`,
529 { mode: 0o755 },
530 );
531 return shellPath;
532}
533
534async function createShowcaseLabelProbe(baseDir: string, label: string): Promise<string> {
535 const binDirectory = NodePath.join(baseDir, "showcase-bin");
536 await NodeFSP.mkdir(binDirectory, { recursive: true });
537 const probeScript = `#!/bin/sh
538if [ "$1" = "--get" ] && [ "$2" = "ComputerName" ]; then
539 printf '%s\\n' ${JSON.stringify(label)}
540 exit 0
541fi
542if [ "$1" = "--pretty" ]; then
543 printf '%s\\n' ${JSON.stringify(label)}
544 exit 0
545fi
546exit 1
547`;
548 await Promise.all(
549 ["scutil", "hostnamectl"].map((executable) =>
550 NodeFSP.writeFile(NodePath.join(binDirectory, executable), probeScript, { mode: 0o755 }),
551 ),
552 );
553 return binDirectory;
554}
555
556function startShowcaseServer(
557 baseDir: string,
558 workspaceRoot: string,
559 port: number,
560 shellPath: string,
561 labelProbeDirectory: string,
562): NodeChildProcess.ChildProcess {
563 return spawnProcess(
564 "node",
565 [
566 "apps/server/src/bin.ts",
567 "serve",
568 "--host",
569 SERVER_HOST,
570 "--port",
571 String(port),
572 "--base-dir",
573 baseDir,
574 "--no-browser",
575 "--log-level",
576 "error",
577 workspaceRoot,
578 ],
579 {
580 env: {
581 ...NodeProcess.env,
582 PATH: `${labelProbeDirectory}:${NodeProcess.env.PATH ?? ""}`,
583 SHELL: shellPath,
584 },
585 },
586 );
587}
588
589export function parsePairingCredentialOutput(output: string): string {
590 const jsonStart = output.indexOf("{");
591 const jsonEnd = output.lastIndexOf("}");
592 if (jsonStart === -1 || jsonEnd < jsonStart) {
593 throw new Error("Pairing credential command did not return JSON.");
594 }
595 const parsed = JSON.parse(output.slice(jsonStart, jsonEnd + 1)) as {
596 readonly credential?: unknown;
597 };
598 if (typeof parsed.credential !== "string" || parsed.credential.length === 0) {
599 throw new Error("Pairing credential command returned no credential.");
600 }
601 return parsed.credential;
602}
603
604async function issuePairingCredential(baseDir: string): Promise<string> {
605 const output = await commandOutput(
606 "node",
607 ["apps/server/src/bin.ts", "auth", "pairing", "create", "--base-dir", baseDir, "--json"],
608 { env: { ...NodeProcess.env, NO_COLOR: "1" } },
609 );
610 return parsePairingCredentialOutput(output);
611}
612
613function buildShowcasePairingUrl(host: string, port: number, credential: string): string {
614 const url = new URL(`http://${host}:${port}/`);
615 url.hash = new URLSearchParams([["token", credential]]).toString();
616 return url.toString();
617}
618
619export function showcaseSceneUrl(scene: ShowcaseScene, environmentId: string): string {
620 if (scene === "threads") return `${APP_SCHEME}://`;
621 if (scene === "environments") return `${APP_SCHEME}://settings/environments`;
622 const threadPath = `threads/${encodeURIComponent(environmentId)}/${SHOWCASE_THREAD_ID}`;
623 if (scene === "thread") return `${APP_SCHEME}://${threadPath}`;
624 if (scene === "terminal") {
625 return `${APP_SCHEME}://${threadPath}/terminal?terminalId=${SHOWCASE_TERMINAL_ID}`;
626 }
627 return `${APP_SCHEME}://${threadPath}/review`;
628}
629
630export function encodeAndroidPairingUrls(pairingUrls: ReadonlyArray<string>): string {
631 return `json-uri:${encodeURIComponent(JSON.stringify(pairingUrls))}`;
632}
633
634function startMetro(config: ShowcaseConfig): NodeChildProcess.ChildProcess {
635 return spawnProcess(
636 "pnpm",
637 ["exec", "expo", "start", "--dev-client", "--port", String(config.metroPort)],
638 {
639 cwd: MOBILE_ROOT,
640 env: {
641 ...MOBILE_BUILD_ENV,
642 EXPO_PUBLIC_SHOWCASE: "1",
643 },
644 },
645 );
646}
647
648async function warmMetroBundle(
649 platform: ShowcaseDevice["platform"],
650 host: string,
651 config: ShowcaseConfig,
652): Promise<void> {
653 const url = `http://${host}:${config.metroPort}/apps/mobile/index.bundle?platform=${platform}&dev=true&minify=false`;
654 await runCommand("curl", ["--fail", "--silent", "--show-error", "--output", "/dev/null", url]);
655}
656
657async function buildIos(): Promise<string> {
658 const derivedData = NodePath.join(MOBILE_ROOT, ".showcase/ios-derived-data");
659 await runCommand("pnpm", ["exec", "expo", "prebuild", "--clean", "--platform", "ios"], {
660 cwd: MOBILE_ROOT,
661 env: MOBILE_BUILD_ENV,
662 });
663 await runCommand(
664 "xcodebuild",
665 [
666 "-workspace",
667 NodePath.join(MOBILE_ROOT, "ios/T3CodeDev.xcworkspace"),
668 "-scheme",
669 "T3CodeDev",
670 "-configuration",
671 "Debug",
672 "-sdk",
673 "iphonesimulator",
674 "-derivedDataPath",
675 derivedData,
676 "-quiet",
677 `ARCHS=${IOS_SIMULATOR_ARCH}`,
678 "ONLY_ACTIVE_ARCH=YES",
679 "build",
680 ],
681 { cwd: MOBILE_ROOT, env: MOBILE_BUILD_ENV },
682 );
683 return IOS_APP_PATH;
684}
685
686async function buildAndroid(abis: ReadonlyArray<string>): Promise<string> {
687 await runCommand("pnpm", ["exec", "expo", "prebuild", "--clean", "--platform", "android"], {
688 cwd: MOBILE_ROOT,
689 env: MOBILE_BUILD_ENV,
690 });
691 await runCommand(
692 "./gradlew",
693 [
694 "app:assembleDebug",
695 ...(abis.length > 0 ? [`-PreactNativeArchitectures=${abis.join(",")}`] : []),
696 ],
697 {
698 cwd: NodePath.join(MOBILE_ROOT, "android"),
699 env: MOBILE_BUILD_ENV,
700 },
701 );
702 return ANDROID_APK_PATH;
703}
704
705async function existingArtifact(path: string): Promise<string | null> {
706 return await NodeFSP.access(path).then(
707 () => path,
708 () => null,
709 );
710}
711
712interface SimctlDevice {
713 readonly name: string;
714 readonly udid: string;
715 readonly state: "Booted" | "Shutdown" | string;
716 readonly isAvailable: boolean;
717}
718
719async function findIosSimulator(name: string): Promise<SimctlDevice | null> {
720 const parsed = JSON.parse(
721 await commandOutput("xcrun", ["simctl", "list", "devices", "available", "-j"]),
722 ) as {
723 readonly devices: Readonly<Record<string, ReadonlyArray<SimctlDevice>>>;
724 };
725 const candidates = Object.entries(parsed.devices)
726 .filter(([runtime]) => runtime.includes("iOS"))
727 .flatMap(([, devices]) => devices)
728 .filter((device) => device.isAvailable && device.name === name);
729 return candidates.at(-1) ?? null;
730}
731
732async function ensureIosSimulator(device: ShowcaseIosDevice): Promise<{
733 readonly simulator: SimctlDevice;
734 readonly createdByRunner: boolean;
735}> {
736 const existing = await findIosSimulator(device.simulator);
737 if (existing) return { simulator: existing, createdByRunner: false };
738 if (!device.simulatorDeviceType) {
739 throw new Error(
740 `iOS simulator '${device.simulator}' is not installed and has no simulatorDeviceType configured.`,
741 );
742 }
743 const udid = (
744 await commandOutput("xcrun", ["simctl", "create", device.simulator, device.simulatorDeviceType])
745 ).trim();
746 if (!udid) throw new Error(`Could not create iOS simulator '${device.simulator}'.`);
747 return {
748 simulator: {
749 name: device.simulator,
750 udid,
751 state: "Shutdown",
752 isAvailable: true,
753 },
754 createdByRunner: true,
755 };
756}
757
758async function normalizeIosSimulator(appearance: ShowcaseAppearance, udid: string): Promise<void> {
759 await runCommand("xcrun", ["simctl", "ui", udid, "appearance", appearance]);
760 await runCommand("xcrun", [
761 "simctl",
762 "status_bar",
763 udid,
764 "override",
765 "--time",
766 "9:41",
767 "--batteryState",
768 "charged",
769 "--batteryLevel",
770 "100",
771 "--wifiBars",
772 "3",
773 "--cellularBars",
774 "4",
775 ]);
776}
777
778async function iosAppContainer(udid: string): Promise<string> {
779 return (
780 await commandOutput("xcrun", ["simctl", "get_app_container", udid, ANDROID_PACKAGE, "data"])
781 ).trim();
782}
783
784async function waitForIosShowcaseScene(
785 udid: string,
786 scene: ShowcaseScene,
787 timeoutMs = 90_000,
788): Promise<void> {
789 const readyPath = NodePath.join(
790 await iosAppContainer(udid),
791 "Library/Caches",
792 IOS_READY_FILENAME,
793 );
794 const deadline = Date.now() + timeoutMs;
795 while (Date.now() < deadline) {
796 const readyScene = await NodeFSP.readFile(readyPath, "utf8").catch(() => "");
797 if (readyScene.trim() === scene) return;
798 await delay(500);
799 }
800 throw new Error(`iOS showcase scene '${scene}' did not render within ${timeoutMs}ms.`);
801}
802
803async function captureIos(
804 capture: ShowcaseCapture & { readonly device: ShowcaseIosDevice },
805 appPath: string | null,
806 outputDirectory: string,
807 config: ShowcaseConfig,
808 metroHost: string,
809 pairingUrls: ReadonlyArray<string>,
810 registerCleanup: (cleanup: IosCaptureCleanup) => void,
811): Promise<void> {
812 const { simulator, createdByRunner } = await ensureIosSimulator(capture.device);
813 const startedByRunner = simulator.state !== "Booted";
814 registerCleanup({ udid: simulator.udid, startedByRunner, createdByRunner });
815 if (!startedByRunner) {
816 // Clear transient SpringBoard state (permission prompts, stale URL-open
817 // confirmations, keyboards) without erasing the developer's simulator.
818 await runCommand("xcrun", ["simctl", "shutdown", simulator.udid]);
819 }
820 await runCommand("xcrun", ["simctl", "boot", simulator.udid]);
821 await runCommand("xcrun", ["simctl", "bootstatus", simulator.udid, "-b"]);
822 await normalizeIosSimulator(capture.appearance, simulator.udid);
823 if (appPath) {
824 await runCommand("xcrun", ["simctl", "uninstall", simulator.udid, ANDROID_PACKAGE]).catch(
825 () => undefined,
826 );
827 await runCommand("xcrun", ["simctl", "install", simulator.udid, appPath]);
828 }
829
830 for (const [key, value] of [
831 ["EXDevMenuIsOnboardingFinished", "true"],
832 ["EXDevMenuShowFloatingActionButton", "false"],
833 ["EXDevMenuShowsAtLaunch", "false"],
834 ] as const) {
835 await runCommand("xcrun", [
836 "simctl",
837 "spawn",
838 simulator.udid,
839 "defaults",
840 "write",
841 ANDROID_PACKAGE,
842 key,
843 "-bool",
844 value,
845 ]);
846 }
847
848 const metroUrl = `http://${metroHost}:${config.metroPort}?disableOnboarding=1`;
849 const scenePath = NodePath.join(
850 await iosAppContainer(simulator.udid),
851 "Library/Caches/T3ShowcaseScene",
852 );
853 const readyPath = NodePath.join(
854 await iosAppContainer(simulator.udid),
855 "Library/Caches",
856 IOS_READY_FILENAME,
857 );
858 const firstScene = capture.scenes[0] ?? "threads";
859 const launchShowcaseApp = async (terminateRunningProcess: boolean) => {
860 await runCommand("xcrun", [
861 "simctl",
862 "launch",
863 ...(terminateRunningProcess ? ["--terminate-running-process"] : []),
864 simulator.udid,
865 ANDROID_PACKAGE,
866 "--initialUrl",
867 metroUrl,
868 "--showcasePairingUrl",
869 JSON.stringify(pairingUrls),
870 "--showcaseScene",
871 firstScene,
872 ]);
873 };
874 await NodeFSP.rm(readyPath, { force: true });
875 await NodeFSP.writeFile(scenePath, firstScene);
876 await launchShowcaseApp(false);
877 for (const [sceneIndex, scene] of capture.scenes.entries()) {
878 if (sceneIndex > 0) await NodeFSP.rm(readyPath, { force: true });
879 await NodeFSP.writeFile(scenePath, scene);
880 if (sceneIndex === 0) {
881 for (let attempt = 0; attempt < 2; attempt += 1) {
882 const isLastAttempt = attempt === 1;
883 try {
884 // A freshly installed Expo development build can spend well over 30s
885 // applying an already-bundled update after it reaches 100%. Killing it
886 // at that point sends the next capture back to the dev launcher.
887 await waitForIosShowcaseScene(simulator.udid, scene, 120_000);
888 break;
889 } catch (error) {
890 if (isLastAttempt) throw error;
891 await launchShowcaseApp(true);
892 }
893 }
894 } else {
895 await waitForIosShowcaseScene(simulator.udid, scene);
896 }
897 await delay(scene === "review" ? Math.max(config.settleDelayMs, 8_000) : config.settleDelayMs);
898 const destination = NodePath.join(
899 showcaseCaptureDirectory(outputDirectory, capture),
900 `${scene}.png`,
901 );
902 await runCommand("xcrun", ["simctl", "io", simulator.udid, "screenshot", destination]);
903 await finalizeCapture(destination, capture.device);
904 }
905}
906
907function androidSdkTool(relativePath: string): string {
908 return NodePath.join(ANDROID_SDK_ROOT, relativePath);
909}
910
911async function adbOutput(serial: string, args: ReadonlyArray<string>): Promise<string> {
912 return await commandOutput(androidSdkTool("platform-tools/adb"), ["-s", serial, ...args]);
913}
914
915async function runAdb(serial: string, args: ReadonlyArray<string>): Promise<void> {
916 await runCommand(androidSdkTool("platform-tools/adb"), ["-s", serial, ...args]);
917}
918
919async function runningAndroidAvds(): Promise<ReadonlyMap<string, string>> {
920 const adb = androidSdkTool("platform-tools/adb");
921 const devices = (await commandOutput(adb, ["devices"]))
922 .split("\n")
923 .map((line) => line.trim().split(/\s+/u))
924 .filter((parts) => parts[0]?.startsWith("emulator-") && parts[1] === "device")
925 .map((parts) => parts[0] as string);
926 const result = new Map<string, string>();
927 for (const serial of devices) {
928 const avdName = (await adbOutput(serial, ["emu", "avd", "name"])).split("\n")[0]?.trim();
929 if (avdName) result.set(avdName, serial);
930 }
931 return result;
932}
933
934async function waitForAndroidSerial(avd: string, timeoutMs = 120_000): Promise<string> {
935 const deadline = Date.now() + timeoutMs;
936 while (Date.now() < deadline) {
937 const serial = (await runningAndroidAvds()).get(avd);
938 if (serial) {
939 await runAdb(serial, ["wait-for-device"]);
940 const bootCompleted = (
941 await adbOutput(serial, ["shell", "getprop", "sys.boot_completed"])
942 ).trim();
943 if (bootCompleted === "1") return serial;
944 }
945 await delay(1_000);
946 }
947 throw new Error(`Android AVD '${avd}' did not finish booting within ${timeoutMs}ms.`);
948}
949
950async function normalizeAndroidEmulator(
951 device: ShowcaseAndroidDevice,
952 appearance: ShowcaseAppearance,
953 serial: string,
954): Promise<void> {
955 await runAdb(serial, ["shell", "settings", "put", "global", "window_animation_scale", "0"]);
956 await runAdb(serial, ["shell", "settings", "put", "global", "transition_animation_scale", "0"]);
957 await runAdb(serial, ["shell", "settings", "put", "global", "animator_duration_scale", "0"]);
958 await runAdb(serial, ["shell", "cmd", "uimode", "night", appearance === "dark" ? "yes" : "no"]);
959 await runAdb(serial, ["shell", "settings", "put", "system", "time_12_24", "12"]);
960 await runAdb(serial, ["emu", "power", "capacity", "100"]);
961 await runAdb(serial, ["shell", "settings", "put", "global", "sysui_demo_allowed", "1"]);
962 await runAdb(serial, [
963 "shell",
964 "am",
965 "broadcast",
966 "-a",
967 "com.android.systemui.demo",
968 "-e",
969 "command",
970 "enter",
971 ]);
972 await runAdb(serial, [
973 "shell",
974 "am",
975 "broadcast",
976 "-a",
977 "com.android.systemui.demo",
978 "-e",
979 "command",
980 "clock",
981 "-e",
982 "hhmm",
983 "0941",
984 ]);
985 await runAdb(serial, [
986 "shell",
987 "am",
988 "broadcast",
989 "-a",
990 "com.android.systemui.demo",
991 "-e",
992 "command",
993 "battery",
994 "-e",
995 "level",
996 "100",
997 "-e",
998 "plugged",
999 "false",
1000 ]);
1001 if (device.viewport) {
1002 await runAdb(serial, [
1003 "shell",
1004 "wm",
1005 "size",
1006 `${device.viewport.width}x${device.viewport.height}`,
1007 ]);
1008 if (device.viewport.density) {
1009 await runAdb(serial, ["shell", "wm", "density", String(device.viewport.density)]);
1010 }
1011 }
1012}
1013
1014async function waitForAndroidShowcaseScene(
1015 serial: string,
1016 scene: ShowcaseScene,
1017 timeoutMs = 90_000,
1018): Promise<void> {
1019 const deadline = Date.now() + timeoutMs;
1020 while (Date.now() < deadline) {
1021 const readyScene = await adbOutput(serial, [
1022 "shell",
1023 "run-as",
1024 ANDROID_PACKAGE,
1025 "cat",
1026 "files/t3-showcase-ready",
1027 ]).catch(() => "");
1028 if (readyScene.trim() === scene) return;
1029 await delay(500);
1030 }
1031 throw new Error(`Android showcase scene '${scene}' did not render within ${timeoutMs}ms.`);
1032}
1033
1034async function writeAndroidShowcaseScene(serial: string, scene: ShowcaseScene): Promise<void> {
1035 await runAdb(serial, [
1036 "shell",
1037 `run-as ${ANDROID_PACKAGE} sh -c 'mkdir -p files && rm -f files/t3-showcase-ready && printf %s ${scene} > files/t3-showcase-scene'`,
1038 ]);
1039}
1040
1041async function prepareAndroidShowcaseApp(serial: string): Promise<void> {
1042 const preferences = `<?xml version="1.0" encoding="utf-8" standalone="yes" ?>
1043<map>
1044 <boolean name="isOnboardingFinished" value="true" />
1045 <boolean name="showsAtLaunch" value="false" />
1046 <boolean name="showFab" value="false" />
1047 <boolean name="motionGestureEnabled" value="false" />
1048 <boolean name="touchGestureEnabled" value="false" />
1049 <boolean name="keyCommandsEnabled" value="false" />
1050</map>`;
1051 const encodedPreferences = Buffer.from(preferences).toString("base64");
1052 await runAdb(serial, [
1053 "shell",
1054 `run-as ${ANDROID_PACKAGE} sh -c 'mkdir -p shared_prefs && printf %s ${encodedPreferences} | base64 -d > shared_prefs/expo.modules.devmenu.sharedpreferences.xml'`,
1055 ]);
1056}
1057
1058async function captureAndroid(
1059 capture: ShowcaseCapture & { readonly device: ShowcaseAndroidDevice },
1060 apkPath: string | null,
1061 outputDirectory: string,
1062 config: ShowcaseConfig,
1063 pairingUrls: ReadonlyArray<string>,
1064 registerCleanup: (cleanup: AndroidCaptureCleanup) => void,
1065): Promise<void> {
1066 const running = await runningAndroidAvds();
1067 const existingSerial = running.get(capture.device.avd);
1068 const startedByRunner = !existingSerial;
1069 let launchedEmulator: NodeChildProcess.ChildProcess | null = null;
1070 if (startedByRunner) {
1071 const installedAvds = (await commandOutput(androidSdkTool("emulator/emulator"), ["-list-avds"]))
1072 .split("\n")
1073 .map((value) => value.trim());
1074 if (!installedAvds.includes(capture.device.avd)) {
1075 throw new Error(
1076 `Android AVD '${capture.device.avd}' is not installed. Run emulator -list-avds.`,
1077 );
1078 }
1079 launchedEmulator = spawnProcess(
1080 androidSdkTool("emulator/emulator"),
1081 ["-avd", capture.device.avd, "-no-snapshot-load", "-no-boot-anim"],
1082 { stdio: "ignore", detached: true },
1083 );
1084 launchedEmulator.unref();
1085 }
1086 const serial =
1087 existingSerial ??
1088 (await waitForAndroidSerial(capture.device.avd).catch(async (error: unknown) => {
1089 if (launchedEmulator) await stopProcess(launchedEmulator);
1090 throw error;
1091 }));
1092 registerCleanup({ device: capture.device, serial, startedByRunner });
1093 await normalizeAndroidEmulator(capture.device, capture.appearance, serial);
1094 if (apkPath) {
1095 await runAdb(serial, ["install", "-r", apkPath]);
1096 }
1097 await runAdb(serial, ["shell", "pm", "clear", ANDROID_PACKAGE]);
1098 await prepareAndroidShowcaseApp(serial);
1099 await runAdb(serial, ["reverse", `tcp:${config.metroPort}`, `tcp:${config.metroPort}`]);
1100 const metroUrl = encodeURIComponent(`http://127.0.0.1:${config.metroPort}?disableOnboarding=1`);
1101 const firstScene = capture.scenes[0] ?? "threads";
1102 await runAdb(serial, [
1103 "shell",
1104 "am",
1105 "start",
1106 "-W",
1107 "-a",
1108 "android.intent.action.VIEW",
1109 "-d",
1110 `${APP_SCHEME}://expo-development-client/?url=${metroUrl}`,
1111 "--es",
1112 "showcasePairingUrl",
1113 encodeAndroidPairingUrls(pairingUrls),
1114 "--es",
1115 "showcaseScene",
1116 firstScene,
1117 ANDROID_PACKAGE,
1118 ]);
1119 for (const [sceneIndex, scene] of capture.scenes.entries()) {
1120 if (sceneIndex > 0) await writeAndroidShowcaseScene(serial, scene);
1121 await waitForAndroidShowcaseScene(serial, scene);
1122 await delay(Math.max(config.settleDelayMs, scene === "review" ? 8_000 : 5_000));
1123 const destination = NodePath.join(
1124 showcaseCaptureDirectory(outputDirectory, capture),
1125 `${scene}.png`,
1126 );
1127 const png = await new Promise<Buffer>((resolve, reject) => {
1128 NodeChildProcess.execFile(
1129 androidSdkTool("platform-tools/adb"),
1130 ["-s", serial, "exec-out", "screencap", "-p"],
1131 { cwd: REPO_ROOT, encoding: "buffer", maxBuffer: 64 * 1024 * 1024 },
1132 (error, stdout) => {
1133 if (error) reject(error);
1134 else resolve(stdout);
1135 },
1136 );
1137 });
1138 await NodeFSP.writeFile(destination, png);
1139 await finalizeCapture(destination, capture.device);
1140 }
1141}
1142
1143async function cleanupAndroidViewport(
1144 device: ShowcaseAndroidDevice,
1145 serial: string,
1146): Promise<void> {
1147 await runAdb(serial, [
1148 "shell",
1149 "am",
1150 "broadcast",
1151 "-a",
1152 "com.android.systemui.demo",
1153 "-e",
1154 "command",
1155 "exit",
1156 ]);
1157 if (!device.viewport) return;
1158 await runAdb(serial, ["shell", "wm", "size", "reset"]);
1159 if (device.viewport.density) {
1160 await runAdb(serial, ["shell", "wm", "density", "reset"]);
1161 }
1162}
1163
1164async function main(): Promise<void> {
1165 const options = parseShowcaseCliArgs(NodeProcess.argv.slice(2));
1166 if (options.list) {
1167 printUsage(showcaseConfig);
1168 return;
1169 }
1170 const captures = planShowcaseCaptures(showcaseConfig, options);
1171 const outputDirectory = NodePath.resolve(REPO_ROOT, showcaseConfig.outputDirectory);
1172 if (options.validateOnly) {
1173 for (const capture of captures) {
1174 await validateCaptureSet(
1175 capture,
1176 outputDirectory,
1177 capture.scenes.length === capture.device.scenes.length,
1178 );
1179 }
1180 return;
1181 }
1182 const hasIos = captures.some((capture) => capture.device.platform === "ios");
1183 const hasAndroid = captures.some((capture) => capture.device.platform === "android");
1184 const metroHost = hasIos ? lanIpv4Address() : "127.0.0.1";
1185 await NodeFSP.mkdir(outputDirectory, { recursive: true });
1186 for (const capture of captures) {
1187 const directory = showcaseCaptureDirectory(outputDirectory, capture);
1188 await NodeFSP.rm(directory, { recursive: true, force: true });
1189 await NodeFSP.mkdir(directory, { recursive: true });
1190 }
1191
1192 const showcaseRootDir = await NodeFSP.mkdtemp(
1193 NodePath.join(NodeOS.tmpdir(), "t3-mobile-showcase-"),
1194 );
1195 const showcaseServers: NodeChildProcess.ChildProcess[] = [];
1196 const showcaseEnvironments: Array<{
1197 readonly baseDir: string;
1198 readonly environmentId: string;
1199 readonly label: string;
1200 readonly port: number;
1201 }> = [];
1202 let metro: NodeChildProcess.ChildProcess | null = null;
1203 const iosCleanups: IosCaptureCleanup[] = [];
1204 const androidCleanups: AndroidCaptureCleanup[] = [];
1205
1206 try {
1207 for (const environment of SHOWCASE_ENVIRONMENTS) {
1208 const projectId = environment.projectIds[0];
1209 const project = SHOWCASE_PROJECTS.find((candidate) => candidate.id === projectId);
1210 if (!project) throw new Error(`Showcase environment '${environment.id}' has no project.`);
1211
1212 const baseDir = NodePath.join(showcaseRootDir, "environments", environment.id);
1213 const workspaceRoot = NodePath.join(baseDir, "workspace", project.directory);
1214 const port = await reserveAvailablePort();
1215 await NodeFSP.mkdir(workspaceRoot, { recursive: true });
1216 const shellPath = await createShowcaseShell(baseDir);
1217 const labelProbeDirectory = await createShowcaseLabelProbe(baseDir, environment.label);
1218 const server = startShowcaseServer(
1219 baseDir,
1220 workspaceRoot,
1221 port,
1222 shellPath,
1223 labelProbeDirectory,
1224 );
1225 showcaseServers.push(server);
1226 await waitForPort(port, `${environment.label} server`);
1227 await seedShowcaseEnvironment({ baseDir, projectIds: environment.projectIds });
1228 const environmentId = (
1229 await NodeFSP.readFile(NodePath.join(baseDir, "userdata", "environment-id"), "utf8")
1230 ).trim();
1231 if (!environmentId) {
1232 throw new Error(`${environment.label} did not persist an environment id.`);
1233 }
1234 showcaseEnvironments.push({ baseDir, environmentId, label: environment.label, port });
1235 }
1236
1237 if (!options.skipMetro) {
1238 metro = startMetro(showcaseConfig);
1239 await waitForPort(showcaseConfig.metroPort, "Metro");
1240 await Promise.all([
1241 hasIos ? warmMetroBundle("ios", metroHost, showcaseConfig) : Promise.resolve(),
1242 hasAndroid ? warmMetroBundle("android", "127.0.0.1", showcaseConfig) : Promise.resolve(),
1243 ]);
1244 }
1245
1246 const iosAppPath = hasIos
1247 ? options.skipBuild
1248 ? await existingArtifact(IOS_APP_PATH)
1249 : await buildIos()
1250 : null;
1251 const androidAbis = captures.flatMap((capture) =>
1252 capture.device.platform === "android" && capture.device.abi ? [capture.device.abi] : [],
1253 );
1254 const androidApkPath = hasAndroid
1255 ? options.skipBuild
1256 ? await existingArtifact(ANDROID_APK_PATH)
1257 : await buildAndroid([...new Set(androidAbis)])
1258 : null;
1259
1260 for (const capture of captures) {
1261 const pairingHost = capture.device.platform === "ios" ? "127.0.0.1" : "10.0.2.2";
1262 const pairingUrls = await Promise.all(
1263 showcaseEnvironments.map(async (environment) => {
1264 const credential = await issuePairingCredential(environment.baseDir);
1265 return buildShowcasePairingUrl(pairingHost, environment.port, credential);
1266 }),
1267 );
1268 if (capture.device.platform === "ios") {
1269 await captureIos(
1270 capture as ShowcaseCapture & { readonly device: ShowcaseIosDevice },
1271 iosAppPath,
1272 outputDirectory,
1273 showcaseConfig,
1274 metroHost,
1275 pairingUrls,
1276 (cleanup) => iosCleanups.push(cleanup),
1277 );
1278 } else {
1279 await captureAndroid(
1280 capture as ShowcaseCapture & { readonly device: ShowcaseAndroidDevice },
1281 androidApkPath,
1282 outputDirectory,
1283 showcaseConfig,
1284 pairingUrls,
1285 (cleanup) => androidCleanups.push(cleanup),
1286 );
1287 }
1288 await validateCaptureSet(
1289 capture,
1290 outputDirectory,
1291 capture.scenes.length === capture.device.scenes.length,
1292 );
1293 }
1294
1295 NodeProcess.stdout.write(
1296 `\nDone. Upload-ready screenshots are in ${NodePath.relative(REPO_ROOT, outputDirectory)}/apple/ and ${NodePath.relative(REPO_ROOT, outputDirectory)}/google-play/.\n`,
1297 );
1298 if (options.keepRunning) {
1299 const serverSummary = showcaseEnvironments
1300 .map((environment) => `${environment.label}:${environment.port}`)
1301 .join(", ");
1302 NodeProcess.stdout.write(
1303 `Showcase environments kept at ${showcaseRootDir} (${serverSummary}).\n`,
1304 );
1305 }
1306 } finally {
1307 if (options.keepRunning) {
1308 metro?.unref();
1309 for (const server of showcaseServers) server.unref();
1310 } else {
1311 for (const cleanup of androidCleanups) {
1312 await cleanupAndroidViewport(cleanup.device, cleanup.serial).catch(() => undefined);
1313 if (cleanup.startedByRunner) {
1314 await runAdb(cleanup.serial, ["emu", "kill"]).catch(() => undefined);
1315 }
1316 }
1317 for (const cleanup of iosCleanups) {
1318 if (cleanup.startedByRunner || cleanup.createdByRunner) {
1319 await runCommand("xcrun", ["simctl", "shutdown", cleanup.udid]).catch(() => undefined);
1320 }
1321 if (cleanup.createdByRunner) {
1322 await runCommand("xcrun", ["simctl", "delete", cleanup.udid]).catch(() => undefined);
1323 }
1324 }
1325 await Promise.all([
1326 ...(metro ? [stopProcess(metro)] : []),
1327 ...showcaseServers.map((server) => stopProcess(server)),
1328 ]);
1329 await NodeFSP.rm(showcaseRootDir, {
1330 recursive: true,
1331 force: true,
1332 maxRetries: 5,
1333 retryDelay: 100,
1334 });
1335 }
1336 }
1337}
1338
1339if (import.meta.main) {
1340 void main().catch((error: unknown) => {
1341 NodeProcess.stderr.write(`${error instanceof Error ? error.message : String(error)}\n`);
1342 NodeProcess.exit(1);
1343 });
1344}