stim 0.0.0 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (80) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +162 -0
  3. package/dist/android-CC5bUer7.mjs +204 -0
  4. package/dist/android-DnZlT3aU.mjs +2279 -0
  5. package/dist/android-cas-DGlTStWu.mjs +1078 -0
  6. package/dist/android-cas-compiler.d.mts +1 -0
  7. package/dist/android-cas-compiler.mjs +71 -0
  8. package/dist/android-xmyGBNy5.mjs +665 -0
  9. package/dist/app-install-oZIQRbdD.mjs +1141 -0
  10. package/dist/build-lock-vE45ZzJZ.mjs +645 -0
  11. package/dist/build-slots-CgacA9zQ.mjs +152 -0
  12. package/dist/cache-manifest-oeH18ERr.mjs +66 -0
  13. package/dist/cache-manifest.d.mts +27 -0
  14. package/dist/cache-manifest.mjs +2 -0
  15. package/dist/cli.d.mts +1 -0
  16. package/dist/cli.mjs +40 -0
  17. package/dist/collector-run.d.mts +119 -0
  18. package/dist/collector-run.mjs +541 -0
  19. package/dist/command-output-8wHMEde0.mjs +289 -0
  20. package/dist/config-D7uu8Gbq.mjs +381 -0
  21. package/dist/deps-64wVnpZc.mjs +435 -0
  22. package/dist/dev-client-Bvky1hya.mjs +557 -0
  23. package/dist/device-DJKv5Qej.mjs +250 -0
  24. package/dist/device-lease-D-G3SgVe.mjs +335 -0
  25. package/dist/device-pool-BlHXnYYs.mjs +408 -0
  26. package/dist/device-remote-CCgkG82J.mjs +1209 -0
  27. package/dist/doctor-BRF9aAJ3.mjs +530 -0
  28. package/dist/doctor-DlVxTtMq.mjs +1137 -0
  29. package/dist/error-diagnostics-B5IJwv3-.mjs +636 -0
  30. package/dist/errors-B6W7FkxQ.mjs +15 -0
  31. package/dist/exec-bsN9MJXb.mjs +63 -0
  32. package/dist/gc-DhXdgSdt.mjs +1651 -0
  33. package/dist/guide-DrhrDBo5.mjs +4319 -0
  34. package/dist/ios-BZxKPuqP.mjs +382 -0
  35. package/dist/ios-CK1Vrk6Q.mjs +2721 -0
  36. package/dist/ios-device-CYbuRNXR.mjs +81 -0
  37. package/dist/ios-device-CdSm0GDw.mjs +413 -0
  38. package/dist/logs-Dxoy16Qv.mjs +176 -0
  39. package/dist/logs-query-oqn47Ffx.mjs +273 -0
  40. package/dist/metro-B01H3EuD.mjs +184 -0
  41. package/dist/metro-store-CDDZHtPl.mjs +92 -0
  42. package/dist/ndjson-DcAtEx_K.mjs +131 -0
  43. package/dist/ndjson-DvHSsNU9.d.mts +16 -0
  44. package/dist/ownership-B9QIdQOw.mjs +475 -0
  45. package/dist/ownership-D8HmSv2E.mjs +60 -0
  46. package/dist/ownership-claim-CeJLEpjD.mjs +569 -0
  47. package/dist/process-output-C7IlIzd7.mjs +40 -0
  48. package/dist/project-COj6nzzh.mjs +243 -0
  49. package/dist/reclaim-BPvN2HlP.mjs +347 -0
  50. package/dist/reload-DYZEBbZy.mjs +332 -0
  51. package/dist/remote-cache-DOi5-zLj.mjs +934 -0
  52. package/dist/server-bare-BYHqEeyw.mjs +352 -0
  53. package/dist/server-expo-BEMr_m6p.mjs +312 -0
  54. package/dist/server-expo-rb0k-0w7.mjs +2 -0
  55. package/dist/settings-BSwrY4FZ.mjs +687 -0
  56. package/dist/spawn-entry-nCE6m770.mjs +14 -0
  57. package/dist/start-ByCylYtB.mjs +822 -0
  58. package/dist/state-IYEY-zi8.mjs +268 -0
  59. package/dist/stats-DZ4Q5J-7.mjs +62 -0
  60. package/dist/stats-wqxPm7Tv.mjs +307 -0
  61. package/dist/status-Dia0XTqG.mjs +363 -0
  62. package/dist/stop-BApyaF21.mjs +591 -0
  63. package/dist/stop-D6o5zAdm.mjs +3 -0
  64. package/dist/supervisor-run.d.mts +84 -0
  65. package/dist/supervisor-run.mjs +210 -0
  66. package/dist/workspace-process-lock-CxOO9-pf.mjs +47 -0
  67. package/dist/worktree-Dx3ZC5lS.mjs +539 -0
  68. package/dist/worktree-DxEmUI_n.mjs +1322 -0
  69. package/dist/xcode-CDB6fytw.mjs +1705 -0
  70. package/package.json +61 -8
  71. package/shim/android-cas-pch.cmake +35 -0
  72. package/shim/android-cas.gradle +29 -0
  73. package/shim/android-cas.toolchain.cmake +12 -0
  74. package/shim/android-optimizations.gradle +30 -0
  75. package/shim/bundle-response.cjs +46 -0
  76. package/shim/bundle-response.d.cts +5 -0
  77. package/shim/expo-metro-config.cjs +188 -0
  78. package/shim/metro-cache-generation.cjs +20 -0
  79. package/shim/metro-cache-generation.d.cts +5 -0
  80. package/skill/SKILL.md +14 -0
@@ -0,0 +1,934 @@
1
+ import { t as getExecutor } from "./exec-bsN9MJXb.mjs";
2
+ import { C as withConfigLock, g as loadConfig, s as ensureConfig, y as saveConfig } from "./config-D7uu8Gbq.mjs";
3
+ import { r as createNdjsonWriter } from "./ndjson-DcAtEx_K.mjs";
4
+ import { D as workspaceLogsDir } from "./state-IYEY-zi8.mjs";
5
+ import { l as resolvePackageJson } from "./project-COj6nzzh.mjs";
6
+ import { n as stripAnsi } from "./process-output-C7IlIzd7.mjs";
7
+ import { S as shutdownIosSim, a as deleteIosSim, b as resolveOwnedIosSim, g as renameIosSim, h as parseRuntimeVersion, m as parkedSimName, o as deleteParkedIosSim, r as clearAppDataContainer, s as findAppDataContainer, u as listIosDeviceTypes } from "./ios-BZxKPuqP.mjs";
8
+ import { A as resolveOwnedAvdSerial, C as ownedAvdMatchesConfiguration, M as shutdownAndroidEmulator, N as waitForAndroidEmulatorShutdown, T as ownedAvdSystemImage, d as deleteAvd, o as assertOwnedAvdStopped } from "./android-xmyGBNy5.mjs";
9
+ import { n as expoBinFromPackage, r as expoBinPath, s as findBinUpward } from "./server-expo-BEMr_m6p.mjs";
10
+ import { createRequire } from "node:module";
11
+ import { existsSync, readFileSync } from "node:fs";
12
+ import { randomUUID } from "node:crypto";
13
+ import { join } from "node:path";
14
+ import { pathToFileURL } from "node:url";
15
+ import { format } from "node:util";
16
+ import { AsyncLocalStorage } from "node:async_hooks";
17
+ const POOL_SETTING_REMEDY = "Run `stim guide settings` for the device pool bounds and where it can be set.";
18
+ const MAX_SETTING = {
19
+ ios: {
20
+ key: "iosParkedMax",
21
+ env: "STIM_POOL_IOS_PARKED_MAX"
22
+ },
23
+ android: {
24
+ key: "androidParkedMax",
25
+ env: "STIM_POOL_ANDROID_PARKED_MAX"
26
+ }
27
+ };
28
+ function parseMax(raw, strings) {
29
+ const value = strings && typeof raw === "string" ? /^\d+$/.test(raw.trim()) ? Number(raw.trim()) : NaN : raw;
30
+ if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 0) return null;
31
+ return value;
32
+ }
33
+ function parkedMaxSetting(platform, { config, env = process.env } = {}) {
34
+ const { key, env: envKey } = MAX_SETTING[platform];
35
+ const fromEnv = env[envKey];
36
+ const explicit = fromEnv !== void 0 && fromEnv !== "";
37
+ const pool = (config === void 0 ? loadConfig() : config)?.pool;
38
+ if (!explicit && pool !== void 0 && (pool === null || typeof pool !== "object" || Array.isArray(pool))) return {
39
+ max: 0,
40
+ error: "Invalid pool value. Expected an object with simulator and emulator bounds."
41
+ };
42
+ const fromConfig = pool !== null && typeof pool === "object" && !Array.isArray(pool) ? pool[key] : void 0;
43
+ const raw = explicit ? fromEnv : fromConfig;
44
+ if (raw === void 0) return {
45
+ max: env.STIM_HOME ? 0 : 3,
46
+ error: null
47
+ };
48
+ const parsed = parseMax(raw, explicit);
49
+ if (parsed === null) return {
50
+ max: 0,
51
+ error: `Invalid ${explicit ? envKey : `pool.${key}`} value ${JSON.stringify(raw)}. Expected a whole number of parked ${platform === "ios" ? "simulators" : "emulators"}, 0 or more.`
52
+ };
53
+ return {
54
+ max: explicit ? parsed : env.STIM_HOME ? 0 : parsed,
55
+ error: null
56
+ };
57
+ }
58
+ function isParkedRecord(value, platform) {
59
+ if (value === null || typeof value !== "object" || Array.isArray(value)) return false;
60
+ const record = value;
61
+ return typeof record.udid === "string" && typeof record.name === "string" && record.name.startsWith("stim-") && typeof record.parkedAt === "string" && (platform === "android" ? record.udid === record.name && /^stim-[A-Za-z0-9._-]+$/.test(record.name) && typeof record.systemImage === "string" && typeof record.configuration === "string" : typeof record.deviceTypeIdentifier === "string" && typeof record.runtimeIdentifier === "string" && typeof record.simslimManaged === "boolean" && (record.bundleId === void 0 || typeof record.bundleId === "string") && (record.cacheKey === void 0 || typeof record.cacheKey === "string"));
62
+ }
63
+ function poolBlock(config) {
64
+ const raw = config?.parked;
65
+ const block = raw !== null && typeof raw === "object" && !Array.isArray(raw) ? raw : {};
66
+ const read = (platform) => {
67
+ const list = block[platform];
68
+ return Array.isArray(list) ? list.filter((record) => isParkedRecord(record, platform)) : [];
69
+ };
70
+ return {
71
+ ios: read("ios"),
72
+ android: read("android")
73
+ };
74
+ }
75
+ function readParked(platform, { config } = {}) {
76
+ return poolBlock(config === void 0 ? loadConfig() : config)[platform];
77
+ }
78
+ function writeParked(config, platform, records) {
79
+ config.parked = {
80
+ ...poolBlock(config),
81
+ [platform]: records
82
+ };
83
+ }
84
+ function oldestFirst(records) {
85
+ return records.toSorted((a, b) => String(a.parkedAt).localeCompare(String(b.parkedAt)));
86
+ }
87
+ function selectParked(records, { deviceTypeIdentifier, runtimeIdentifier }) {
88
+ return oldestFirst(records.filter((r) => r.deletionClaim === void 0 && r.deviceTypeIdentifier === deviceTypeIdentifier && r.runtimeIdentifier === runtimeIdentifier));
89
+ }
90
+ function evictOverflow(records, max) {
91
+ if (records.length <= max) return {
92
+ keep: [...records],
93
+ evicted: []
94
+ };
95
+ const ordered = oldestFirst(records);
96
+ const evicted = ordered.slice(0, ordered.length - max);
97
+ const dropped = new Set(evicted.map((r) => r.udid));
98
+ return {
99
+ keep: records.filter((r) => !dropped.has(r.udid)),
100
+ evicted
101
+ };
102
+ }
103
+ function parkSim({ platform, projectPath, record, max }) {
104
+ return withConfigLock(() => {
105
+ const cfg = ensureConfig();
106
+ if (platform === "android") {
107
+ const current = cfg.projects[projectPath]?.platforms?.android;
108
+ if (!current?.owned || current.avdName !== record.udid) throw new Error("The emulator assignment changed before parking.");
109
+ }
110
+ const { keep, evicted } = evictOverflow([...readParked(platform, { config: cfg }).filter((r) => r.udid !== record.udid), record], max);
111
+ writeParked(cfg, platform, [...keep, ...evicted]);
112
+ const platforms = cfg.projects?.[projectPath]?.platforms;
113
+ if (platforms) delete platforms[platform];
114
+ saveConfig(cfg);
115
+ return evicted;
116
+ });
117
+ }
118
+ function adoptParked({ platform, projectPath, udid, device }) {
119
+ return withConfigLock(() => {
120
+ const cfg = ensureConfig();
121
+ const records = readParked(platform, { config: cfg });
122
+ const taken = records.find((r) => r.udid === udid);
123
+ if (!taken || taken.deletionClaim !== void 0) return null;
124
+ if (platform === "android" && cfg.projects[projectPath]?.platforms?.android) return null;
125
+ writeParked(cfg, platform, records.filter((r) => r.udid !== udid));
126
+ const project = cfg.projects[projectPath];
127
+ if (!project) throw new Error(`Project not registered: ${projectPath}`);
128
+ project.platforms = project.platforms || {};
129
+ project.platforms[platform] = device;
130
+ saveConfig(cfg);
131
+ return taken;
132
+ });
133
+ }
134
+ function isProcessAlive(pid) {
135
+ try {
136
+ process.kill(pid, 0);
137
+ return true;
138
+ } catch (error) {
139
+ return error.code === "EPERM";
140
+ }
141
+ }
142
+ function parseDeletionClaim(value) {
143
+ if (value === null || typeof value !== "object" || Array.isArray(value)) return null;
144
+ const claim = value;
145
+ if (!Number.isSafeInteger(claim.pid) || claim.pid <= 0) return null;
146
+ if (typeof claim.token !== "string" || claim.token.length === 0) return null;
147
+ return {
148
+ pid: claim.pid,
149
+ token: claim.token
150
+ };
151
+ }
152
+ function claimParkedRemoval(platform, udid) {
153
+ return withConfigLock(() => {
154
+ const cfg = loadConfig();
155
+ if (!cfg) return null;
156
+ const records = readParked(platform, { config: cfg });
157
+ const record = records.find((candidate) => candidate.udid === udid);
158
+ if (!record) return null;
159
+ const existingClaim = parseDeletionClaim(record.deletionClaim);
160
+ if (record.deletionClaim !== void 0 && (!existingClaim || isProcessAlive(existingClaim.pid))) return null;
161
+ const token = randomUUID();
162
+ const claimedRecord = {
163
+ ...record,
164
+ deletionClaim: {
165
+ pid: process.pid,
166
+ token
167
+ }
168
+ };
169
+ writeParked(cfg, platform, records.map((candidate) => candidate.udid === udid ? claimedRecord : candidate));
170
+ saveConfig(cfg);
171
+ const claimed = { ...record };
172
+ delete claimed.deletionClaim;
173
+ return {
174
+ record: claimed,
175
+ token
176
+ };
177
+ });
178
+ }
179
+ function clearParkedRemovalClaim(platform, udid, token) {
180
+ withConfigLock(() => {
181
+ const cfg = loadConfig();
182
+ if (!cfg) return;
183
+ const records = readParked(platform, { config: cfg });
184
+ const record = records.find((candidate) => candidate.udid === udid);
185
+ if (!record || parseDeletionClaim(record.deletionClaim)?.token !== token) return;
186
+ const restored = { ...record };
187
+ delete restored.deletionClaim;
188
+ writeParked(cfg, platform, records.map((candidate) => candidate.udid === udid ? restored : candidate));
189
+ saveConfig(cfg);
190
+ });
191
+ }
192
+ function removeParkedAfter(platform, udid, beforeRemove) {
193
+ const claim = claimParkedRemoval(platform, udid);
194
+ if (!claim) return null;
195
+ try {
196
+ beforeRemove(claim.record);
197
+ } catch (error) {
198
+ try {
199
+ clearParkedRemovalClaim(platform, udid, claim.token);
200
+ } catch {}
201
+ throw error;
202
+ }
203
+ return withConfigLock(() => {
204
+ const cfg = loadConfig();
205
+ if (!cfg) return null;
206
+ const records = readParked(platform, { config: cfg });
207
+ if (parseDeletionClaim(records.find((candidate) => candidate.udid === udid)?.deletionClaim)?.token !== claim.token) return null;
208
+ writeParked(cfg, platform, records.filter((candidate) => candidate.udid !== udid));
209
+ saveConfig(cfg);
210
+ return claim.record;
211
+ });
212
+ }
213
+ function dropParked(platform, udid) {
214
+ return removeParkedAfter(platform, udid, () => {}) !== null;
215
+ }
216
+ //#endregion
217
+ //#region src/teardown.ts
218
+ function teardownParkedAvd(avdName) {
219
+ try {
220
+ return removeParkedAfter("android", avdName, () => {
221
+ const result = teardownOwnedAvd(avdName, { del: true });
222
+ if (result.status !== "torn-down" && result.status !== "missing") throw new Error(result.reason);
223
+ }) ? {
224
+ status: "torn-down",
225
+ label: avdName
226
+ } : {
227
+ status: "skipped",
228
+ kind: "not-parked",
229
+ reason: "emulator is no longer parked"
230
+ };
231
+ } catch (error) {
232
+ return {
233
+ status: "failed",
234
+ reason: String(error?.message || error)
235
+ };
236
+ }
237
+ }
238
+ function teardownParkedIosSim(udid, { label, deleteSim = deleteParkedIosSim } = {}) {
239
+ try {
240
+ const removed = removeParkedAfter("ios", udid, () => deleteSim(udid));
241
+ if (!removed) return {
242
+ status: "skipped",
243
+ kind: "not-parked",
244
+ reason: "simulator is no longer parked"
245
+ };
246
+ return {
247
+ status: "torn-down",
248
+ label: label ?? removed.name
249
+ };
250
+ } catch (error) {
251
+ return {
252
+ status: "failed",
253
+ reason: String(error?.message || error)
254
+ };
255
+ }
256
+ }
257
+ function parkOwnedIosSim(udid, park) {
258
+ const resolved = resolveOwnedIosSim(udid);
259
+ if (resolved.missing) throw new Error(`simulator ${udid} disappeared after shutdown`);
260
+ if (resolved.notOwned) throw new Error(`simulator ${udid} is now named ${JSON.stringify(resolved.notOwned)}`);
261
+ const sim = resolved.sim;
262
+ if (sim.state !== "Shutdown") throw new Error(`simulator ${udid} is still ${sim.state} after shutdown`);
263
+ const model = listIosDeviceTypes().find((d) => d.identifier === sim.deviceTypeIdentifier)?.name ?? null;
264
+ const runtime = parseRuntimeVersion(sim.runtime);
265
+ if (park.bundleId) {
266
+ if (!sim.dataPath) throw new Error(`simulator ${udid} did not report a data path for app cleanup`);
267
+ const container = findAppDataContainer(sim.dataPath, park.bundleId);
268
+ if (container) clearAppDataContainer(container);
269
+ }
270
+ const name = parkedSimName(sim.udid, {
271
+ model,
272
+ runtime
273
+ });
274
+ renameIosSim(sim.udid, name);
275
+ const record = {
276
+ udid: sim.udid,
277
+ name,
278
+ deviceTypeIdentifier: sim.deviceTypeIdentifier,
279
+ runtimeIdentifier: sim.runtime,
280
+ parkedAt: (/* @__PURE__ */ new Date()).toISOString(),
281
+ simslimManaged: Boolean(park.simslimManaged),
282
+ ...park.bundleId ? { bundleId: park.bundleId } : {},
283
+ ...park.cacheKey ? { cacheKey: park.cacheKey } : {}
284
+ };
285
+ return {
286
+ record,
287
+ evicted: parkSim({
288
+ platform: "ios",
289
+ projectPath: park.projectPath,
290
+ record,
291
+ max: park.max
292
+ })
293
+ };
294
+ }
295
+ function teardownOwnedIosSim(udid, { del = false, label, park } = {}) {
296
+ let parkFallback;
297
+ try {
298
+ const resolved = resolveOwnedIosSim(udid);
299
+ if (resolved.notOwned) return {
300
+ status: "skipped",
301
+ kind: "not-owned",
302
+ reason: `sim is now named "${resolved.notOwned}", not Stim-owned by name`
303
+ };
304
+ if (resolved.missing) return { status: "missing" };
305
+ shutdownIosSim(udid);
306
+ const sim = resolved.sim;
307
+ if (del && park && park.max > 0) try {
308
+ const { record, evicted } = parkOwnedIosSim(udid, park);
309
+ const removed = [];
310
+ const failures = [];
311
+ for (const entry of evicted) {
312
+ const result = teardownParkedIosSim(entry.udid, { label: entry.name });
313
+ if (result.status === "torn-down") removed.push({
314
+ udid: entry.udid,
315
+ name: entry.name
316
+ });
317
+ else if (result.status === "failed") failures.push(`could not delete evicted ${entry.name} (${entry.udid}): ${result.reason}`);
318
+ }
319
+ return {
320
+ status: "torn-down",
321
+ label: label ?? sim.name ?? udid,
322
+ parked: {
323
+ udid: record.udid,
324
+ name: record.name
325
+ },
326
+ evicted: removed,
327
+ ...failures.length ? { evictionFailures: failures } : {}
328
+ };
329
+ } catch (e) {
330
+ parkFallback = String(e?.message || e);
331
+ }
332
+ if (del) deleteIosSim(udid);
333
+ return {
334
+ status: "torn-down",
335
+ label: label ?? sim.name ?? udid,
336
+ ...parkFallback ? { parkFallback } : {}
337
+ };
338
+ } catch (e) {
339
+ return {
340
+ status: "failed",
341
+ reason: String(e?.message || e),
342
+ ...parkFallback ? { parkFallback } : {}
343
+ };
344
+ }
345
+ }
346
+ function teardownOwnedAvd(avdName, { del = false, park, waitForShutdown = waitForAndroidEmulatorShutdown, assertStopped = assertOwnedAvdStopped, resolveAvd = resolveOwnedAvdSerial } = {}) {
347
+ let parkFallback;
348
+ try {
349
+ const resolved = resolveAvd(avdName);
350
+ if (resolved.notOwned) return {
351
+ status: "skipped",
352
+ kind: "not-owned",
353
+ reason: `AVD ${avdName} is not Stim-owned by name`
354
+ };
355
+ if (resolved.missing) return { status: "missing" };
356
+ const serial = resolved.serial;
357
+ if (serial) waitForShutdown(avdName, (timeoutMs) => shutdownAndroidEmulator(serial, timeoutMs));
358
+ else assertStopped(avdName);
359
+ if (del) {
360
+ const current = resolveAvd(avdName);
361
+ if (current.notOwned) return {
362
+ status: "skipped",
363
+ kind: "not-owned",
364
+ reason: `AVD ${avdName} is not Stim-owned by name`
365
+ };
366
+ if (current.missing) return { status: "missing" };
367
+ if (current.serial) throw new Error(`Owned AVD ${avdName} started again before deletion.`);
368
+ assertStopped(avdName);
369
+ if (park && park.max > 0) try {
370
+ const systemImage = ownedAvdSystemImage(avdName);
371
+ if (!systemImage || !park.configuration || !ownedAvdMatchesConfiguration(avdName, park.configuration)) throw new Error("the AVD has no verified creation configuration");
372
+ const evicted = parkSim({
373
+ platform: "android",
374
+ projectPath: park.projectPath,
375
+ max: park.max,
376
+ record: {
377
+ udid: avdName,
378
+ name: avdName,
379
+ systemImage,
380
+ configuration: park.configuration,
381
+ parkedAt: (/* @__PURE__ */ new Date()).toISOString()
382
+ }
383
+ });
384
+ const removed = [];
385
+ const failures = [];
386
+ for (const entry of evicted) {
387
+ const result = teardownParkedAvd(entry.name);
388
+ if (result.status === "torn-down") removed.push({
389
+ udid: entry.name,
390
+ name: entry.name,
391
+ platform: "android"
392
+ });
393
+ else if (result.status === "failed") failures.push(`could not delete evicted ${entry.name}: ${result.reason}`);
394
+ }
395
+ return {
396
+ status: "torn-down",
397
+ label: avdName,
398
+ parked: {
399
+ udid: avdName,
400
+ name: avdName,
401
+ platform: "android"
402
+ },
403
+ evicted: removed,
404
+ ...failures.length ? { evictionFailures: failures } : {}
405
+ };
406
+ } catch (error) {
407
+ parkFallback = String(error?.message || error);
408
+ }
409
+ deleteAvd(avdName);
410
+ }
411
+ return {
412
+ status: "torn-down",
413
+ label: avdName,
414
+ serial: resolved.serial ?? null,
415
+ ...parkFallback ? { parkFallback } : {}
416
+ };
417
+ } catch (e) {
418
+ return {
419
+ status: "failed",
420
+ reason: String(e?.message || e)
421
+ };
422
+ }
423
+ }
424
+ //#endregion
425
+ //#region src/engine/remote-cache.ts
426
+ const EAS_PROVIDER_PACKAGE = "eas-build-cache-provider";
427
+ const RESOLVE_TIMEOUT_MS = 3e4;
428
+ const UPLOAD_TIMEOUT_MS = 6e4;
429
+ const CONFIG_TIMEOUT_MS = 3e4;
430
+ const DYNAMIC_CONFIG_FILES = [
431
+ "app.config.ts",
432
+ "app.config.js",
433
+ "app.config.mjs",
434
+ "app.config.cjs"
435
+ ];
436
+ const TIMED_OUT = Symbol("timed-out");
437
+ function dynamicConfigFile(root) {
438
+ for (const name of DYNAMIC_CONFIG_FILES) if (existsSync(join(root, name))) return name;
439
+ return null;
440
+ }
441
+ function providerFromConfig(config) {
442
+ if (!config || typeof config !== "object") return null;
443
+ const expoField = config.expo;
444
+ const exp = expoField && typeof expoField === "object" ? expoField : config;
445
+ return exp.buildCacheProvider ?? exp.experiments?.buildCacheProvider ?? null;
446
+ }
447
+ function ownerFromConfig(config) {
448
+ if (!config || typeof config !== "object") return null;
449
+ const expoField = config.expo;
450
+ const owner = (expoField && typeof expoField === "object" ? expoField : config).owner;
451
+ return typeof owner === "string" && owner.trim() !== "" ? owner.trim() : null;
452
+ }
453
+ function normalizeProvider(raw) {
454
+ if (raw === null || raw === void 0 || raw === "") return null;
455
+ if (raw === "eas") return {
456
+ name: "eas",
457
+ reference: EAS_PROVIDER_PACKAGE,
458
+ options: {}
459
+ };
460
+ if (typeof raw === "object") {
461
+ const obj = raw;
462
+ if (typeof obj.plugin === "string" && obj.plugin.trim() !== "") {
463
+ const reference = obj.plugin.trim();
464
+ return {
465
+ name: reference,
466
+ reference,
467
+ options: obj.options && typeof obj.options === "object" ? obj.options : {}
468
+ };
469
+ }
470
+ }
471
+ return { invalid: typeof raw === "string" ? `"${raw}"` : JSON.stringify(raw) };
472
+ }
473
+ function runOptionsFor(platform) {
474
+ return platform === "android" ? { variant: "debug" } : { configuration: "Debug" };
475
+ }
476
+ function isProviderPlugin(plugin) {
477
+ if (!plugin || typeof plugin !== "object") return false;
478
+ const p = plugin;
479
+ const resolves = typeof p.resolveBuildCache === "function" || typeof p.resolveRemoteBuildCache === "function";
480
+ const uploads = typeof p.uploadBuildCache === "function" || typeof p.uploadRemoteBuildCache === "function";
481
+ return resolves && uploads;
482
+ }
483
+ function cacheLevel(value) {
484
+ return value === "local" || value === "remote" ? value : false;
485
+ }
486
+ function exitAfterFlush(code = 0, { exit = (c) => process.exit(c), stream = process.stdout } = {}) {
487
+ try {
488
+ stream.write("", () => exit(code));
489
+ } catch {
490
+ exit(code);
491
+ }
492
+ }
493
+ function readProjectConfig(root, { run = null, timeoutMs = CONFIG_TIMEOUT_MS } = {}) {
494
+ const dynamic = dynamicConfigFile(root);
495
+ if (!dynamic) {
496
+ const file = join(root, "app.json");
497
+ if (!existsSync(file)) return {
498
+ config: null,
499
+ source: null
500
+ };
501
+ try {
502
+ return {
503
+ config: JSON.parse(readFileSync(file, "utf-8")),
504
+ source: "app.json"
505
+ };
506
+ } catch (err) {
507
+ return { unavailable: `app.json could not be parsed: ${firstLine(err)}` };
508
+ }
509
+ }
510
+ const bin = expoBinPath(root);
511
+ if (!bin) return { unavailable: `${dynamic} is code, so it has to be evaluated to read its buildCacheProvider, and the \`expo\` package is not resolvable from this project (no expo/package.json to read a bin from, and no node_modules/.bin/expo here or in any parent)` };
512
+ const exec = run || ((file, args, opts) => getExecutor().runFile(file, args, opts));
513
+ let stdout;
514
+ try {
515
+ stdout = exec(bin, [
516
+ "config",
517
+ "--json",
518
+ root
519
+ ], { timeoutMs });
520
+ } catch (err) {
521
+ return { unavailable: `\`expo config --json\` failed: ${firstLine(err)}` };
522
+ }
523
+ try {
524
+ return {
525
+ config: JSON.parse(String(stdout)),
526
+ source: dynamic
527
+ };
528
+ } catch (err) {
529
+ return { unavailable: `\`expo config --json\` did not print JSON: ${firstLine(err)}` };
530
+ }
531
+ }
532
+ async function loadPlugin(projectRoot, reference, { requireFrom = null } = {}) {
533
+ const localRequire = requireFrom ? requireFrom(projectRoot) : createRequire(join(projectRoot, "package.json"));
534
+ const file = localRequire.resolve(reference);
535
+ let mod;
536
+ try {
537
+ mod = localRequire(file);
538
+ } catch (err) {
539
+ if (err?.code !== "ERR_REQUIRE_ESM") throw err;
540
+ mod = await import(pathToFileURL(file).href);
541
+ }
542
+ const plugin = mod?.default ?? mod;
543
+ if (!isProviderPlugin(plugin)) throw new Error(`"${reference}" does not export resolveBuildCache and uploadBuildCache functions`);
544
+ return plugin;
545
+ }
546
+ async function loadProjectProvider(projectRoot, { isExpo = true, run = null, requireFrom = null, timeoutMs = CONFIG_TIMEOUT_MS } = {}) {
547
+ if (!isExpo) return { none: true };
548
+ const read = readProjectConfig(projectRoot, {
549
+ run,
550
+ timeoutMs
551
+ });
552
+ if (read.unavailable) return { unavailable: read.unavailable };
553
+ const normalized = normalizeProvider(providerFromConfig(read.config));
554
+ if (!normalized) return { none: true };
555
+ if (normalized.invalid) return { unavailable: `buildCacheProvider is ${normalized.invalid}, which is not "eas" or { plugin: <module> }` };
556
+ if (normalized.reference === "@stim-cli/expo-build-cache") return { none: true };
557
+ let plugin;
558
+ try {
559
+ plugin = await loadPlugin(projectRoot, normalized.reference, { requireFrom });
560
+ } catch (err) {
561
+ const missing = err?.code === "MODULE_NOT_FOUND";
562
+ return { unavailable: normalized.name === "eas" && missing ? `the EAS build cache needs the \`${EAS_PROVIDER_PACKAGE}\` package, which is not installed in this project` : `${normalized.name} could not be loaded: ${firstLine(err)}` };
563
+ }
564
+ return {
565
+ provider: {
566
+ plugin,
567
+ options: normalized.options ?? {}
568
+ },
569
+ name: normalized.name,
570
+ owner: ownerFromConfig(read.config)
571
+ };
572
+ }
573
+ const WHOAMI_TIMEOUT_MS = 15e3;
574
+ const EAS_CLI_PACKAGE = "eas-cli";
575
+ const EAS_CLI_BIN = "eas";
576
+ function parseWhoami({ stdout = "", stderr = "", exitCode = 0 } = {}) {
577
+ const out = stripAnsi(stdout);
578
+ const combined = `${out}\n${stripAnsi(stderr)}`;
579
+ if (/^\s*Not logged in\s*$/m.test(combined)) return { loggedOut: true };
580
+ if (exitCode !== 0) return { unknown: firstLine(combined.trim() || `eas whoami exited ${exitCode}`) };
581
+ const lines = out.split("\n").map((line) => line.trim()).filter((line) => line !== "");
582
+ if (lines.length === 0) return { unknown: "eas whoami printed nothing" };
583
+ const raw = lines[0];
584
+ if (raw === void 0) return { unknown: "eas whoami printed nothing" };
585
+ const viaToken = /\(authenticated using EXPO_TOKEN\)\s*$/.test(raw);
586
+ const display = raw.replace(/\s*\(authenticated using EXPO_TOKEN\)\s*$/, "").trim();
587
+ const accounts = [];
588
+ for (const line of lines) {
589
+ const name = /^\u2022\s*(\S+)\s*\(Role:/.exec(line)?.[1];
590
+ if (name !== void 0) accounts.push(name);
591
+ }
592
+ if (accounts.length === 0 && !display.endsWith("(robot)") && display !== "robot") accounts.push(display);
593
+ return {
594
+ loggedIn: true,
595
+ account: display,
596
+ accounts: accounts.length ? accounts : null,
597
+ viaToken
598
+ };
599
+ }
600
+ function isEasAuthFailureText(text) {
601
+ const t = stripAnsi(text || "");
602
+ if (t.trim() === "") return false;
603
+ return /not logged in/i.test(t) || /\beas login\b/i.test(t) || /EXPO_TOKEN/.test(t) || /unauthorized/i.test(t) || /not authorized/i.test(t) || /authentication (failed|required)/i.test(t);
604
+ }
605
+ function easAuthNote(status) {
606
+ const { code, account, owner, reason, phase = "resolve" } = status || {};
607
+ const because = reason ? ` (${reason})` : "";
608
+ if (code === "logged-out") return `eas is not authenticated${because} -- run \`eas login\` (or set EXPO_TOKEN); ` + (phase === "upload" ? "this build stayed in the local cache" : "building with the local cache only");
609
+ if (code === "wrong-account") return `eas is authenticated as ${account}, and this project's owner is ${owner} -- run \`eas login\` as a member of ${owner} (or set EXPO_TOKEN); consulting the EAS cache anyway`;
610
+ return null;
611
+ }
612
+ function resolveEasCliBin(projectRoot, { lookupPath = null, timeoutMs = 5e3 } = {}) {
613
+ const fromPackage = expoBinFromPackage(resolvePackageJson(projectRoot, EAS_CLI_PACKAGE), EAS_CLI_BIN);
614
+ if (fromPackage) return {
615
+ file: fromPackage,
616
+ source: "project"
617
+ };
618
+ const shim = findBinUpward(projectRoot, EAS_CLI_BIN);
619
+ if (shim) return {
620
+ file: shim,
621
+ source: "project"
622
+ };
623
+ const onPath = lookupPath ? lookupPath() : getExecutor().runQuiet(`command -v ${EAS_CLI_BIN}`, { timeoutMs });
624
+ const file = (String(onPath || "").split("\n")[0] ?? "").trim();
625
+ return file ? {
626
+ file,
627
+ source: "path"
628
+ } : null;
629
+ }
630
+ const easAuthCache = /* @__PURE__ */ new Map();
631
+ function checkEasAuth({ projectRoot, owner = null, run = null, resolveBin = null, timeoutMs = WHOAMI_TIMEOUT_MS, cache = easAuthCache }) {
632
+ const key = `${projectRoot}::${owner || ""}`;
633
+ if (cache?.has(key)) return cache.get(key);
634
+ const answer = probeEasAuth({
635
+ projectRoot,
636
+ owner,
637
+ run,
638
+ resolveBin,
639
+ timeoutMs
640
+ });
641
+ cache?.set(key, answer);
642
+ return answer;
643
+ }
644
+ function probeEasAuth({ projectRoot, owner, run, resolveBin, timeoutMs }) {
645
+ const bin = (resolveBin || resolveEasCliBin)(projectRoot);
646
+ if (!bin) return {
647
+ failed: true,
648
+ code: "no-cli",
649
+ reason: "no `eas` executable is resolvable from this project or on PATH",
650
+ remedy: "Install eas-cli (`npm i -g eas-cli`, or as a project devDependency), then run `eas login`."
651
+ };
652
+ const exec = run || ((file, args, opts) => getExecutor().runFile(file, args, opts));
653
+ let result;
654
+ try {
655
+ result = {
656
+ stdout: String(exec(bin.file, ["whoami"], { timeoutMs }) ?? ""),
657
+ exitCode: 0
658
+ };
659
+ } catch (e) {
660
+ const err = e;
661
+ if (err?.code === "ETIMEDOUT" || err?.signal === "SIGTERM" || err?.killed) return { unknown: `eas whoami timed out after ${timeoutMs}ms` };
662
+ result = {
663
+ stdout: String(err?.stdout ?? ""),
664
+ stderr: String(err?.stderr ?? err?.message ?? ""),
665
+ exitCode: typeof err?.status === "number" ? err.status : 1
666
+ };
667
+ }
668
+ const parsed = parseWhoami(result);
669
+ if (parsed.loggedOut) return {
670
+ failed: true,
671
+ code: "logged-out",
672
+ reason: "eas whoami says \"Not logged in\"",
673
+ remedy: "Run `eas login` (or set EXPO_TOKEN)."
674
+ };
675
+ if (parsed.unknown) return { unknown: parsed.unknown };
676
+ if (owner && Array.isArray(parsed.accounts) && !parsed.accounts.includes(owner)) return {
677
+ failed: true,
678
+ code: "wrong-account",
679
+ account: parsed.account,
680
+ accounts: parsed.accounts,
681
+ owner,
682
+ reason: `eas is authenticated as ${parsed.account} (accounts: ${parsed.accounts.join(", ")}), which does not include this project's owner ${owner}`,
683
+ remedy: `Run \`eas login\` as a member of ${owner}, or set EXPO_TOKEN to a token for it.`
684
+ };
685
+ return {
686
+ ok: true,
687
+ account: parsed.account,
688
+ accounts: parsed.accounts,
689
+ viaToken: parsed.viaToken,
690
+ source: bin.source
691
+ };
692
+ }
693
+ const capturing = [];
694
+ const abandoned = /* @__PURE__ */ new Set();
695
+ let patched = null;
696
+ const PROVIDER_CONTEXT = new AsyncLocalStorage();
697
+ function uploadDestination(lines) {
698
+ const text = (lines || []).map(stripAnsi);
699
+ for (const line of text) {
700
+ const url = /(https?:\/\/[^\s'"]+)/.exec(line)?.[1];
701
+ if (url !== void 0) return url.replace(/[.,)\]]+$/, "");
702
+ }
703
+ for (const line of text) {
704
+ const slug = /\bto\s+(@?[\w.-]+\/[\w.-]+)/i.exec(line)?.[1];
705
+ if (slug !== void 0) return slug.replace(/[.,)\]]+$/, "");
706
+ }
707
+ return null;
708
+ }
709
+ function providerNote(text) {
710
+ return `${"cache".padEnd(11)} ${text}`;
711
+ }
712
+ function currentFrame() {
713
+ const store = PROVIDER_CONTEXT.getStore();
714
+ return store && (capturing.includes(store) || abandoned.has(store)) ? store : null;
715
+ }
716
+ function install() {
717
+ if (patched && process.stdout.write === patched.patchedWrite) return;
718
+ const stdout = process.stdout;
719
+ const write = stdout.write.bind(stdout);
720
+ const log = console.log;
721
+ const passthrough = write;
722
+ const patchedWrite = ((chunk, encoding, callback) => {
723
+ const frame = currentFrame();
724
+ if (!frame) return passthrough(chunk, encoding, callback);
725
+ const cb = typeof encoding === "function" ? encoding : callback;
726
+ absorb(frame, typeof chunk === "string" ? chunk : String(chunk));
727
+ if (typeof cb === "function") cb();
728
+ return true;
729
+ });
730
+ const patchedLog = (...args) => {
731
+ const frame = currentFrame();
732
+ if (!frame) return log(...args);
733
+ absorb(frame, `${format(...args)}\n`);
734
+ };
735
+ stdout.write = patchedWrite;
736
+ console.log = patchedLog;
737
+ patched = {
738
+ stdout,
739
+ write,
740
+ log,
741
+ patchedWrite,
742
+ patchedLog
743
+ };
744
+ }
745
+ function uninstall() {
746
+ if (!patched || capturing.length || abandoned.size) return;
747
+ if (patched.stdout.write === patched.patchedWrite) patched.stdout.write = patched.write;
748
+ if (console.log === patched.patchedLog) console.log = patched.log;
749
+ patched = null;
750
+ }
751
+ function absorb(frame, chunk) {
752
+ try {
753
+ process.stderr.write(chunk);
754
+ } catch {}
755
+ frame.pending += chunk;
756
+ let index = frame.pending.indexOf("\n");
757
+ while (index !== -1) {
758
+ emitLine(frame, frame.pending.slice(0, index));
759
+ frame.pending = frame.pending.slice(index + 1);
760
+ index = frame.pending.indexOf("\n");
761
+ }
762
+ }
763
+ function emitLine(frame, raw) {
764
+ const line = stripAnsi(raw).trim();
765
+ if (line === "") return;
766
+ frame.lines.push(line);
767
+ const writer = frame.writer();
768
+ try {
769
+ writer?.write({
770
+ src: "build",
771
+ level: "debug",
772
+ event: "provider",
773
+ msg: line
774
+ });
775
+ } catch {}
776
+ frame.onLine?.(line);
777
+ }
778
+ function beginCapture({ logWriter = null, projectRoot = null, platform = null, onLine = null } = {}) {
779
+ let own = null;
780
+ const frame = {
781
+ lines: [],
782
+ pending: "",
783
+ onLine,
784
+ writer: () => {
785
+ if (logWriter) return logWriter;
786
+ if (own) return own;
787
+ if (!projectRoot || !platform) return null;
788
+ own = createNdjsonWriter(join(workspaceLogsDir(projectRoot), `build-${platform}.ndjson`));
789
+ return own;
790
+ },
791
+ close: () => {
792
+ own?.close?.();
793
+ own = null;
794
+ }
795
+ };
796
+ capturing.push(frame);
797
+ install();
798
+ return frame;
799
+ }
800
+ function endCapture(frame) {
801
+ if (!frame) return;
802
+ const at = capturing.lastIndexOf(frame);
803
+ if (at !== -1) capturing.splice(at, 1);
804
+ abandoned.delete(frame);
805
+ if (frame.pending !== "") {
806
+ const rest = frame.pending;
807
+ frame.pending = "";
808
+ emitLine(frame, rest);
809
+ }
810
+ frame.close();
811
+ uninstall();
812
+ }
813
+ function abandonCapture(frame, work) {
814
+ if (!frame) return;
815
+ const at = capturing.lastIndexOf(frame);
816
+ if (at !== -1) capturing.splice(at, 1);
817
+ abandoned.add(frame);
818
+ Promise.resolve(work).then(() => endCapture(frame), () => endCapture(frame));
819
+ }
820
+ async function resolveRemote({ provider, platform, projectRoot, fingerprintHash, runOptions = null, timeoutMs = RESOLVE_TIMEOUT_MS, logWriter = null } = {}) {
821
+ if (!provider?.plugin || !fingerprintHash) return null;
822
+ const opts = runOptions || runOptionsFor(platform);
823
+ const outcome = await withBudget(async () => {
824
+ const props = {
825
+ fingerprintHash: await providerFingerprint({
826
+ provider,
827
+ platform,
828
+ projectRoot,
829
+ runOptions: opts
830
+ }) ?? fingerprintHash,
831
+ platform,
832
+ runOptions: opts,
833
+ projectRoot
834
+ };
835
+ return typeof provider.plugin.resolveBuildCache === "function" ? provider.plugin.resolveBuildCache(props, provider.options) : provider.plugin.resolveRemoteBuildCache(props, provider.options);
836
+ }, timeoutMs, {
837
+ logWriter,
838
+ projectRoot,
839
+ platform
840
+ });
841
+ if (outcome.timedOut) return { timedOut: true };
842
+ if (outcome.error) return { failed: firstLine(outcome.error) };
843
+ const appPath = typeof outcome.value === "string" ? outcome.value.trim() : "";
844
+ if (!appPath) return null;
845
+ if (!existsSync(appPath)) return { failed: `returned ${appPath}, which does not exist` };
846
+ return { appPath };
847
+ }
848
+ async function uploadRemote({ provider, platform, projectRoot, fingerprintHash, buildPath, runOptions = null, timeoutMs = UPLOAD_TIMEOUT_MS, logWriter = null, note = (line) => console.error(line) } = {}) {
849
+ if (!provider?.plugin || !fingerprintHash || !buildPath) return { skipped: true };
850
+ const opts = runOptions || runOptionsFor(platform);
851
+ let announced = false;
852
+ const onLine = (line) => {
853
+ if (announced) return;
854
+ const dest = uploadDestination([line]);
855
+ if (!dest) return;
856
+ announced = true;
857
+ note(providerNote(`uploading to ${dest}`));
858
+ };
859
+ const outcome = await withBudget(async () => {
860
+ const props = {
861
+ projectRoot,
862
+ platform,
863
+ fingerprintHash: await providerFingerprint({
864
+ provider,
865
+ platform,
866
+ projectRoot,
867
+ runOptions: opts
868
+ }) ?? fingerprintHash,
869
+ buildPath,
870
+ runOptions: opts
871
+ };
872
+ return typeof provider.plugin.uploadBuildCache === "function" ? provider.plugin.uploadBuildCache(props, provider.options) : provider.plugin.uploadRemoteBuildCache(props, provider.options);
873
+ }, timeoutMs, {
874
+ logWriter,
875
+ projectRoot,
876
+ platform,
877
+ onLine
878
+ });
879
+ if (outcome.timedOut) return { timedOut: true };
880
+ if (outcome.error) return { failed: firstLine(outcome.error) };
881
+ const destination = uploadDestination(outcome.lines);
882
+ return destination ? {
883
+ uploaded: true,
884
+ destination
885
+ } : { uploaded: true };
886
+ }
887
+ async function providerFingerprint({ provider, platform, projectRoot, runOptions }) {
888
+ if (typeof provider.plugin.calculateFingerprintHash !== "function") return null;
889
+ try {
890
+ const hash = await provider.plugin.calculateFingerprintHash({
891
+ projectRoot,
892
+ platform,
893
+ runOptions
894
+ }, provider.options);
895
+ return typeof hash === "string" && hash.trim() !== "" ? hash.trim() : null;
896
+ } catch {
897
+ return null;
898
+ }
899
+ }
900
+ async function withBudget(factory, ms, capture) {
901
+ let timer = null;
902
+ const timeout = new Promise((resolve) => {
903
+ timer = setTimeout(() => resolve(TIMED_OUT), ms);
904
+ timer?.unref?.();
905
+ });
906
+ const frame = beginCapture(capture || {});
907
+ const work = Promise.resolve().then(() => PROVIDER_CONTEXT.run(frame, factory)).then((value) => ({ value }), (error) => ({ error }));
908
+ try {
909
+ const settled = await Promise.race([work, timeout]);
910
+ if (settled === TIMED_OUT) {
911
+ abandonCapture(frame, work);
912
+ return {
913
+ timedOut: true,
914
+ lines: frame.lines
915
+ };
916
+ }
917
+ endCapture(frame);
918
+ return {
919
+ ...settled,
920
+ lines: frame.lines
921
+ };
922
+ } catch (err) {
923
+ endCapture(frame);
924
+ throw err;
925
+ } finally {
926
+ if (timer) clearTimeout(timer);
927
+ }
928
+ }
929
+ function firstLine(err) {
930
+ const line = (String(err?.message || err || "unknown error").trim().split("\n")[0] ?? "").trim();
931
+ return line.length > 200 ? `${line.slice(0, 197)}...` : line;
932
+ }
933
+ //#endregion
934
+ export { selectParked as C, readParked as S, teardownParkedIosSim as _, easAuthNote as a, dropParked as b, loadProjectProvider as c, resolveEasCliBin as d, resolveRemote as f, teardownParkedAvd as g, teardownOwnedIosSim as h, checkEasAuth as i, ownerFromConfig as l, teardownOwnedAvd as m, UPLOAD_TIMEOUT_MS as n, exitAfterFlush as o, uploadRemote as p, cacheLevel as r, isEasAuthFailureText as s, RESOLVE_TIMEOUT_MS as t, providerFromConfig as u, POOL_SETTING_REMEDY as v, parkedMaxSetting as x, adoptParked as y };