Repository navigation
Expand file tree
/
Copy pathmobile-showcase.ts
More file actions
1518 lines (1431 loc) · 50.4 KB
/
Copy pathmobile-showcase.ts
File metadata and controls
1518 lines (1431 loc) · 50.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env node
// @effect-diagnostics nodeBuiltinImport:off globalTimers:off globalDate:off - Host-side simulator and emulator automation uses Node subprocess and timing APIs directly.
import * as NodeChildProcess from "node:child_process";
import * as NodeFSP from "node:fs/promises";
import * as NodeNet from "node:net";
import * as NodeOS from "node:os";
import * as NodePath from "node:path";
import * as NodeProcess from "node:process";
import * as NodeURL from "node:url";
import { PNG } from "pngjs";
import showcaseConfig, {
type ShowcaseAppearance,
type ShowcaseAndroidDevice,
type ShowcaseConfig,
type ShowcaseDevice,
type ShowcaseIosDevice,
type ShowcaseStoreAssetSpec,
SHOWCASE_SCENES,
type ShowcaseScene,
SHOWCASE_THEMES,
type ShowcaseTheme,
} from "./mobile-showcase.config.ts";
import {
SHOWCASE_ENVIRONMENTS,
SHOWCASE_PROJECTS,
SHOWCASE_TERMINAL_ID,
SHOWCASE_THREAD_ID,
seedShowcaseEnvironment,
} from "./mobile-showcase-environment.ts";
const REPO_ROOT = NodePath.resolve(NodePath.dirname(NodeURL.fileURLToPath(import.meta.url)), "..");
const MOBILE_ROOT = NodePath.join(REPO_ROOT, "apps/mobile");
const ANDROID_PACKAGE = "com.t3tools.t3code";
const APP_SCHEME = "t3code";
const IOS_READY_FILENAME = "T3ShowcaseReadyScene";
const SERVER_HOST = "0.0.0.0";
const IOS_SIMULATOR_ARCH = NodeProcess.arch === "arm64" ? "arm64" : "x86_64";
const IOS_APP_PATH = NodePath.join(
MOBILE_ROOT,
".showcase/ios-derived-data/Build/Products/Debug-iphonesimulator/T3Code.app",
);
const ANDROID_APK_PATH = NodePath.join(
MOBILE_ROOT,
"android/app/build/outputs/apk/debug/app-debug.apk",
);
export function resolveAndroidSdkRoot(
environment: Readonly<Record<string, string | undefined>>,
platform: NodeJS.Platform = NodeProcess.platform,
): string {
const configured = environment.ANDROID_HOME ?? environment.ANDROID_SDK_ROOT;
if (configured) return configured;
const home = environment.HOME ?? environment.USERPROFILE ?? "";
const path = platform === "win32" ? NodePath.win32 : NodePath.posix;
return path.join(home, platform === "darwin" ? "Library/Android/sdk" : "Android/Sdk");
}
const ANDROID_SDK_ROOT = resolveAndroidSdkRoot(NodeProcess.env);
const MOBILE_BUILD_ENV = {
...NodeProcess.env,
ANDROID_HOME: ANDROID_SDK_ROOT,
APP_VARIANT: "production",
EXPO_NO_GIT_STATUS: "1",
// Lets the capture build require full screen on iPad so the app can rotate
// itself to landscape (see app.config.ts).
T3_SHOWCASE_CAPTURE_BUILD: "1",
JAVA_HOME:
NodeProcess.env.JAVA_HOME ??
(NodeProcess.platform === "darwin"
? "/Applications/Android Studio.app/Contents/jbr/Contents/Home"
: undefined),
NODE_ENV: "development",
};
interface CliOptions {
readonly platforms: ReadonlySet<ShowcaseDevice["platform"]>;
readonly deviceIds: ReadonlySet<string>;
readonly scenes: ReadonlySet<ShowcaseScene>;
readonly appearances: ReadonlySet<ShowcaseAppearance>;
readonly themes: ReadonlySet<ShowcaseTheme>;
readonly skipBuild: boolean;
readonly skipMetro: boolean;
readonly keepRunning: boolean;
readonly validateOnly: boolean;
readonly list: boolean;
}
export interface ShowcaseCapture {
readonly device: ShowcaseDevice;
readonly scenes: ReadonlyArray<ShowcaseScene>;
readonly appearance: ShowcaseAppearance;
readonly theme: ShowcaseTheme;
}
interface IosCaptureCleanup {
readonly udid: string;
readonly startedByRunner: boolean;
readonly createdByRunner: boolean;
}
interface AndroidCaptureCleanup {
readonly device: ShowcaseAndroidDevice;
readonly serial: string;
readonly startedByRunner: boolean;
}
interface NetworkAddress {
readonly address: string;
readonly family: string;
readonly internal: boolean;
}
export function selectLanIpv4Address(addresses: ReadonlyArray<NetworkAddress>): string | null {
return (
addresses.find(
({ address, family, internal }) =>
family === "IPv4" && !internal && !address.startsWith("169.254."),
)?.address ?? null
);
}
function lanIpv4Address(): string {
const address = selectLanIpv4Address(
Object.values(NodeOS.networkInterfaces()).flatMap((addresses) => addresses ?? []),
);
if (!address) {
throw new Error("No LAN IPv4 address is available for the iOS Simulator to reach Metro.");
}
return address;
}
export interface PngMetadata {
readonly width: number;
readonly height: number;
readonly bitDepth: number;
readonly colorType: number;
readonly hasAlpha: boolean;
}
export function readPngMetadata(bytes: Uint8Array): PngMetadata {
const pngSignature = [137, 80, 78, 71, 13, 10, 26, 10];
if (bytes.byteLength < 26 || !pngSignature.every((value, index) => bytes[index] === value)) {
throw new Error("Captured file is not a valid PNG.");
}
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
const colorType = view.getUint8(25);
return {
width: view.getUint32(16),
height: view.getUint32(20),
bitDepth: view.getUint8(24),
colorType,
hasAlpha: colorType === 4 || colorType === 6,
};
}
export function readPngDimensions(bytes: Uint8Array): {
readonly width: number;
readonly height: number;
} {
const { width, height } = readPngMetadata(bytes);
return { width, height };
}
export function normalizeStorePng(bytes: Uint8Array): Buffer {
const png = PNG.sync.read(Buffer.from(bytes));
return PNG.sync.write(png, {
bitDepth: 8,
colorType: 2,
inputColorType: 6,
inputHasAlpha: true,
});
}
export function validateStoreAsset(
spec: ShowcaseStoreAssetSpec,
bytes: Uint8Array,
label = "Screenshot",
): PngMetadata {
const metadata = readPngMetadata(bytes);
if (metadata.width !== spec.width || metadata.height !== spec.height) {
throw new Error(
`${label} is ${metadata.width}×${metadata.height}; ${spec.store} requires ${spec.width}×${spec.height}.`,
);
}
if (metadata.bitDepth !== 8 || metadata.colorType !== 2 || metadata.hasAlpha) {
throw new Error(
`${label} must be an 8-bit, 24-bit RGB PNG without alpha (found bit depth ${metadata.bitDepth}, color type ${metadata.colorType}).`,
);
}
if (spec.maximumFileSizeBytes && bytes.byteLength > spec.maximumFileSizeBytes) {
throw new Error(
`${label} is ${bytes.byteLength} bytes; ${spec.store} allows at most ${spec.maximumFileSizeBytes} bytes.`,
);
}
if (spec.store === "google-play") {
const shortestSide = Math.min(metadata.width, metadata.height);
const longestSide = Math.max(metadata.width, metadata.height);
if (shortestSide < 320 || longestSide > 3_840 || longestSide > shortestSide * 2) {
throw new Error(
`${label} does not meet Google Play's 320–3,840 px bounds and 2:1 maximum aspect ratio.`,
);
}
if (metadata.width * 16 !== metadata.height * 9) {
throw new Error(`${label} must use Google Play's recommended portrait 9:16 aspect ratio.`);
}
}
return metadata;
}
export function validateStoreAssetCount(
spec: ShowcaseStoreAssetSpec,
count: number,
requireMinimum: boolean,
): void {
if (count > spec.maximumUploadCount) {
throw new Error(
`${spec.directory} contains ${count} screenshots; ${spec.store} allows at most ${spec.maximumUploadCount}.`,
);
}
if (requireMinimum && count < spec.minimumUploadCount) {
throw new Error(
`${spec.directory} contains ${count} screenshots; ${spec.store} requires at least ${spec.minimumUploadCount}.`,
);
}
}
export function showcaseCaptureDirectory(
outputDirectory: string,
capture: Pick<ShowcaseCapture, "device" | "appearance" | "theme">,
): string {
// Each palette owns a leaf folder so one upload slot never mixes themes and
// every folder keeps a store-legal screenshot count of its own.
return NodePath.join(
outputDirectory,
capture.device.storeAsset.directory,
capture.appearance,
capture.theme,
);
}
async function finalizeCapture(destination: string, device: ShowcaseDevice): Promise<void> {
const normalized = normalizeStorePng(await NodeFSP.readFile(destination));
await NodeFSP.writeFile(destination, normalized);
const metadata = validateStoreAsset(
device.storeAsset,
normalized,
NodePath.basename(destination),
);
NodeProcess.stdout.write(
`Captured ${NodePath.relative(REPO_ROOT, destination)} (${metadata.width}×${metadata.height}, 24-bit RGB, validated for ${device.storeAsset.store})\n`,
);
}
async function validateCaptureSet(
capture: ShowcaseCapture,
outputDirectory: string,
requireMinimum: boolean,
): Promise<void> {
const directory = showcaseCaptureDirectory(outputDirectory, capture);
const files = (await NodeFSP.readdir(directory)).filter((file) => file.endsWith(".png")).sort();
const expectedFiles = capture.scenes.map((scene) => `${scene}.png`).sort();
const missingFiles = expectedFiles.filter((file) => !files.includes(file));
if (missingFiles.length > 0) {
throw new Error(`${capture.device.id} is missing ${missingFiles.join(", ")} in ${directory}.`);
}
validateStoreAssetCount(capture.device.storeAsset, files.length, requireMinimum);
for (const file of files) {
const bytes = await NodeFSP.readFile(NodePath.join(directory, file));
validateStoreAsset(capture.device.storeAsset, bytes, `${capture.device.id}/${file}`);
}
NodeProcess.stdout.write(
`Validated ${files.length} upload-ready ${capture.device.storeAsset.store} screenshots in ${NodePath.relative(REPO_ROOT, directory)}/\n`,
);
}
function argumentValue(args: ReadonlyArray<string>, index: number, flag: string): string {
const value = args[index + 1];
if (!value || value.startsWith("--")) {
throw new Error(`${flag} requires a value.`);
}
return value;
}
export function parseShowcaseCliArgs(args: ReadonlyArray<string>): CliOptions {
const platforms = new Set<ShowcaseDevice["platform"]>();
const deviceIds = new Set<string>();
const scenes = new Set<ShowcaseScene>();
const appearances = new Set<ShowcaseAppearance>();
const themes = new Set<ShowcaseTheme>();
let skipBuild = false;
let skipMetro = false;
let keepRunning = false;
let validateOnly = false;
let list = false;
for (let index = 0; index < args.length; index += 1) {
const argument = args[index];
if (argument === "--platform") {
const value = argumentValue(args, index, argument);
if (value !== "ios" && value !== "android" && value !== "all") {
throw new Error(`Unsupported platform '${value}'. Use ios, android, or all.`);
}
if (value === "all") {
platforms.add("ios");
platforms.add("android");
} else {
platforms.add(value);
}
index += 1;
} else if (argument === "--device") {
deviceIds.add(argumentValue(args, index, argument));
index += 1;
} else if (argument === "--scene") {
const value = argumentValue(args, index, argument);
if (!SHOWCASE_SCENES.includes(value as ShowcaseScene)) {
throw new Error(`Unsupported scene '${value}'. Use ${SHOWCASE_SCENES.join(", ")}.`);
}
scenes.add(value as ShowcaseScene);
index += 1;
} else if (argument === "--appearance") {
const value = argumentValue(args, index, argument);
if (value !== "light" && value !== "dark" && value !== "both") {
throw new Error(`Unsupported appearance '${value}'. Use light, dark, or both.`);
}
if (value === "both") {
appearances.add("light");
appearances.add("dark");
} else {
appearances.add(value);
}
index += 1;
} else if (argument === "--theme") {
const value = argumentValue(args, index, argument);
if (value === "all") {
for (const theme of SHOWCASE_THEMES) themes.add(theme);
} else if (SHOWCASE_THEMES.some((theme) => theme === value)) {
themes.add(value as ShowcaseTheme);
} else {
// The app silently falls back to its default palette for an unknown id,
// so reject it here rather than shipping a mislabeled screenshot.
throw new Error(`Unsupported theme '${value}'. Use ${SHOWCASE_THEMES.join(", ")}, or all.`);
}
index += 1;
} else if (argument === "--skip-build") {
skipBuild = true;
} else if (argument === "--skip-metro") {
skipMetro = true;
} else if (argument === "--keep-running") {
keepRunning = true;
} else if (argument === "--validate-only") {
validateOnly = true;
} else if (argument === "--list") {
list = true;
} else if (argument === "--help" || argument === "-h") {
list = true;
} else {
throw new Error(`Unknown option '${argument}'.`);
}
}
return {
platforms,
deviceIds,
scenes,
appearances,
themes,
skipBuild,
skipMetro,
keepRunning,
validateOnly,
list,
};
}
export function planShowcaseCaptures(
config: ShowcaseConfig,
options: Pick<CliOptions, "platforms" | "deviceIds" | "scenes" | "appearances" | "themes">,
): ReadonlyArray<ShowcaseCapture> {
const captures = config.devices
.filter((device) => options.platforms.size === 0 || options.platforms.has(device.platform))
.filter((device) => options.deviceIds.size === 0 || options.deviceIds.has(device.id))
.flatMap((device) => {
const appearances =
options.appearances.size === 0 ? [device.appearance] : options.appearances;
const themes = options.themes.size === 0 ? [device.theme] : options.themes;
return [...appearances].flatMap((appearance) =>
[...themes].map((theme) => ({
device,
appearance,
theme,
scenes:
options.scenes.size === 0
? device.scenes
: device.scenes.filter((scene) => options.scenes.has(scene)),
})),
);
})
.filter((capture) => capture.scenes.length > 0);
const knownDeviceIds = new Set(config.devices.map((device) => device.id));
for (const id of options.deviceIds) {
if (!knownDeviceIds.has(id)) {
throw new Error(`Unknown device '${id}'. Run with --list to see configured devices.`);
}
}
if (captures.length === 0) {
throw new Error("No captures match the selected platform, device, and scene filters.");
}
return captures;
}
function printUsage(config: ShowcaseConfig): void {
NodeProcess.stdout.write(`App screenshot showcase
Usage:
pnpm --filter @t3tools/mobile screenshots [options]
Options:
--platform ios|android|all Capture one platform (repeatable)
--device <id> Capture one configured device (repeatable)
--scene <name> Capture one scene (repeatable)
--appearance light|dark|both
Override the configured appearance
--theme <id>|all Override the configured palette (repeatable)
--skip-build Reuse the existing simulator app / debug APK
--skip-metro Reuse an already running showcase Metro server
--keep-running Leave devices and Metro running after capture
--validate-only Validate existing upload assets without capturing
--list Print this help and the configured matrix
Scenes: ${SHOWCASE_SCENES.join(", ")}
Themes: ${SHOWCASE_THEMES.join(", ")}
Configured devices:
${config.devices
.map((device) => {
const target = device.platform === "ios" ? device.simulator : device.avd;
return ` ${device.id.padEnd(18)} ${device.platform.padEnd(8)} ${target} -> ${device.storeAsset.directory}/{light|dark}/<theme> (${device.storeAsset.width}×${device.storeAsset.height}, default ${device.appearance} ${device.theme}) [${device.scenes.join(", ")}]`;
})
.join("\n")}
`);
}
function spawnProcess(
command: string,
args: ReadonlyArray<string>,
options: NodeChildProcess.SpawnOptions = {},
): NodeChildProcess.ChildProcess {
return NodeChildProcess.spawn(command, args, {
cwd: REPO_ROOT,
env: NodeProcess.env,
stdio: "inherit",
...options,
});
}
async function runCommand(
command: string,
args: ReadonlyArray<string>,
options: NodeChildProcess.SpawnOptions = {},
): Promise<void> {
await new Promise<void>((resolve, reject) => {
const child = spawnProcess(command, args, options);
child.once("error", reject);
child.once("exit", (code, signal) => {
if (code === 0) {
resolve();
} else {
reject(
new Error(
`${command} ${args.join(" ")} failed ${signal ? `with signal ${signal}` : `with code ${String(code)}`}.`,
),
);
}
});
});
}
async function commandOutput(
command: string,
args: ReadonlyArray<string>,
options: NodeChildProcess.ExecFileOptions = {},
): Promise<string> {
return await new Promise<string>((resolve, reject) => {
NodeChildProcess.execFile(
command,
[...args],
{ cwd: REPO_ROOT, encoding: "utf8", maxBuffer: 10 * 1024 * 1024, ...options },
(error, stdout) => {
if (error) reject(error);
else resolve(String(stdout));
},
);
});
}
function delay(milliseconds: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, milliseconds));
}
async function stopProcess(child: NodeChildProcess.ChildProcess): Promise<void> {
if (child.exitCode !== null || child.signalCode !== null) return;
const exited = new Promise<void>((resolve) => {
child.once("exit", () => resolve());
});
child.kill("SIGTERM");
await Promise.race([exited, delay(5_000)]);
if (child.exitCode !== null || child.signalCode !== null) return;
child.kill("SIGKILL");
await Promise.race([exited, delay(1_000)]);
}
async function waitForPort(port: number, label = "Process", timeoutMs = 60_000): Promise<void> {
const deadline = Date.now() + timeoutMs;
while (Date.now() < deadline) {
const open = await new Promise<boolean>((resolve) => {
const socket = NodeNet.createConnection({ host: "127.0.0.1", port });
socket.once("connect", () => {
socket.destroy();
resolve(true);
});
socket.once("error", () => resolve(false));
socket.setTimeout(500, () => {
socket.destroy();
resolve(false);
});
});
if (open) return;
await delay(500);
}
throw new Error(`${label} did not begin listening on port ${port} within ${timeoutMs}ms.`);
}
async function waitForFileContent(
filePath: string,
label: string,
timeoutMs = 60_000,
): Promise<string> {
const deadline = Date.now() + timeoutMs;
while (Date.now() < deadline) {
const content = await NodeFSP.readFile(filePath, "utf8").then(
(value) => value.trim(),
() => "",
);
if (content) return content;
await delay(250);
}
throw new Error(`${label} was not written to ${filePath} within ${timeoutMs}ms.`);
}
async function reserveAvailablePort(): Promise<number> {
return await new Promise<number>((resolve, reject) => {
const server = NodeNet.createServer();
server.once("error", reject);
server.listen(0, "127.0.0.1", () => {
const address = server.address();
if (!address || typeof address === "string") {
server.close();
reject(new Error("Could not reserve a local port for the showcase environment."));
return;
}
server.close((error) => (error ? reject(error) : resolve(address.port)));
});
});
}
async function createShowcaseShell(baseDir: string): Promise<string> {
const shellPath = NodePath.join(baseDir, "showcase-shell");
await NodeFSP.writeFile(
shellPath,
`#!/bin/sh
if [ "$1" = "-ilc" ] || [ "$1" = "-lic" ]; then
exec /bin/sh -c "$2"
fi
exec /bin/cat
`,
{ mode: 0o755 },
);
return shellPath;
}
async function createShowcaseLabelProbe(baseDir: string, label: string): Promise<string> {
const binDirectory = NodePath.join(baseDir, "showcase-bin");
await NodeFSP.mkdir(binDirectory, { recursive: true });
const probeScript = `#!/bin/sh
if [ "$1" = "--get" ] && [ "$2" = "ComputerName" ]; then
printf '%s\\n' ${JSON.stringify(label)}
exit 0
fi
if [ "$1" = "--pretty" ]; then
printf '%s\\n' ${JSON.stringify(label)}
exit 0
fi
exit 1
`;
await Promise.all(
["scutil", "hostnamectl"].map((executable) =>
NodeFSP.writeFile(NodePath.join(binDirectory, executable), probeScript, { mode: 0o755 }),
),
);
return binDirectory;
}
function startShowcaseServer(
baseDir: string,
workspaceRoot: string,
port: number,
shellPath: string,
labelProbeDirectory: string,
): NodeChildProcess.ChildProcess {
return spawnProcess(
"node",
[
"apps/server/src/bin.ts",
"serve",
"--host",
SERVER_HOST,
"--port",
String(port),
"--base-dir",
baseDir,
"--no-browser",
"--log-level",
"error",
workspaceRoot,
],
{
env: {
...NodeProcess.env,
PATH: `${labelProbeDirectory}:${NodeProcess.env.PATH ?? ""}`,
SHELL: shellPath,
},
},
);
}
export function parsePairingCredentialOutput(output: string): string {
const jsonStart = output.indexOf("{");
const jsonEnd = output.lastIndexOf("}");
if (jsonStart === -1 || jsonEnd < jsonStart) {
throw new Error("Pairing credential command did not return JSON.");
}
const parsed = JSON.parse(output.slice(jsonStart, jsonEnd + 1)) as {
readonly credential?: unknown;
};
if (typeof parsed.credential !== "string" || parsed.credential.length === 0) {
throw new Error("Pairing credential command returned no credential.");
}
return parsed.credential;
}
async function issuePairingCredential(baseDir: string): Promise<string> {
const output = await commandOutput(
"node",
["apps/server/src/bin.ts", "auth", "pairing", "create", "--base-dir", baseDir, "--json"],
{ env: { ...NodeProcess.env, NO_COLOR: "1" } },
);
return parsePairingCredentialOutput(output);
}
function buildShowcasePairingUrl(host: string, port: number, credential: string): string {
const url = new URL(`http://${host}:${port}/`);
url.hash = new URLSearchParams([["token", credential]]).toString();
return url.toString();
}
export function showcaseSceneUrl(scene: ShowcaseScene, environmentId: string): string {
if (scene === "threads") return `${APP_SCHEME}://`;
if (scene === "environments") return `${APP_SCHEME}://settings/environments`;
const threadPath = `threads/${encodeURIComponent(environmentId)}/${SHOWCASE_THREAD_ID}`;
if (scene === "thread") return `${APP_SCHEME}://${threadPath}`;
if (scene === "terminal") {
return `${APP_SCHEME}://${threadPath}/terminal?terminalId=${SHOWCASE_TERMINAL_ID}`;
}
return `${APP_SCHEME}://${threadPath}/review`;
}
export function encodeAndroidPairingUrls(pairingUrls: ReadonlyArray<string>): string {
return `json-uri:${encodeURIComponent(JSON.stringify(pairingUrls))}`;
}
function startMetro(config: ShowcaseConfig): NodeChildProcess.ChildProcess {
return spawnProcess(
"pnpm",
["exec", "expo", "start", "--dev-client", "--port", String(config.metroPort)],
{
cwd: MOBILE_ROOT,
env: {
...MOBILE_BUILD_ENV,
EXPO_PUBLIC_SHOWCASE: "1",
},
},
);
}
async function warmMetroBundle(
platform: ShowcaseDevice["platform"],
host: string,
config: ShowcaseConfig,
): Promise<void> {
const url = `http://${host}:${config.metroPort}/apps/mobile/index.bundle?platform=${platform}&dev=true&minify=false`;
await runCommand("curl", ["--fail", "--silent", "--show-error", "--output", "/dev/null", url]);
}
async function buildIos(): Promise<string> {
const derivedData = NodePath.join(MOBILE_ROOT, ".showcase/ios-derived-data");
await runCommand("pnpm", ["exec", "expo", "prebuild", "--clean", "--platform", "ios"], {
cwd: MOBILE_ROOT,
env: MOBILE_BUILD_ENV,
});
await runCommand(
"xcodebuild",
[
"-workspace",
NodePath.join(MOBILE_ROOT, "ios/T3Code.xcworkspace"),
"-scheme",
"T3Code",
"-configuration",
"Debug",
"-sdk",
"iphonesimulator",
"-derivedDataPath",
derivedData,
"-quiet",
`ARCHS=${IOS_SIMULATOR_ARCH}`,
"ONLY_ACTIVE_ARCH=YES",
"build",
],
{ cwd: MOBILE_ROOT, env: MOBILE_BUILD_ENV },
);
return IOS_APP_PATH;
}
async function buildAndroid(abis: ReadonlyArray<string>): Promise<string> {
await runCommand("pnpm", ["exec", "expo", "prebuild", "--clean", "--platform", "android"], {
cwd: MOBILE_ROOT,
env: MOBILE_BUILD_ENV,
});
await runCommand(
"./gradlew",
[
"app:assembleDebug",
...(abis.length > 0 ? [`-PreactNativeArchitectures=${abis.join(",")}`] : []),
],
{
cwd: NodePath.join(MOBILE_ROOT, "android"),
env: MOBILE_BUILD_ENV,
},
);
return ANDROID_APK_PATH;
}
async function existingArtifact(path: string): Promise<string | null> {
return await NodeFSP.access(path).then(
() => path,
() => null,
);
}
interface SimctlDevice {
readonly name: string;
readonly udid: string;
readonly state: "Booted" | "Shutdown" | string;
readonly isAvailable: boolean;
}
async function findIosSimulator(name: string): Promise<SimctlDevice | null> {
const parsed = JSON.parse(
await commandOutput("xcrun", ["simctl", "list", "devices", "available", "-j"]),
) as {
readonly devices: Readonly<Record<string, ReadonlyArray<SimctlDevice>>>;
};
const candidates = Object.entries(parsed.devices)
.filter(([runtime]) => runtime.includes("iOS"))
.flatMap(([, devices]) => devices)
.filter((device) => device.isAvailable && device.name === name);
return candidates.at(-1) ?? null;
}
async function ensureIosSimulator(device: ShowcaseIosDevice): Promise<{
readonly simulator: SimctlDevice;
readonly createdByRunner: boolean;
}> {
const existing = await findIosSimulator(device.simulator);
if (existing) return { simulator: existing, createdByRunner: false };
if (!device.simulatorDeviceType) {
throw new Error(
`iOS simulator '${device.simulator}' is not installed and has no simulatorDeviceType configured.`,
);
}
const udid = (
await commandOutput("xcrun", ["simctl", "create", device.simulator, device.simulatorDeviceType])
).trim();
if (!udid) throw new Error(`Could not create iOS simulator '${device.simulator}'.`);
return {
simulator: {
name: device.simulator,
udid,
state: "Shutdown",
isAvailable: true,
},
createdByRunner: true,
};
}
async function iosSimulatorDataPath(udid: string): Promise<string> {
const parsed = JSON.parse(await commandOutput("xcrun", ["simctl", "list", "devices", "-j"])) as {
readonly devices: Readonly<
Record<string, ReadonlyArray<SimctlDevice & { readonly dataPath: string }>>
>;
};
const dataPath = Object.values(parsed.devices)
.flat()
.find((device) => device.udid === udid)?.dataPath;
if (!dataPath) throw new Error(`Could not resolve the data path of iOS simulator ${udid}.`);
return dataPath;
}
// generativeexperiencesd posts a "Ready for Apple Intelligence" follow-up
// banner on an eligible device's first boot, and CoreFollowUp re-surfaces it
// on every boot until the user dismisses it. Stamping the readiness marker
// before boot makes the daemon skip the post, and dropping the CoreFollowUp
// store clears a banner that a previous boot already queued. Runs while the
// device is shut down so the files are read fresh on the next boot.
async function suppressIosSystemFollowUps(udid: string): Promise<void> {
const dataPath = await iosSimulatorDataPath(udid);
const preferences = NodePath.join(dataPath, "Library/Preferences");
await NodeFSP.mkdir(preferences, { recursive: true });
await NodeFSP.writeFile(
NodePath.join(preferences, "com.apple.generativeexperiences.corefollowup.plist"),
`<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
\t<key>DateOfLastAppleIntelligenceReadinessCFU</key>
\t<date>2020-01-01T00:00:00Z</date>
</dict>
</plist>
`,
);
await NodeFSP.rm(NodePath.join(dataPath, "Library/CoreFollowUp"), {
recursive: true,
force: true,
});
}
async function normalizeIosSimulator(appearance: ShowcaseAppearance, udid: string): Promise<void> {
await runCommand("xcrun", ["simctl", "ui", udid, "appearance", appearance]);
await runCommand("xcrun", [
"simctl",
"status_bar",
udid,
"override",
"--time",
"9:41",
"--batteryState",
"charged",
"--batteryLevel",
"100",
"--wifiBars",
"3",
"--cellularBars",
"4",
]);
}
// iPadOS 26 windowing ("Chamois") runs UIRequiresFullScreen apps in a fixed
// portrait compatibility window, which defeats the in-app landscape rotation
// the capture build relies on. Switch the device to Full Screen Apps mode
// (Settings > Multitasking & Gestures) and restart SpringBoard to apply it.
async function ensureIosFullScreenAppsMode(udid: string): Promise<void> {
const current = await commandOutput("xcrun", [
"simctl",
"spawn",
udid,
"defaults",
"read",
"com.apple.springboard",
"SBChamoisWindowingEnabled",
]).catch(() => "");
if (current.trim() === "0") return;
// The Settings toggle writes all three keys; SBChamoisWindowingEnabled
// alone is not honored on a freshly created device.
for (const key of [
"SBChamoisWindowingEnabled",
"SBMedusaMultitaskingEnabled",
"SBFlexibleWindowingPreviouslyEnabledAutomaticStageCreation",
]) {
await runCommand("xcrun", [
"simctl",
"spawn",
udid,
"defaults",
"write",
"com.apple.springboard",
key,
"-bool",
"false",
]);
}
// A SpringBoard restart is not enough on a freshly created simulator (the
// first CI run captured with windowing still active), so reboot the device
// and verify the mode actually stuck.
await runCommand("xcrun", ["simctl", "shutdown", udid]);
await runCommand("xcrun", ["simctl", "boot", udid]);
await runCommand("xcrun", ["simctl", "bootstatus", udid, "-b"]);
const applied = await commandOutput("xcrun", [
"simctl",
"spawn",
udid,
"defaults",
"read",
"com.apple.springboard",
"SBChamoisWindowingEnabled",
]).catch(() => "");
if (applied.trim() !== "0") {
throw new Error(`Simulator ${udid} did not switch to Full Screen Apps mode.`);
}
}
async function iosAppContainer(udid: string): Promise<string> {
return (
await commandOutput("xcrun", ["simctl", "get_app_container", udid, ANDROID_PACKAGE, "data"])
).trim();
}
async function waitForIosShowcaseScene(
udid: string,
scene: ShowcaseScene,
timeoutMs = 90_000,
): Promise<void> {
const readyPath = NodePath.join(
await iosAppContainer(udid),
"Library/Caches",
IOS_READY_FILENAME,
);
const deadline = Date.now() + timeoutMs;
while (Date.now() < deadline) {
const readyScene = await NodeFSP.readFile(readyPath, "utf8").catch(() => "");
if (readyScene.trim() === scene) return;
await delay(500);
}
throw new Error(`iOS showcase scene '${scene}' did not render within ${timeoutMs}ms.`);
}
async function captureIos(
capture: ShowcaseCapture & { readonly device: ShowcaseIosDevice },
appPath: string | null,
outputDirectory: string,
config: ShowcaseConfig,
metroHost: string,
pairingUrls: ReadonlyArray<string>,
registerCleanup: (cleanup: IosCaptureCleanup) => void,
): Promise<void> {
const { simulator, createdByRunner } = await ensureIosSimulator(capture.device);
const startedByRunner = simulator.state !== "Booted";
registerCleanup({ udid: simulator.udid, startedByRunner, createdByRunner });
if (!startedByRunner) {
// Clear transient SpringBoard state (permission prompts, stale URL-open
// confirmations, keyboards) without erasing the developer's simulator.
await runCommand("xcrun", ["simctl", "shutdown", simulator.udid]);
}
await suppressIosSystemFollowUps(simulator.udid);
await runCommand("xcrun", ["simctl", "boot", simulator.udid]);
await runCommand("xcrun", ["simctl", "bootstatus", simulator.udid, "-b"]);
if (capture.device.orientation === "landscape") {
await ensureIosFullScreenAppsMode(simulator.udid);
}
await normalizeIosSimulator(capture.appearance, simulator.udid);
if (appPath) {
await runCommand("xcrun", ["simctl", "uninstall", simulator.udid, ANDROID_PACKAGE]).catch(
() => undefined,
);
await runCommand("xcrun", ["simctl", "install", simulator.udid, appPath]);
}
for (const [key, value] of [
["EXDevMenuIsOnboardingFinished", "true"],
["EXDevMenuShowFloatingActionButton", "false"],
["EXDevMenuShowsAtLaunch", "false"],
] as const) {
await runCommand("xcrun", [
"simctl",
"spawn",
simulator.udid,
"defaults",
"write",
ANDROID_PACKAGE,
key,
"-bool",
value,
]);
}
const metroUrl = `http://${metroHost}:${config.metroPort}?disableOnboarding=1`;
const scenePath = NodePath.join(