emd-agents 0.14.0 → 0.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,21 +1,33 @@
1
- import { mkdir, readFile } from "node:fs/promises";
1
+ import { appendFile, mkdir, readFile, realpath, rm, stat, symlink, } from "node:fs/promises";
2
2
  import { homedir } from "node:os";
3
3
  import { basename, join } from "node:path";
4
+ import { builtApp, readBuildRecord, whyBuild, writeBuildRecord, } from "./buildrecord.js";
4
5
  import { detect } from "./detect.js";
6
+ import { axeBackend } from "./device/axe.js";
7
+ import { detectEnvironment, untilReadable } from "./device/backend.js";
5
8
  import { derivedDataPath, diskMB, pickPort, xcodebuildShim, } from "./isolate.js";
6
9
  import { launchesIn } from "./jobstore.js";
7
- import { firstErrors, knownFix, onlyOpenFailed } from "./log.js";
10
+ import { buildTiming, firstErrors, knownFix, onlyOpenFailed } from "./log.js";
8
11
  import { startCapture, stopCaptures } from "./logs.js";
9
12
  import { confirm, reserve, worktreeKey } from "./owned.js";
10
13
  import { startLogged } from "./process.js";
11
14
  import { inspectProject } from "./project.js";
12
15
  import { loadAdapter } from "./registry.js";
13
- import { boot, cloneDevice, launchApp, listDevices, newerThan, pickDevice, removeSimulator, simulatorSdk, } from "./simulator.js";
16
+ import { bundlesServed, earlierLaunch, runningPid, sendReload, untilBundled, } from "./reload.js";
17
+ import { appAccessibilityOn, appInstalled, boot, cloneDevice, enableAppAccessibility, installApp, launchApp, listDevices, newerThan, pickDevice, plainKeyboard, removeSimulator, simulatorSdk, terminateApp, } from "./simulator.js";
14
18
  import { stateDir } from "./state.js";
15
19
  import { runTool } from "./tool.js";
16
20
  const metroStartSeconds = 120;
17
21
  const stopSeconds = 10;
18
22
  const defaultTimeoutSeconds = 900;
23
+ // How long AXe may take to read the screen after the app started, about twice
24
+ // the slowest measurement: first launch 7.8 to 51.4 s on CI iOS 26 and up to
25
+ // 86 s on iOS 27.1; relaunch 5.9 to 31.3 s.
26
+ const screenReadSeconds = 180;
27
+ // An empty tree this long after the app started means accessibility is off.
28
+ const emptyTreeSeconds = 5;
29
+ // How long a reload may take to show a new bundle request in the dev server log.
30
+ const bundleSeconds = 60;
19
31
  const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
20
32
  async function metroRunning(port) {
21
33
  try {
@@ -90,10 +102,75 @@ async function withTimeout(exited, seconds) {
90
102
  }
91
103
  }
92
104
  const logTail = async (path) => firstErrors(await readFile(path, "utf8").catch(() => ""));
105
+ // Runs the build and install. Returns why it failed; undefined when the app is
106
+ // installed.
107
+ async function runBuild(command, cwd, logPath, env, options) {
108
+ const seconds = options.timeoutSeconds ?? defaultTimeoutSeconds;
109
+ const build = startLogged(command, { cwd, logPath, env });
110
+ const outcome = await withTimeout(build.exited, seconds);
111
+ if (outcome === 0)
112
+ return undefined;
113
+ build.kill();
114
+ const text = await readFile(logPath, "utf8").catch(() => "");
115
+ // Expo's own open step timed out after the install; EMD opens the app next.
116
+ if (outcome !== "timeout" && onlyOpenFailed(text))
117
+ return undefined;
118
+ const fix = knownFix(text);
119
+ let reason = `The build failed (exit ${outcome}).`;
120
+ if (outcome === "timeout") {
121
+ reason = `The build did not finish in ${seconds}s.`;
122
+ }
123
+ else if (fix) {
124
+ reason = fix;
125
+ }
126
+ else if (text.includes("\u203a Build Succeeded")) {
127
+ reason = `The app compiled, but the install or open step failed (exit ${outcome}).`;
128
+ }
129
+ return { reason, errors: firstErrors(text) };
130
+ }
131
+ // After a build, xcodebuild's timing from the raw log Expo writes to
132
+ // <app>/.expo/xcodebuild.log (#208): appends the slowest steps to build.log and
133
+ // returns xcodebuild's total. A log older than the build gives nothing.
134
+ export async function recordTiming(root, buildLog, since) {
135
+ const raw = join(root, ".expo", "xcodebuild.log");
136
+ try {
137
+ if ((await stat(raw)).mtimeMs < since)
138
+ return undefined;
139
+ const timing = buildTiming(await readFile(raw, "utf8"));
140
+ if (!timing)
141
+ return undefined;
142
+ const lines = [
143
+ `EMD: xcodebuild took ${timing.seconds ?? "an unknown number of"} s. Its slowest steps:`,
144
+ ...timing.slowest.map((s) => `EMD: ${s.step} (${s.tasks} tasks): ${s.seconds} s`),
145
+ ];
146
+ await appendFile(buildLog, `\n${lines.join("\n")}\n`);
147
+ return timing.seconds;
148
+ }
149
+ catch {
150
+ return undefined;
151
+ }
152
+ }
93
153
  export async function launch(options = {}, report = () => { }) {
94
154
  const started = Date.now();
95
- const seconds = () => Math.round((Date.now() - started) / 100) / 10;
96
- report("checking the project");
155
+ const tenths = (ms) => Math.round(ms / 100) / 10;
156
+ const seconds = () => tenths(Date.now() - started);
157
+ // Seconds each phase took, in order, under a short name (#203). A phase ends
158
+ // when the next one starts or the launch returns. A phase that runs twice adds up.
159
+ const phases = {};
160
+ let current;
161
+ const endPhase = () => {
162
+ if (current) {
163
+ phases[current.name] = tenths((phases[current.name] ?? 0) * 1000 + Date.now() - current.at);
164
+ }
165
+ current = undefined;
166
+ return phases;
167
+ };
168
+ const phase = (name, step) => {
169
+ endPhase();
170
+ current = { name, at: Date.now() };
171
+ report(step);
172
+ };
173
+ phase("project", "checking the project");
97
174
  const detected = await detect(options.dir);
98
175
  const { root } = detected;
99
176
  const unsupported = (reason) => ({
@@ -101,17 +178,25 @@ export async function launch(options = {}, report = () => { }) {
101
178
  root,
102
179
  reason,
103
180
  });
104
- const failed = (reason, rest = {}) => ({ verdict: "failed", root, reason, seconds: seconds(), ...rest });
181
+ const failed = (reason, rest = {}) => ({
182
+ verdict: "failed",
183
+ root,
184
+ reason,
185
+ seconds: seconds(),
186
+ phases: endPhase(),
187
+ ...rest,
188
+ });
105
189
  if (detected.verdict !== "detected" || !detected.stack) {
106
190
  return unsupported("No supported mobile project found here.");
107
191
  }
108
192
  if (!detected.platforms?.includes("ios")) {
109
193
  return unsupported("The project does not target iOS.");
110
194
  }
111
- const appId = detected.appIds?.ios;
112
- if (!appId) {
113
- return unsupported("No iOS app ID found; install the app's dependencies and set ios.bundleIdentifier in the app config.");
114
- }
195
+ // Without an ID, Expo's own build sets one (ios.bundleIdentifier) and the
196
+ // ID is read again after it. EMD writes nothing to the app config.
197
+ if (detected.problem)
198
+ return unsupported(detected.problem);
199
+ let appId = detected.appIds?.ios;
115
200
  if (process.platform !== "darwin") {
116
201
  return unsupported("iOS simulators need macOS.");
117
202
  }
@@ -131,7 +216,7 @@ export async function launch(options = {}, report = () => { }) {
131
216
  // A clone on a runtime newer than the selected Xcode's SDK does not build
132
217
  // (#122). It is EMD's own, so it is replaced, not reused.
133
218
  if (device && sdk && newerThan(device, sdk)) {
134
- report(`replacing the simulator: iOS ${device.version.join(".")} is newer than Xcode's iOS ${sdk.join(".")} SDK`);
219
+ phase("replace", `replacing the simulator: iOS ${device.version.join(".")} is newer than Xcode's iOS ${sdk.join(".")} SDK`);
135
220
  await removeSimulator(device);
136
221
  device = undefined;
137
222
  }
@@ -142,7 +227,7 @@ export async function launch(options = {}, report = () => { }) {
142
227
  ? `No shut-down simulator matches "${options.device}" to clone.`
143
228
  : "No shut-down iPhone simulator is available to clone.");
144
229
  }
145
- report("cloning a simulator");
230
+ phase("clone", "cloning a simulator");
146
231
  const id = await cloneDevice(base, name);
147
232
  device = {
148
233
  id,
@@ -184,7 +269,7 @@ export async function launch(options = {}, report = () => { }) {
184
269
  diskMB: await sizes(),
185
270
  ...rest,
186
271
  });
187
- report("booting the simulator");
272
+ phase("boot", "booting the simulator");
188
273
  try {
189
274
  await boot(device);
190
275
  }
@@ -193,18 +278,99 @@ export async function launch(options = {}, report = () => { }) {
193
278
  errors: String(error).split("\n").slice(0, 3),
194
279
  });
195
280
  }
281
+ // Reuse the installed build when nothing native changed. A fingerprint that
282
+ // cannot be computed means a normal build.
283
+ let fingerprint;
284
+ let why;
285
+ try {
286
+ fingerprint = await (await loadAdapter(detected.stack)).fingerprint(root, "ios");
287
+ }
288
+ catch (error) {
289
+ why = `fingerprint failed: ${String(error).split("\n")[0]}`;
290
+ }
291
+ // A running app, a running dev server of this worktree and an unchanged
292
+ // fingerprint: reload the app. Without a new bundle request in the log the
293
+ // reload did not happen, and the launch goes on as a relaunch.
294
+ let reloadFailed;
295
+ const earlier = fingerprint === undefined
296
+ ? undefined
297
+ : earlierLaunch(root, port, await listeningGroups(port));
298
+ if (earlier?.appId &&
299
+ earlier.logDir &&
300
+ fingerprint !== undefined &&
301
+ whyBuild(readBuildRecord(derivedData), { fingerprint, port }, true) ===
302
+ undefined &&
303
+ (await metroRunning(port))) {
304
+ const pid = await runningPid(device, earlier.appId);
305
+ if (pid !== undefined) {
306
+ phase("reload", "reloading the app");
307
+ const before = await bundlesServed(earlier.logDir);
308
+ // The reload starts a new run, as a relaunch does: its own folder and log
309
+ // window, open before the message so no line of the reloaded app is missed.
310
+ let reloadCapture;
311
+ try {
312
+ await mkdir(logDir, { recursive: true });
313
+ await stopCaptures(root);
314
+ reloadCapture = await startCapture(device.id, earlier.appId, logDir);
315
+ await symlink(await realpath(join(earlier.logDir, "metro.log")), metroLog);
316
+ await sendReload(port);
317
+ if (await untilBundled(earlier.logDir, before, bundleSeconds)) {
318
+ const axe = (await detectEnvironment()).axe;
319
+ phase("screen", "waiting for the screen");
320
+ const screen = axe
321
+ ? await untilReadable(() => axeBackend.readScreen(device.id, axe), screenReadSeconds)
322
+ : undefined;
323
+ return {
324
+ verdict: "launched",
325
+ root,
326
+ ...where,
327
+ appId: earlier.appId,
328
+ ...(screen && { screen }),
329
+ appPid: pid,
330
+ build: { action: "reloaded" },
331
+ ...(earlier.metro && { metro: earlier.metro }),
332
+ logStream: { pid: reloadCapture.pid },
333
+ derivedData,
334
+ diskMB: await sizes(),
335
+ seconds: seconds(),
336
+ phases: endPhase(),
337
+ };
338
+ }
339
+ reloadFailed = `no new bundle request ${bundleSeconds}s after the reload message`;
340
+ }
341
+ catch (error) {
342
+ reloadFailed = `the reload message failed: ${String(error).split("\n")[0]}`;
343
+ }
344
+ reloadCapture?.kill();
345
+ }
346
+ }
347
+ if (reloadFailed !== undefined) {
348
+ // The relaunch writes its own dev server log in the same folder.
349
+ await rm(metroLog, { force: true });
350
+ await rm(join(logDir, "app.ndjson"), { force: true });
351
+ }
196
352
  await stopEarlierServer(root, port);
197
353
  if (await metroRunning(port)) {
198
354
  return stuck(`Port ${port} already serves a dev server. Stop it and retry.`);
199
355
  }
200
356
  await stopCaptures(root);
201
- report("starting the dev server");
357
+ // Runs while the dev server starts, so it costs no time, and ends before the
358
+ // app starts. A failed write is not a launch failure: `type` still checks
359
+ // its text.
360
+ const keyboard = plainKeyboard(device).catch(() => { });
361
+ phase("server", "starting the dev server");
202
362
  const env = {
203
363
  CI: "1",
204
364
  RCT_METRO_PORT: String(port),
205
365
  PATH: `${shimDir}:${process.env.PATH}`,
206
366
  };
207
- const metro = startLogged(plan.server, { cwd: root, logPath: metroLog, env });
367
+ // With CI set Metro does not watch files, so an edit never reaches the next
368
+ // bundle. The server has no terminal (stdin is closed), so it asks nothing.
369
+ const metro = startLogged(plan.server, {
370
+ cwd: root,
371
+ logPath: metroLog,
372
+ env: { ...env, CI: undefined },
373
+ });
208
374
  const metroState = await untilReady(() => metroRunning(port), metro.exited, metroStartSeconds);
209
375
  if (metroState !== "ready") {
210
376
  metro.kill();
@@ -212,62 +378,153 @@ export async function launch(options = {}, report = () => { }) {
212
378
  ? "The dev server exited before it was ready."
213
379
  : `The dev server was not ready after ${metroStartSeconds}s.`, { errors: await logTail(metroLog) });
214
380
  }
381
+ await keyboard;
215
382
  confirm(root, "port");
216
- report("building and installing the app");
217
- const build = startLogged(plan.build, { cwd: root, logPath: buildLog, env });
218
- const outcome = await withTimeout(build.exited, options.timeoutSeconds ?? defaultTimeoutSeconds);
219
- if (outcome !== 0) {
220
- build.kill();
221
- const text = await readFile(buildLog, "utf8").catch(() => "");
222
- // Expo's own open step timed out after the install; EMD opens the app next.
223
- if (outcome === "timeout" || !onlyOpenFailed(text)) {
383
+ if (fingerprint !== undefined) {
384
+ why = whyBuild(readBuildRecord(derivedData), { fingerprint, port }, appId !== undefined && (await appInstalled(device, appId)));
385
+ }
386
+ const reused = why === undefined;
387
+ // Builds and installs the app; returns the launch result when it fails.
388
+ let xcodebuildSeconds;
389
+ const buildApp = async () => {
390
+ phase("build", "building and installing the app");
391
+ const buildStarted = Date.now();
392
+ const failure = await runBuild(plan.build, root, buildLog, env, options);
393
+ xcodebuildSeconds = await recordTiming(root, buildLog, buildStarted);
394
+ if (failure) {
224
395
  metro.kill();
225
- const fix = knownFix(text);
226
- let reason = `The build failed (exit ${outcome}).`;
227
- if (outcome === "timeout") {
228
- reason = `The build did not finish in ${options.timeoutSeconds ?? defaultTimeoutSeconds}s.`;
396
+ return stuck(failure.reason, { errors: failure.errors });
397
+ }
398
+ if (fingerprint !== undefined) {
399
+ try {
400
+ writeBuildRecord(derivedData, { fingerprint, port });
229
401
  }
230
- else if (fix) {
231
- reason = fix;
402
+ catch { }
403
+ }
404
+ };
405
+ // The fingerprint and port match but the app is gone from the simulator: the
406
+ // build in DerivedData installs in seconds. Build only if that is not possible.
407
+ let installedAgain = false;
408
+ if (reused) {
409
+ phase("reuse", "reusing the installed build");
410
+ }
411
+ else {
412
+ const earlierApp = why === "app not installed" && appId !== undefined
413
+ ? builtApp(derivedData)
414
+ : undefined;
415
+ if (earlierApp) {
416
+ phase("install", "installing the earlier build");
417
+ try {
418
+ await installApp(device, earlierApp);
419
+ installedAgain = true;
232
420
  }
233
- else if (text.includes("\u203a Build Succeeded")) {
234
- reason = `The app compiled, but the install or open step failed (exit ${outcome}).`;
421
+ catch (error) {
422
+ why = `app not installed; install failed: ${String(error).split("\n")[0]}`;
235
423
  }
236
- return stuck(reason, { errors: firstErrors(text) });
424
+ }
425
+ if (!installedAgain) {
426
+ const failure = await buildApp();
427
+ if (failure)
428
+ return failure;
237
429
  }
238
430
  }
239
- report("launching the app");
240
- let capture;
241
- try {
242
- capture = await startCapture(device.id, appId, logDir);
431
+ let appIdSet;
432
+ if (appId === undefined) {
433
+ appId = (await detect(root)).appIds?.ios;
434
+ if (appId === undefined) {
435
+ metro.kill();
436
+ return stuck("The build finished, but the app config still has no iOS app ID. Expo may have built from an existing ios/ project.", { errors: await logTail(buildLog) });
437
+ }
438
+ appIdSet = appId;
439
+ // The config changed, so the fingerprint did too. A failure here only costs
440
+ // one rebuild on the next launch.
441
+ try {
442
+ fingerprint = await (await loadAdapter(detected.stack)).fingerprint(root, "ios");
443
+ writeBuildRecord(derivedData, { fingerprint, port });
444
+ }
445
+ catch { }
243
446
  }
244
- catch (error) {
447
+ const captureFailed = (error) => {
245
448
  metro.kill();
246
449
  return stuck("Built, but could not capture the app's log.", {
247
450
  errors: String(error).split("\n").slice(0, 3),
248
451
  });
452
+ };
453
+ phase("open", "launching the app");
454
+ let capture;
455
+ try {
456
+ capture = await startCapture(device.id, appId, logDir);
457
+ }
458
+ catch (error) {
459
+ if (!reused && !installedAgain)
460
+ return captureFailed(error);
461
+ // The reused or installed build's app cannot be read: build once and try again.
462
+ why = "installed app could not be read";
463
+ installedAgain = false;
464
+ const failure = await buildApp();
465
+ if (failure)
466
+ return failure;
467
+ phase("open", "launching the app");
468
+ try {
469
+ capture = await startCapture(device.id, appId, logDir);
470
+ }
471
+ catch (again) {
472
+ return captureFailed(again);
473
+ }
249
474
  }
250
475
  let appPid;
251
476
  try {
477
+ // A running app still talks to the dev server it started with; a restart
478
+ // makes it load the new JavaScript from this one.
479
+ if (why === undefined)
480
+ await terminateApp(device, appId);
252
481
  appPid = await launchApp(device, appId);
253
482
  }
254
483
  catch (error) {
255
484
  capture.kill();
256
485
  metro.kill();
257
- return stuck(`Built, but launching ${appId} failed.`, {
486
+ return stuck(`${why === undefined ? "Reused the build" : "Built"}, but launching ${appId} failed.`, {
258
487
  errors: String(error).split("\n").slice(0, 3),
259
488
  });
260
489
  }
490
+ const axe = (await detectEnvironment()).axe;
491
+ phase("screen", "waiting for the screen");
492
+ // This device is EMD's own clone. On some iOS versions AXe reads an empty
493
+ // tree until application accessibility is on, and only an app that starts
494
+ // after the write sees it. An AXe error never triggers the write.
495
+ const screen = axe
496
+ ? await untilReadable(() => axeBackend.readScreen(device.id, axe), screenReadSeconds, {
497
+ afterSeconds: emptyTreeSeconds,
498
+ act: async () => {
499
+ if (await appAccessibilityOn(device))
500
+ return;
501
+ await enableAppAccessibility(device);
502
+ await terminateApp(device, appId);
503
+ appPid = await launchApp(device, appId);
504
+ },
505
+ })
506
+ : undefined;
261
507
  return {
262
508
  verdict: "launched",
263
509
  root,
264
510
  ...where,
265
511
  appId,
512
+ ...(appIdSet && { appIdSet }),
513
+ ...(reloadFailed && { reloadFailed }),
514
+ ...(screen && { screen }),
266
515
  appPid,
516
+ build: why === undefined
517
+ ? { action: "reused" }
518
+ : {
519
+ action: installedAgain ? "installed" : "built",
520
+ reason: why,
521
+ ...(xcodebuildSeconds !== undefined && { xcodebuildSeconds }),
522
+ },
267
523
  metro: { pid: metro.pid, port },
268
524
  logStream: { pid: capture.pid },
269
525
  derivedData,
270
526
  diskMB: await sizes(),
271
527
  seconds: seconds(),
528
+ phases: endPhase(),
272
529
  };
273
530
  }
@@ -3,3 +3,12 @@ export declare const stripAnsi: (text: string) => string;
3
3
  export declare function firstErrors(log: string, max?: number): string[];
4
4
  export declare function knownFix(log: string): string | undefined;
5
5
  export declare function onlyOpenFailed(log: string): boolean;
6
+ export type BuildTiming = {
7
+ seconds?: number;
8
+ slowest: {
9
+ step: string;
10
+ tasks: number;
11
+ seconds: number;
12
+ }[];
13
+ };
14
+ export declare function buildTiming(log: string, top?: number): BuildTiming | undefined;
package/dist/core/log.js CHANGED
@@ -52,3 +52,25 @@ export function onlyOpenFailed(log) {
52
52
  /^Error: xcrun simctl openurl /m.test(text) &&
53
53
  text.indexOf("\nError: ") === text.indexOf("\nError: xcrun simctl openurl "));
54
54
  }
55
+ const timingLine = /^(.+?) \((\d+) tasks?\) \| ([\d.]+) seconds?$/;
56
+ const buildEnd = /\*\* BUILD (?:SUCCEEDED|FAILED) \*\* \[([\d.]+) sec\]/;
57
+ export function buildTiming(log, top = 5) {
58
+ const lines = stripAnsi(log)
59
+ .split("\n")
60
+ .map((line) => line.trim());
61
+ const steps = lines.flatMap((line) => {
62
+ const m = line.match(timingLine);
63
+ return m
64
+ ? [{ step: m[1] ?? "", tasks: Number(m[2]), seconds: Number(m[3]) }]
65
+ : [];
66
+ });
67
+ const total = lines
68
+ .map((line) => line.match(buildEnd)?.[1])
69
+ .findLast(Boolean);
70
+ if (steps.length === 0 && total === undefined)
71
+ return undefined;
72
+ return {
73
+ ...(total !== undefined && { seconds: Number(total) }),
74
+ slowest: steps.sort((a, b) => b.seconds - a.seconds).slice(0, top),
75
+ };
76
+ }
@@ -0,0 +1,7 @@
1
+ import type { LaunchResult } from "./result.js";
2
+ import type { Device } from "./simulator.js";
3
+ export declare function sendReload(port: number): Promise<void>;
4
+ export declare function runningPid(device: Device, appId: string): Promise<number | undefined>;
5
+ export declare const earlierLaunch: (root: string, port: number, listening: number[]) => LaunchResult | undefined;
6
+ export declare function untilBundled(logDir: string, before: number, seconds: number): Promise<boolean>;
7
+ export declare const bundlesServed: (logDir: string) => Promise<number>;
@@ -0,0 +1,68 @@
1
+ import { readFile } from "node:fs/promises";
2
+ import { basename, join } from "node:path";
3
+ import { launchesIn } from "./jobstore.js";
4
+ import { runTool } from "./tool.js";
5
+ // The same message Expo's R key broadcasts to connected apps: the dev server's
6
+ // message socket relays a "reload" from a local client to every app.
7
+ export async function sendReload(port) {
8
+ const socket = new WebSocket(`ws://localhost:${port}/message`);
9
+ await new Promise((resolve, reject) => {
10
+ const timer = setTimeout(() => reject(new Error("socket timeout")), 5000);
11
+ socket.onopen = () => {
12
+ socket.send(JSON.stringify({ version: 2, method: "reload" }));
13
+ clearTimeout(timer);
14
+ resolve();
15
+ };
16
+ socket.onerror = () => {
17
+ clearTimeout(timer);
18
+ reject(new Error("socket error"));
19
+ };
20
+ });
21
+ // The server answers the close; a silent one must not hold this process.
22
+ await new Promise((resolve) => {
23
+ socket.onclose = () => resolve();
24
+ socket.close();
25
+ setTimeout(resolve, 1000).unref();
26
+ });
27
+ }
28
+ // The pid of the app when it runs on the device; undefined when it does not.
29
+ export async function runningPid(device, appId) {
30
+ try {
31
+ const { stdout } = await runTool("simctl spawn launchctl list", "xcrun", ["simctl", "spawn", device.id, "launchctl", "list"], 60);
32
+ const mark = `UIKitApplication:${appId}[`;
33
+ for (const line of stdout.split("\n")) {
34
+ if (!line.includes(mark))
35
+ continue;
36
+ const pid = Number(line.trim().split(/\s+/)[0]);
37
+ return Number.isInteger(pid) ? pid : undefined;
38
+ }
39
+ }
40
+ catch { }
41
+ return undefined;
42
+ }
43
+ // The earlier launch in this worktree whose dev server still listens on `port`,
44
+ // or undefined. `listening` tells which recorded dev server pids do.
45
+ export const earlierLaunch = (root, port, listening) =>
46
+ // Reloads share one dev server, so the newest run (its folder name starts
47
+ // with its start time) is the one whose log window is open.
48
+ launchesIn(root)
49
+ .filter(({ verdict, metro, device, logDir }) => verdict === "launched" &&
50
+ metro?.port === port &&
51
+ listening.includes(metro.pid) &&
52
+ device &&
53
+ logDir)
54
+ .sort((a, b) => basename(b.logDir ?? "").localeCompare(basename(a.logDir ?? "")))[0];
55
+ const bundled = /Bundled \d+ms/g;
56
+ const count = async (path) => ((await readFile(path, "utf8").catch(() => "")).match(bundled) ?? []).length;
57
+ // Resolves when the dev server log shows a bundle served after `before` bundles.
58
+ export async function untilBundled(logDir, before, seconds) {
59
+ const path = join(logDir, "metro.log");
60
+ const deadline = Date.now() + seconds * 1000;
61
+ while (Date.now() < deadline) {
62
+ if ((await count(path)) > before)
63
+ return true;
64
+ await new Promise((resolve) => setTimeout(resolve, 500));
65
+ }
66
+ return false;
67
+ }
68
+ export const bundlesServed = (logDir) => count(join(logDir, "metro.log"));