Open History to see the last commit
1import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
2import * as NodeServices from "@effect/platform-node/NodeServices";
3import * as HostProcess from "@t3tools/shared/HostProcess";
4import { isCommandAvailable, resolveSpawnCommand } from "@t3tools/shared/shell";
5import * as Console from "effect/Console";
6import * as Crypto from "effect/Crypto";
7import * as Effect from "effect/Effect";
8import * as FileSystem from "effect/FileSystem";
9import * as Path from "effect/Path";
10import * as Schema from "effect/Schema";
11import * as Stream from "effect/Stream";
12import { Argument, Command } from "effect/cli";
13import { ChildProcess, ChildProcessSpawner } from "effect/process";
14
15export type NativePlatform = "ios" | "android";
16const NativeClientRecord = Schema.Struct({ fingerprint: Schema.String, binary: Schema.String });
17const encodeRecord = Schema.encodeEffect(Schema.fromJsonString(NativeClientRecord));
18const decodeRecord = Schema.decodeUnknownEffect(Schema.fromJsonString(NativeClientRecord));
19const encodeOutput = Schema.encodeEffect(Schema.fromJsonString(Schema.Unknown));
20const isNotLink = Schema.is(Schema.Struct({ code: Schema.Literal("EINVAL") }));
21const decodeSimulators = Schema.decodeUnknownEffect(
22 Schema.fromJsonString(
23 Schema.Struct({
24 devices: Schema.Record(
25 Schema.String,
26 Schema.Array(Schema.Struct({ udid: Schema.String, state: Schema.String })),
27 ),
28 }),
29 ),
30);
31export type NativeClientRecord = typeof NativeClientRecord.Type;
32export type NativeClientStatus = "compatible" | "missing" | "unknown" | "stale";
33export class NativeClientError extends Schema.TaggedError<NativeClientError>()(
34 "NativeClientError",
35 { message: Schema.String },
36) {}
37
38export function clientStatus(
39 fingerprint: string,
40 binary: string | null,
41 record: NativeClientRecord | null,
42): NativeClientStatus {
43 if (binary === null) return "missing";
44 if (!record || record.binary !== binary) return "unknown";
45 return record.fingerprint === fingerprint ? "compatible" : "stale";
46}
47
48/** Keep native sources stable during ensure, as with a normal build; endpoint checks reject detected edits. */
49export const ensureClient = Effect.fn("ensureClient")(function* <E, R, E2, R2>(operations: {
50 fingerprint: Effect.Effect<string, E, R>;
51 installedBinary: Effect.Effect<string | null, E, R>;
52 readRecord: Effect.Effect<NativeClientRecord | null, E, R>;
53 build: Effect.Effect<void, E, R>;
54 saveRecord: (record: NativeClientRecord) => Effect.Effect<void, E2, R2>;
55}) {
56 const fingerprint = yield* operations.fingerprint;
57 const status = clientStatus(
58 fingerprint,
59 yield* operations.installedBinary,
60 yield* operations.readRecord,
61 );
62 const verifyInputs = Effect.gen(function* () {
63 if ((yield* operations.fingerprint) !== fingerprint) {
64 return yield* new NativeClientError({
65 message:
66 "Native inputs changed during verification. Run ensure again; this build was not recorded.",
67 });
68 }
69 });
70 yield* verifyInputs;
71 if (status === "compatible") {
72 return { status, rebuilt: false, fingerprint };
73 }
74 yield* operations.build;
75 const binary = yield* operations.installedBinary;
76 if (binary === null)
77 return yield* new NativeClientError({
78 message: "Build finished but the development client is not installed.",
79 });
80 yield* verifyInputs;
81 yield* operations.saveRecord({ fingerprint, binary });
82 return { status: "compatible" as const, rebuilt: true, fingerprint };
83});
84
85const digest = Effect.fn("nativeClient.digest")(function* (value: string | Uint8Array) {
86 const crypto = yield* Crypto.Crypto;
87 const bytes = yield* crypto.digest(
88 "SHA-256",
89 typeof value === "string" ? new TextEncoder().encode(value) : value,
90 );
91 return Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
92});
93
94/** Hash fixed-size chunks to bound memory, including resources and symlink targets. */
95export const hashBundle = Effect.fn("hashBundle")(function* (root: string) {
96 const fs = yield* FileSystem.FileSystem;
97 const path = yield* Path.Path;
98 const entries: string[] = [];
99 const visit = Effect.fn("mobile-native-client.visit")(function* (
100 relative: string,
101 ): Effect.fn.Return<void, FileSystemError, FileSystem.FileSystem | Crypto.Crypto> {
102 const names = (yield* fs.readDirectory(path.join(root, relative))).sort((a, b) =>
103 a.localeCompare(b, "en"),
104 );
105 for (const name of names) {
106 const key = path.join(relative, name);
107 const absolute = path.join(root, key);
108 // FileSystem.stat follows links; readLink distinguishes them without following a cycle.
109 const link = yield* fs.readLink(absolute).pipe(
110 Effect.catchIf(
111 (error) => isNotLink(error.reason.cause),
112 () => Effect.succeed(null),
113 ),
114 );
115 if (link !== null) {
116 entries.push(`link:${key}:${link}`);
117 continue;
118 }
119 const info = yield* fs.stat(absolute);
120 if (info.type === "Directory") {
121 entries.push(`directory:${key}`);
122 yield* visit(key);
123 } else {
124 const chunks = yield* fs.stream(absolute, { chunkSize: 65536 }).pipe(
125 Stream.mapEffect((chunk) => digest(chunk)),
126 Stream.runCollect,
127 );
128 entries.push(`file:${key}:${yield* digest(chunks.join("\n"))}`);
129 }
130 }
131 });
132 yield* visit("");
133 return yield* digest(entries.map((entry) => `${entry.length}:${entry}`).join(""));
134});
135type FileSystemError = import("effect/PlatformError").PlatformError;
136
137const bundleId = "com.t3tools.t3code.dev";
138const roots = Effect.gen(function* () {
139 const path = yield* Path.Path;
140 const repo = yield* path.fromFileUrl(new URL("../", import.meta.url));
141 return { repo, mobile: path.join(repo, "apps/mobile") };
142});
143const collect = <E>(stream: Stream.Stream<Uint8Array, E>) =>
144 stream.pipe(
145 Stream.decodeText(),
146 Stream.runFold(
147 () => "",
148 (a, b) => a + b,
149 ),
150 );
151export const resolveAdb = Effect.gen(function* () {
152 if (yield* isCommandAvailable("adb")) return "adb";
153 const environment = yield* HostProcess.Environment;
154 const path = yield* Path.Path;
155 const executable = (yield* HostProcess.Platform) === "win32" ? "adb.exe" : "adb";
156 for (const sdk of [environment.ANDROID_SDK_ROOT, environment.ANDROID_HOME]) {
157 if (!sdk) continue;
158 const candidate = path.join(sdk, "platform-tools", executable);
159 if (yield* isCommandAvailable(candidate)) return candidate;
160 }
161 return yield* new NativeClientError({
162 message:
163 "adb was not found on PATH or in ANDROID_SDK_ROOT/ANDROID_HOME. Install Android SDK platform-tools.",
164 });
165});
166
167const command = Effect.fn("nativeClient.command")(function* (
168 program: string,
169 args: string[],
170 inherit = false,
171 cwd?: string,
172) {
173 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
174 const environment = yield* HostProcess.Environment;
175 const spawn = yield* resolveSpawnCommand(program === "adb" ? yield* resolveAdb : program, args);
176 const child = yield* spawner.spawn(
177 ChildProcess.make(spawn.command, spawn.args, {
178 shell: spawn.shell,
179 cwd: cwd ?? (yield* roots).mobile,
180 env: {
181 ...environment,
182 APP_VARIANT: "development",
183 MOBILE_VERSION_POLICY: "appVersion",
184 T3CODE_IOS_PERSONAL_TEAM: "0",
185 CI: "1",
186 EXPO_NO_GIT_STATUS: "1",
187 },
188 stdin: "ignore",
189 stdout: inherit ? "inherit" : "pipe",
190 stderr: inherit ? "inherit" : "pipe",
191 }),
192 );
193 const [stdout, stderr, code] = yield* Effect.all(
194 [collect(child.stdout), collect(child.stderr), child.exitCode],
195 { concurrency: "unbounded" },
196 );
197 if (code !== 0)
198 return yield* new NativeClientError({
199 message: `${program} ${args[0]} failed (${code}): ${stderr || "see build output"}`,
200 });
201 return stdout.trim();
202}, Effect.scoped);
203
204const fingerprint = Effect.fn("nativeClient.fingerprint")(function* (platform: NativePlatform) {
205 const output = yield* command(yield* HostProcess.ExecutablePath, [
206 "--eval",
207 `require('expo/fingerprint').createFingerprintAsync(process.cwd(), { platforms: [process.argv[1]], silent: true }).then(fp => console.log('T3_NATIVE_FINGERPRINT=' + fp.hash)).catch(e => { console.error(e); process.exitCode = 1; });`,
208 platform,
209 ]);
210 const hash = output
211 .split("\n")
212 .find((line) => line.startsWith("T3_NATIVE_FINGERPRINT="))
213 ?.split("=")[1];
214 if (!hash || !/^[a-f0-9]{40,64}$/.test(hash))
215 return yield* new NativeClientError({ message: "Expo did not return a native fingerprint." });
216 return hash;
217});
218
219const validateDevice = Effect.fn("nativeClient.validateDevice")(function* (
220 platform: NativePlatform,
221 device: string,
222) {
223 if (platform === "ios") {
224 if ((yield* HostProcess.Platform) !== "darwin")
225 return yield* new NativeClientError({
226 message: "Run iOS check/ensure on the Mac that hosts the simulator.",
227 });
228 const listing = yield* decodeSimulators(
229 yield* command("xcrun", ["simctl", "list", "devices", "available", "--json"]),
230 );
231 const simulator = Object.values(listing.devices)
232 .flat()
233 .find((entry) => entry.udid === device);
234 if (!simulator)
235 return yield* new NativeClientError({
236 message: `No available iOS simulator with UDID ${device}.`,
237 });
238 if (simulator.state !== "Booted")
239 return yield* new NativeClientError({
240 message: `Boot the selected simulator first: xcrun simctl boot ${device}`,
241 });
242 } else {
243 if ((yield* command("adb", ["-s", device, "get-state"])) !== "device")
244 return yield* new NativeClientError({ message: "Android device is not connected." });
245 if ((yield* command("adb", ["-s", device, "shell", "getprop", "ro.kernel.qemu"])) !== "1")
246 return yield* new NativeClientError({
247 message: "Select an Android emulator, not a physical device.",
248 });
249 }
250});
251
252export const installedBinary = Effect.fn("installedBinary")(function* (
253 platform: NativePlatform,
254 device: string,
255 run: typeof command = command,
256) {
257 if (platform === "ios") {
258 const apps = yield* run("xcrun", ["simctl", "listapps", device]);
259 if (!apps.includes(`"${bundleId}"`)) return null;
260 return yield* hashBundle(
261 yield* run("xcrun", ["simctl", "get_app_container", device, bundleId, "app"]),
262 );
263 }
264 const installed = yield* run("adb", ["-s", device, "shell", "pm", "list", "packages", bundleId]);
265 if (!installed.split("\n").some((line) => line.trim() === `package:${bundleId}`)) return null;
266 const packages = yield* run("adb", ["-s", device, "shell", "pm", "path", bundleId]);
267 const apks = packages
268 .split("\n")
269 .filter((line) => line.startsWith("package:"))
270 .map((line) => line.slice(8).trim())
271 .sort();
272 if (apks.length === 0) return null;
273 const hashes = yield* Effect.forEach(apks, (apk) =>
274 Effect.gen(function* () {
275 if (!/^\/[\w/+=.~-]+\.apk$/.test(apk))
276 return yield* new NativeClientError({ message: "Unexpected installed APK path." });
277 const hash = (yield* run("adb", ["-s", device, "shell", "sha256sum", apk])).split(/\s/)[0];
278 if (!hash || !/^[a-f0-9]{64}$/.test(hash))
279 return yield* new NativeClientError({ message: "Could not hash installed APK." });
280 return hash;
281 }),
282 );
283 return yield* digest(hashes.sort().join("\n"));
284});
285
286/**
287 * Run `expo prebuild --clean` without losing `android/.gradle` (task history) and
288 * `android/app/.cxx` (native compile outputs). Both invalidate by input, so a clean
289 * rebuild only redoes changed work. `app/build` stays out: its autolinking and JS
290 * bundle tasks do not declare every input. Each step is best-effort, because a lost
291 * cache costs one slower build and must never cost the build.
292 */
293export const prebuildAndroid = Effect.fn("nativeClient.prebuildAndroid")(function* <E, R>(
294 mobile: string,
295 prebuild: Effect.Effect<void, E, R>,
296) {
297 const fs = yield* FileSystem.FileSystem;
298 const path = yield* Path.Path;
299 const android = path.join(mobile, "android");
300 // A sibling of android/ keeps the renames on one filesystem. It is gitignored, and a
301 // run killed mid-prebuild leaves it for the next run to clear.
302 const saved = path.join(mobile, ".android-cache");
303 const caches = [".gradle", "app/.cxx"];
304 const clear = fs.remove(saved, { recursive: true, force: true }).pipe(Effect.ignore);
305 const move = (from: string, to: string) =>
306 Effect.forEach(
307 caches,
308 (cache) =>
309 Effect.gen(function* () {
310 const source = path.join(from, cache);
311 const target = path.join(to, cache);
312 if (!(yield* fs.exists(source)) || (yield* fs.exists(target))) return;
313 yield* fs.makeDirectory(path.dirname(target), { recursive: true });
314 yield* fs.rename(source, target);
315 }).pipe(Effect.ignore),
316 { discard: true },
317 );
318 yield* Effect.acquireUseRelease(
319 clear.pipe(Effect.andThen(move(android, saved))),
320 () => prebuild,
321 () => move(saved, android).pipe(Effect.andThen(clear)),
322 );
323});
324
325const main = Command.make(
326 "mobile-native-client",
327 {
328 mode: Argument.Literals("mode", ["check", "ensure"]),
329 platform: Argument.Literals("platform", ["ios", "android"]),
330 device: Argument.String("device"),
331 },
332 Effect.fn("nativeClient.main")(function* ({ mode, platform, device }) {
333 yield* validateDevice(platform, device);
334 const fs = yield* FileSystem.FileSystem;
335 const path = yield* Path.Path;
336 const environment = yield* HostProcess.Environment;
337 const home = environment.HOME ?? environment.USERPROFILE;
338 if (!home)
339 return yield* new NativeClientError({
340 message: "HOME or USERPROFILE must be set to store native client records.",
341 });
342 const recordPath = path.join(
343 home,
344 ".cache/t3code/native-clients",
345 platform,
346 `${yield* digest(device)}.json`,
347 );
348 const operations = {
349 fingerprint: fingerprint(platform),
350 installedBinary: installedBinary(platform, device),
351 readRecord: fs.readFileString(recordPath).pipe(
352 Effect.flatMap(decodeRecord),
353 Effect.catchTags({ SchemaError: () => Effect.succeed(null) }),
354 Effect.catchIf(
355 (error) => error.reason._tag === "NotFound",
356 () => Effect.succeed(null),
357 ),
358 ),
359 build: Effect.gen(function* () {
360 yield* Console.error(
361 "Native client is missing, stale, or unverified. Building and installing a development client...",
362 );
363 const tracked = yield* command(
364 "git",
365 ["ls-files", `apps/mobile/${platform}`],
366 false,
367 (yield* roots).repo,
368 );
369 if (tracked)
370 return yield* new NativeClientError({
371 message:
372 "Native directory contains tracked files; clean prebuild would overwrite them.",
373 });
374 const prebuild = command(
375 "vp",
376 ["exec", "expo", "prebuild", "--clean", "--platform", platform, "--no-install"],
377 true,
378 ).pipe(Effect.asVoid);
379 yield* platform === "android" ? prebuildAndroid((yield* roots).mobile, prebuild) : prebuild;
380 if (platform === "ios") {
381 const output = yield* fs.makeTempDirectoryScoped({ prefix: "t3-native-client-" });
382 const { mobile } = yield* roots;
383 yield* command("pod", ["install"], true, path.join(mobile, "ios"));
384 yield* command(
385 "xcrun",
386 [
387 "xcodebuild",
388 "-workspace",
389 path.join(mobile, "ios/T3CodeDev.xcworkspace"),
390 "-scheme",
391 "T3CodeDev",
392 "-configuration",
393 "Debug",
394 "-destination",
395 `id=${device}`,
396 "-derivedDataPath",
397 output,
398 "build",
399 ],
400 true,
401 );
402 yield* command(
403 "xcrun",
404 [
405 "simctl",
406 "install",
407 device,
408 path.join(output, "Build/Products/Debug-iphonesimulator/T3CodeDev.app"),
409 ],
410 true,
411 );
412 } else {
413 yield* command(
414 "vp",
415 [
416 "exec",
417 "expo",
418 "run:android",
419 "--device",
420 device,
421 "--no-bundler",
422 "--variant",
423 "debug",
424 ],
425 true,
426 );
427 }
428 }).pipe(Effect.scoped),
429 saveRecord: Effect.fn(function* (record: NativeClientRecord) {
430 yield* fs.makeDirectory(path.dirname(recordPath), { recursive: true });
431 yield* fs.writeFileString(recordPath, yield* encodeRecord(record));
432 }),
433 };
434 if (mode === "ensure") {
435 yield* Console.log(yield* encodeOutput(yield* ensureClient(operations)));
436 } else {
437 const current = yield* operations.fingerprint;
438 const status = clientStatus(
439 current,
440 yield* operations.installedBinary,
441 yield* operations.readRecord,
442 );
443 yield* Console.log(
444 yield* encodeOutput({
445 status,
446 fingerprint: current,
447 next:
448 status === "compatible"
449 ? "Start Metro with vp run dev:client"
450 : `node scripts/mobile-native-client.ts ensure ${platform} ${device}`,
451 }),
452 );
453 process.exitCode = status === "compatible" ? 0 : 2;
454 }
455 }),
456);
457
458if (import.meta.main) {
459 Command.run(main, { version: "0.0.0" }).pipe(
460 Effect.scoped,
461 Effect.provide(NodeServices.layer),
462 NodeRuntime.runMain,
463 );
464}