stim 1.9.0 → 1.10.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 (83) hide show
  1. package/dist/{android-_y4Ohi5z.mjs → android-787HhP5w.mjs} +119 -29
  2. package/dist/{android-BPGizezh.mjs → android-DBkeHwpm.mjs} +168 -95
  3. package/dist/{android-DEgo4oCo.mjs → android-DPov-fv2.mjs} +2 -2
  4. package/dist/{android-cas-eiExNLf7.mjs → android-cas-CITmIeWY.mjs} +9 -8
  5. package/dist/android-cas-compiler.mjs +1 -1
  6. package/dist/{app-install-Uf3a83Tv.mjs → app-install-CrJ6t_bv.mjs} +2 -2
  7. package/dist/budget-BP4jZZL4.mjs +620 -0
  8. package/dist/build-progress-BXx-ZBe4.mjs +512 -0
  9. package/dist/{cache-manifest-Dg7OnMrp.mjs → cache-manifest-Pubfp8wV.mjs} +1 -1
  10. package/dist/cache-manifest.mjs +1 -1
  11. package/dist/cli.mjs +16 -16
  12. package/dist/collector-run.d.mts +5 -1
  13. package/dist/collector-run.mjs +7 -7
  14. package/dist/{command-output-gByVmIjy.mjs → command-output-D5z2_bcF.mjs} +1 -1
  15. package/dist/{config-Cp9lM3wX.mjs → config-BEq0Qw_a.mjs} +14 -131
  16. package/dist/{dependency-state-Bq5DcLGn.mjs → dependency-state-r9UesA9a.mjs} +2 -2
  17. package/dist/{deps-Cip5vUm1.mjs → deps-DP4eWqea.mjs} +3 -3
  18. package/dist/{detached-entry-KEu0_AXL.mjs → detached-entry-DJHoca49.mjs} +1 -1
  19. package/dist/{dev-client-HyqISM0h.mjs → dev-client-92U593KT.mjs} +137 -250
  20. package/dist/{device-D4U-xLty.mjs → device-DhTZe7L4.mjs} +7 -7
  21. package/dist/{build-lock-DPXPLgTc.mjs → device-lease-CbEaIk7b.mjs} +370 -12
  22. package/dist/{device-pool-CnTAz8X1.mjs → device-pool-Di8Q-9Ro.mjs} +4 -4
  23. package/dist/{device-remote-AQ5rQPqr.mjs → device-remote-Dy1jGj3U.mjs} +547 -468
  24. package/dist/{doctor-B_Ei3bZu.mjs → doctor-B-inAJmt.mjs} +58 -22
  25. package/dist/{error-diagnostics-Vfz83GCF.mjs → error-diagnostics-xxWKNO3-.mjs} +11 -12
  26. package/dist/{exec-jIAlgilk.mjs → exec-DK8KaVHK.mjs} +3 -2
  27. package/dist/{gc-Ckw8RQHi.mjs → gc-ChPFZMRC.mjs} +500 -1114
  28. package/dist/{guide-BiAbhs1J.mjs → guide-DwmaD_Wa.mjs} +882 -528
  29. package/dist/guide-status-CWvti2Lg.mjs +125 -0
  30. package/dist/idle-DpRLp5lj.mjs +157 -0
  31. package/dist/in-use-CjUluqIX.mjs +245 -0
  32. package/dist/{ios-BL2NFckr.mjs → ios-B2Fpqvlb.mjs} +25 -59
  33. package/dist/{ios-BzUJWk1K.mjs → ios-Dd-hYJBh.mjs} +130 -89
  34. package/dist/{ios-device-DPsSm0v_.mjs → ios-device-BiOsSVzd.mjs} +1 -1
  35. package/dist/{ios-device-D972i9wf.mjs → ios-device-CtRdEVjx.mjs} +3 -3
  36. package/dist/{launch-verify-Q_OtW1Rf.mjs → launch-verify-CQS_Kg-C.mjs} +5 -5
  37. package/dist/{logs-CI9NQSK7.mjs → logs-MARIy6m9.mjs} +9 -9
  38. package/dist/{metro-DrLHaMn2.mjs → metro-BWLOJ_Wr.mjs} +116 -10
  39. package/dist/{named-ports-CmLQSIRj.mjs → named-ports-DiTfSz6p.mjs} +4 -4
  40. package/dist/{ndjson-9uFNRwfe.mjs → ndjson-CDY9IkVC.mjs} +3 -56
  41. package/dist/{ndjson-DvHSsNU9.d.mts → ndjson-Du3j0AQ9.d.mts} +1 -0
  42. package/dist/{ownership-D15Op8vN.mjs → ownership-D2xbLVoz.mjs} +2 -3
  43. package/dist/ownership-DZjdx8Gq.mjs +1180 -0
  44. package/dist/{ports-BNKoWVWZ.mjs → ports-CLSSFOuz.mjs} +3 -3
  45. package/dist/{project-DS112DYB.mjs → project-BXZzOABt.mjs} +2 -2
  46. package/dist/{reload-ZNJUo1pl.mjs → reload-DoETJ3rl.mjs} +9 -10
  47. package/dist/{server-bare-DWkkcIxV.mjs → server-bare-DVbb7kXH.mjs} +1 -1
  48. package/dist/{server-expo-B_lctBR3.mjs → server-expo-BvOCeakp.mjs} +4 -4
  49. package/dist/server-expo-DBVTdult.mjs +2 -0
  50. package/dist/{settings-D030k0t4.mjs → settings-DOugPlPz.mjs} +16 -428
  51. package/dist/{settings-BKNh5rl4.mjs → settings-EWYNwe72.mjs} +16 -14
  52. package/dist/settings.schema.json +75 -0
  53. package/dist/{simslim-B_LsGLuJ.mjs → simslim-Ca3487H6.mjs} +182 -5
  54. package/dist/{slot-launch-DU9A-gYw.mjs → slot-launch-C5cg0fmk.mjs} +4 -4
  55. package/dist/{spawn-claims-Dn3C_N6w.mjs → spawn-claims-CUleC2cM.mjs} +1 -1
  56. package/dist/{start-DYkkKF0s.mjs → start-F9gv5dcC.mjs} +147 -98
  57. package/dist/start-VoFsPSes.mjs +2 -0
  58. package/dist/{state-NcJzMEBF.mjs → state-WGdIbi_d.mjs} +2 -2
  59. package/dist/{stats-DG9e66Rz.mjs → stats-BAgJaLA4.mjs} +1 -1
  60. package/dist/{stats-B63-JVAY.mjs → stats-DBYJ5bxL.mjs} +4 -4
  61. package/dist/{status-S6ehL4Ui.mjs → status-DLCD-o3s.mjs} +63 -231
  62. package/dist/status-Dr4fRkym.mjs +216 -0
  63. package/dist/{guide-status-BAMVU0ZA.mjs → stim-installations-CINXy_su.mjs} +3 -124
  64. package/dist/{stop-BO28HGqF.mjs → stop-Dj4pfmyv.mjs} +22 -18
  65. package/dist/{stop-T1R-cZRz.mjs → stop-ZvOeTmKb.mjs} +2 -2
  66. package/dist/supervisor-run.d.mts +11 -2
  67. package/dist/supervisor-run.mjs +185 -17
  68. package/dist/{workspace-process-lock-DWaiRD0e.mjs → workspace-process-lock-BXA96myD.mjs} +2 -2
  69. package/dist/workspaces-BTUyFfkv.mjs +1003 -0
  70. package/dist/{worktree-DKhSF0UX.mjs → worktree-4aZg2NnI.mjs} +1 -1
  71. package/dist/{worktree-LGB-UwgG.mjs → worktree-BMS7GeqB.mjs} +40 -122
  72. package/dist/{worktree-R_cUlE7s.mjs → worktree-BlizKDpZ.mjs} +143 -18
  73. package/dist/{xcode-BZqyxh3e.mjs → xcode-B2tBkf0m.mjs} +9 -158
  74. package/package.json +6 -5
  75. package/dist/build-progress-CVqkfPC6.mjs +0 -188
  76. package/dist/device-lease-Crs-HkJY.mjs +0 -366
  77. package/dist/logs-query-Cqma3WIu.mjs +0 -298
  78. package/dist/ownership-DCQPuWEc.mjs +0 -489
  79. package/dist/public-http-probe-CyMDrQ3c.mjs +0 -61
  80. package/dist/server-expo-CeILEu86.mjs +0 -2
  81. package/dist/sim-pool-KaIsp2Ft.mjs +0 -723
  82. package/dist/spawn-entry-nCE6m770.mjs +0 -14
  83. package/dist/workspace-state-DF2gCFhx.mjs +0 -169
@@ -1,723 +0,0 @@
1
- import { B as assignSlotDevice, T as withConfigLock, U as deviceSlotPlatforms, d as getConfigPath, g as loadConfig, k as ownership_claim_exports, q as removeSlotDevice, s as ensureConfig, u as getConfigDir, x as saveConfig } from "./config-Cp9lM3wX.mjs";
2
- import { t as getExecutor } from "./exec-jIAlgilk.mjs";
3
- import { r as createNdjsonWriter } from "./ndjson-9uFNRwfe.mjs";
4
- import { b as workspaceLogsDir } from "./workspace-state-DF2gCFhx.mjs";
5
- import { u as resolvePackageJson } from "./project-DS112DYB.mjs";
6
- import { n as stripAnsi } from "./process-output-Fpl8PYi8.mjs";
7
- import { n as expoBinFromPackage, r as expoBinPath, s as findBinUpward } from "./server-expo-B_lctBR3.mjs";
8
- import { createRequire } from "node:module";
9
- import { existsSync, readFileSync } from "node:fs";
10
- import { join } from "node:path";
11
- import { pathToFileURL } from "node:url";
12
- import { format, isDeepStrictEqual } from "node:util";
13
- import { AsyncLocalStorage } from "node:async_hooks";
14
- //#region src/engine/remote-cache.ts
15
- const EAS_PROVIDER_PACKAGE = "eas-build-cache-provider";
16
- const RESOLVE_TIMEOUT_MS = 3e4;
17
- const UPLOAD_TIMEOUT_MS = 6e4;
18
- const CONFIG_TIMEOUT_MS = 3e4;
19
- const DYNAMIC_CONFIG_FILES = [
20
- "app.config.ts",
21
- "app.config.js",
22
- "app.config.mjs",
23
- "app.config.cjs"
24
- ];
25
- const TIMED_OUT = Symbol("timed-out");
26
- function dynamicConfigFile(root) {
27
- for (const name of DYNAMIC_CONFIG_FILES) if (existsSync(join(root, name))) return name;
28
- return null;
29
- }
30
- function providerFromConfig(config) {
31
- if (!config || typeof config !== "object") return null;
32
- const expoField = config.expo;
33
- const exp = expoField && typeof expoField === "object" ? expoField : config;
34
- return exp.buildCacheProvider ?? exp.experiments?.buildCacheProvider ?? null;
35
- }
36
- function ownerFromConfig(config) {
37
- if (!config || typeof config !== "object") return null;
38
- const expoField = config.expo;
39
- const owner = (expoField && typeof expoField === "object" ? expoField : config).owner;
40
- return typeof owner === "string" && owner.trim() !== "" ? owner.trim() : null;
41
- }
42
- function normalizeProvider(raw) {
43
- if (raw === null || raw === void 0 || raw === "") return null;
44
- if (raw === "eas") return {
45
- name: "eas",
46
- reference: EAS_PROVIDER_PACKAGE,
47
- options: {}
48
- };
49
- if (typeof raw === "object") {
50
- const obj = raw;
51
- if (typeof obj.plugin === "string" && obj.plugin.trim() !== "") {
52
- const reference = obj.plugin.trim();
53
- return {
54
- name: reference,
55
- reference,
56
- options: obj.options && typeof obj.options === "object" ? obj.options : {}
57
- };
58
- }
59
- }
60
- return { invalid: typeof raw === "string" ? `"${raw}"` : JSON.stringify(raw) };
61
- }
62
- function runOptionsFor(platform) {
63
- return platform === "android" ? { variant: "debug" } : { configuration: "Debug" };
64
- }
65
- function isProviderPlugin(plugin) {
66
- if (!plugin || typeof plugin !== "object") return false;
67
- const p = plugin;
68
- const resolves = typeof p.resolveBuildCache === "function" || typeof p.resolveRemoteBuildCache === "function";
69
- const uploads = typeof p.uploadBuildCache === "function" || typeof p.uploadRemoteBuildCache === "function";
70
- return resolves && uploads;
71
- }
72
- function cacheLevel(value) {
73
- return value === "local" || value === "remote" ? value : false;
74
- }
75
- function exitAfterFlush(code = 0, { exit = (c) => process.exit(c), stream = process.stdout } = {}) {
76
- try {
77
- stream.write("", () => exit(code));
78
- } catch {
79
- exit(code);
80
- }
81
- }
82
- function readProjectConfig(root, { run = null, timeoutMs = CONFIG_TIMEOUT_MS } = {}) {
83
- const dynamic = dynamicConfigFile(root);
84
- if (!dynamic) {
85
- const file = join(root, "app.json");
86
- if (!existsSync(file)) return {
87
- config: null,
88
- source: null
89
- };
90
- try {
91
- return {
92
- config: JSON.parse(readFileSync(file, "utf-8")),
93
- source: "app.json"
94
- };
95
- } catch (err) {
96
- return { unavailable: `app.json could not be parsed: ${firstLine(err)}` };
97
- }
98
- }
99
- const bin = expoBinPath(root);
100
- 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)` };
101
- const exec = run || ((file, args, opts) => getExecutor().runFile(file, args, opts));
102
- let stdout;
103
- try {
104
- stdout = exec(bin, [
105
- "config",
106
- "--json",
107
- root
108
- ], { timeoutMs });
109
- } catch (err) {
110
- return { unavailable: `\`expo config --json\` failed: ${firstLine(err)}` };
111
- }
112
- try {
113
- return {
114
- config: JSON.parse(String(stdout)),
115
- source: dynamic
116
- };
117
- } catch (err) {
118
- return { unavailable: `\`expo config --json\` did not print JSON: ${firstLine(err)}` };
119
- }
120
- }
121
- async function loadPlugin(projectRoot, reference, { requireFrom = null } = {}) {
122
- const localRequire = requireFrom ? requireFrom(projectRoot) : createRequire(join(projectRoot, "package.json"));
123
- const file = localRequire.resolve(reference);
124
- let mod;
125
- try {
126
- mod = localRequire(file);
127
- } catch (err) {
128
- if (err?.code !== "ERR_REQUIRE_ESM") throw err;
129
- mod = await import(pathToFileURL(file).href);
130
- }
131
- const plugin = mod?.default ?? mod;
132
- if (!isProviderPlugin(plugin)) throw new Error(`"${reference}" does not export resolveBuildCache and uploadBuildCache functions`);
133
- return plugin;
134
- }
135
- async function loadProjectProvider(projectRoot, { isExpo = true, run = null, requireFrom = null, timeoutMs = CONFIG_TIMEOUT_MS } = {}) {
136
- if (!isExpo) return { none: true };
137
- const read = readProjectConfig(projectRoot, {
138
- run,
139
- timeoutMs
140
- });
141
- if (read.unavailable) return { unavailable: read.unavailable };
142
- const normalized = normalizeProvider(providerFromConfig(read.config));
143
- if (!normalized) return { none: true };
144
- if (normalized.invalid) return { unavailable: `buildCacheProvider is ${normalized.invalid}, which is not "eas" or { plugin: <module> }` };
145
- if (normalized.reference === "@stim-cli/expo-build-cache") return { none: true };
146
- let plugin;
147
- try {
148
- plugin = await loadPlugin(projectRoot, normalized.reference, { requireFrom });
149
- } catch (err) {
150
- const missing = err?.code === "MODULE_NOT_FOUND";
151
- 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)}` };
152
- }
153
- return {
154
- provider: {
155
- plugin,
156
- options: normalized.options ?? {}
157
- },
158
- name: normalized.name,
159
- owner: ownerFromConfig(read.config)
160
- };
161
- }
162
- const WHOAMI_TIMEOUT_MS = 15e3;
163
- const EAS_CLI_PACKAGE = "eas-cli";
164
- const EAS_CLI_BIN = "eas";
165
- function parseWhoami({ stdout = "", stderr = "", exitCode = 0 } = {}) {
166
- const out = stripAnsi(stdout);
167
- const combined = `${out}\n${stripAnsi(stderr)}`;
168
- if (/^\s*Not logged in\s*$/m.test(combined)) return { loggedOut: true };
169
- if (exitCode !== 0) return { unknown: firstLine(combined.trim() || `eas whoami exited ${exitCode}`) };
170
- const lines = out.split("\n").map((line) => line.trim()).filter((line) => line !== "");
171
- if (lines.length === 0) return { unknown: "eas whoami printed nothing" };
172
- const raw = lines[0];
173
- if (raw === void 0) return { unknown: "eas whoami printed nothing" };
174
- const viaToken = /\(authenticated using EXPO_TOKEN\)\s*$/.test(raw);
175
- const display = raw.replace(/\s*\(authenticated using EXPO_TOKEN\)\s*$/, "").trim();
176
- const accounts = [];
177
- for (const line of lines) {
178
- const name = /^\u2022\s*(\S+)\s*\(Role:/.exec(line)?.[1];
179
- if (name !== void 0) accounts.push(name);
180
- }
181
- if (accounts.length === 0 && !display.endsWith("(robot)") && display !== "robot") accounts.push(display);
182
- return {
183
- loggedIn: true,
184
- account: display,
185
- accounts: accounts.length ? accounts : null,
186
- viaToken
187
- };
188
- }
189
- function isEasAuthFailureText(text) {
190
- const t = stripAnsi(text || "");
191
- if (t.trim() === "") return false;
192
- 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);
193
- }
194
- function easAuthNote(status) {
195
- const { code, account, owner, reason, phase = "resolve" } = status || {};
196
- const because = reason ? ` (${reason})` : "";
197
- 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");
198
- 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`;
199
- return null;
200
- }
201
- function resolveEasCliBin(projectRoot, { lookupPath = null } = {}) {
202
- const fromPackage = expoBinFromPackage(resolvePackageJson(projectRoot, EAS_CLI_PACKAGE), EAS_CLI_BIN);
203
- if (fromPackage) return {
204
- file: fromPackage,
205
- source: "project"
206
- };
207
- const shim = findBinUpward(projectRoot, EAS_CLI_BIN);
208
- if (shim) return {
209
- file: shim,
210
- source: "project"
211
- };
212
- const onPath = lookupPath ? lookupPath() : getExecutor().findExecutable(EAS_CLI_BIN);
213
- const file = (String(onPath || "").split("\n")[0] ?? "").trim();
214
- return file ? {
215
- file,
216
- source: "path"
217
- } : null;
218
- }
219
- const easAuthCache = /* @__PURE__ */ new Map();
220
- function checkEasAuth({ projectRoot, owner = null, run = null, resolveBin = null, timeoutMs = WHOAMI_TIMEOUT_MS, cache = easAuthCache }) {
221
- const key = `${projectRoot}::${owner || ""}`;
222
- if (cache?.has(key)) return cache.get(key);
223
- const answer = probeEasAuth({
224
- projectRoot,
225
- owner,
226
- run,
227
- resolveBin,
228
- timeoutMs
229
- });
230
- cache?.set(key, answer);
231
- return answer;
232
- }
233
- function probeEasAuth({ projectRoot, owner, run, resolveBin, timeoutMs }) {
234
- const bin = (resolveBin || resolveEasCliBin)(projectRoot);
235
- if (!bin) return {
236
- failed: true,
237
- code: "no-cli",
238
- reason: "no `eas` executable is resolvable from this project or on PATH",
239
- remedy: "Install eas-cli (`npm i -g eas-cli`, or as a project devDependency), then run `eas login`."
240
- };
241
- const exec = run || ((file, args, opts) => getExecutor().runFile(file, args, opts));
242
- let result;
243
- try {
244
- result = {
245
- stdout: String(exec(bin.file, ["whoami"], { timeoutMs }) ?? ""),
246
- exitCode: 0
247
- };
248
- } catch (e) {
249
- const err = e;
250
- if (err?.code === "ETIMEDOUT" || err?.signal === "SIGTERM" || err?.killed) return { unknown: `eas whoami timed out after ${timeoutMs}ms` };
251
- result = {
252
- stdout: String(err?.stdout ?? ""),
253
- stderr: String(err?.stderr ?? err?.message ?? ""),
254
- exitCode: typeof err?.status === "number" ? err.status : 1
255
- };
256
- }
257
- const parsed = parseWhoami(result);
258
- if (parsed.loggedOut) return {
259
- failed: true,
260
- code: "logged-out",
261
- reason: "eas whoami says \"Not logged in\"",
262
- remedy: "Run `eas login` (or set EXPO_TOKEN)."
263
- };
264
- if (parsed.unknown) return { unknown: parsed.unknown };
265
- if (owner && Array.isArray(parsed.accounts) && !parsed.accounts.includes(owner)) return {
266
- failed: true,
267
- code: "wrong-account",
268
- account: parsed.account,
269
- accounts: parsed.accounts,
270
- owner,
271
- reason: `eas is authenticated as ${parsed.account} (accounts: ${parsed.accounts.join(", ")}), which does not include this project's owner ${owner}`,
272
- remedy: `Run \`eas login\` as a member of ${owner}, or set EXPO_TOKEN to a token for it.`
273
- };
274
- return {
275
- ok: true,
276
- account: parsed.account,
277
- accounts: parsed.accounts,
278
- viaToken: parsed.viaToken,
279
- source: bin.source
280
- };
281
- }
282
- const capturing = [];
283
- const abandoned = /* @__PURE__ */ new Set();
284
- let patched = null;
285
- const PROVIDER_CONTEXT = new AsyncLocalStorage();
286
- function uploadDestination(lines) {
287
- const text = (lines || []).map(stripAnsi);
288
- for (const line of text) {
289
- const url = /(https?:\/\/[^\s'"]+)/.exec(line)?.[1];
290
- if (url !== void 0) return url.replace(/[.,)\]]+$/, "");
291
- }
292
- for (const line of text) {
293
- const slug = /\bto\s+(@?[\w.-]+\/[\w.-]+)/i.exec(line)?.[1];
294
- if (slug !== void 0) return slug.replace(/[.,)\]]+$/, "");
295
- }
296
- return null;
297
- }
298
- function providerNote(text) {
299
- return `${"cache".padEnd(11)} ${text}`;
300
- }
301
- function currentFrame() {
302
- const store = PROVIDER_CONTEXT.getStore();
303
- return store && (capturing.includes(store) || abandoned.has(store)) ? store : null;
304
- }
305
- function install() {
306
- if (patched && process.stdout.write === patched.patchedWrite) return;
307
- const stdout = process.stdout;
308
- const write = stdout.write.bind(stdout);
309
- const log = console.log;
310
- const passthrough = write;
311
- const patchedWrite = ((chunk, encoding, callback) => {
312
- const frame = currentFrame();
313
- if (!frame) return passthrough(chunk, encoding, callback);
314
- const cb = typeof encoding === "function" ? encoding : callback;
315
- absorb(frame, typeof chunk === "string" ? chunk : String(chunk));
316
- if (typeof cb === "function") cb();
317
- return true;
318
- });
319
- const patchedLog = (...args) => {
320
- const frame = currentFrame();
321
- if (!frame) return log(...args);
322
- absorb(frame, `${format(...args)}\n`);
323
- };
324
- stdout.write = patchedWrite;
325
- console.log = patchedLog;
326
- patched = {
327
- stdout,
328
- write,
329
- log,
330
- patchedWrite,
331
- patchedLog
332
- };
333
- }
334
- function uninstall() {
335
- if (!patched || capturing.length || abandoned.size) return;
336
- if (patched.stdout.write === patched.patchedWrite) patched.stdout.write = patched.write;
337
- if (console.log === patched.patchedLog) console.log = patched.log;
338
- patched = null;
339
- }
340
- function absorb(frame, chunk) {
341
- try {
342
- process.stderr.write(chunk);
343
- } catch {}
344
- frame.pending += chunk;
345
- let index = frame.pending.indexOf("\n");
346
- while (index !== -1) {
347
- emitLine(frame, frame.pending.slice(0, index));
348
- frame.pending = frame.pending.slice(index + 1);
349
- index = frame.pending.indexOf("\n");
350
- }
351
- }
352
- function emitLine(frame, raw) {
353
- const line = stripAnsi(raw).trim();
354
- if (line === "") return;
355
- frame.lines.push(line);
356
- const writer = frame.writer();
357
- try {
358
- writer?.write({
359
- src: "build",
360
- level: "debug",
361
- event: "provider",
362
- msg: line
363
- });
364
- } catch {}
365
- frame.onLine?.(line);
366
- }
367
- function beginCapture({ logWriter = null, projectRoot = null, platform = null, onLine = null } = {}) {
368
- let own = null;
369
- const frame = {
370
- lines: [],
371
- pending: "",
372
- onLine,
373
- writer: () => {
374
- if (logWriter) return logWriter;
375
- if (own) return own;
376
- if (!projectRoot || !platform) return null;
377
- own = createNdjsonWriter(join(workspaceLogsDir(projectRoot), `build-${platform}.ndjson`));
378
- return own;
379
- },
380
- close: () => {
381
- own?.close?.();
382
- own = null;
383
- }
384
- };
385
- capturing.push(frame);
386
- install();
387
- return frame;
388
- }
389
- function endCapture(frame) {
390
- if (!frame) return;
391
- const at = capturing.lastIndexOf(frame);
392
- if (at !== -1) capturing.splice(at, 1);
393
- abandoned.delete(frame);
394
- if (frame.pending !== "") {
395
- const rest = frame.pending;
396
- frame.pending = "";
397
- emitLine(frame, rest);
398
- }
399
- frame.close();
400
- uninstall();
401
- }
402
- function abandonCapture(frame, work) {
403
- if (!frame) return;
404
- const at = capturing.lastIndexOf(frame);
405
- if (at !== -1) capturing.splice(at, 1);
406
- abandoned.add(frame);
407
- Promise.resolve(work).then(() => endCapture(frame), () => endCapture(frame));
408
- }
409
- async function resolveRemote({ provider, platform, projectRoot, fingerprintHash, runOptions = null, timeoutMs = RESOLVE_TIMEOUT_MS, logWriter = null } = {}) {
410
- if (!provider?.plugin || !fingerprintHash) return null;
411
- const opts = runOptions || runOptionsFor(platform);
412
- const outcome = await withBudget(async () => {
413
- const props = {
414
- fingerprintHash: await providerFingerprint({
415
- provider,
416
- platform,
417
- projectRoot,
418
- runOptions: opts
419
- }) ?? fingerprintHash,
420
- platform,
421
- runOptions: opts,
422
- projectRoot
423
- };
424
- return typeof provider.plugin.resolveBuildCache === "function" ? provider.plugin.resolveBuildCache(props, provider.options) : provider.plugin.resolveRemoteBuildCache(props, provider.options);
425
- }, timeoutMs, {
426
- logWriter,
427
- projectRoot,
428
- platform
429
- });
430
- if (outcome.timedOut) return { timedOut: true };
431
- if (outcome.error) return { failed: firstLine(outcome.error) };
432
- const appPath = typeof outcome.value === "string" ? outcome.value.trim() : "";
433
- if (!appPath) return null;
434
- if (!existsSync(appPath)) return { failed: `returned ${appPath}, which does not exist` };
435
- return { appPath };
436
- }
437
- async function uploadRemote({ provider, platform, projectRoot, fingerprintHash, buildPath, runOptions = null, timeoutMs = UPLOAD_TIMEOUT_MS, logWriter = null, note = (line) => console.error(line) } = {}) {
438
- if (!provider?.plugin || !fingerprintHash || !buildPath) return { skipped: true };
439
- const opts = runOptions || runOptionsFor(platform);
440
- let announced = false;
441
- const onLine = (line) => {
442
- if (announced) return;
443
- const dest = uploadDestination([line]);
444
- if (!dest) return;
445
- announced = true;
446
- note(providerNote(`uploading to ${dest}`));
447
- };
448
- const outcome = await withBudget(async () => {
449
- const props = {
450
- projectRoot,
451
- platform,
452
- fingerprintHash: await providerFingerprint({
453
- provider,
454
- platform,
455
- projectRoot,
456
- runOptions: opts
457
- }) ?? fingerprintHash,
458
- buildPath,
459
- runOptions: opts
460
- };
461
- return typeof provider.plugin.uploadBuildCache === "function" ? provider.plugin.uploadBuildCache(props, provider.options) : provider.plugin.uploadRemoteBuildCache(props, provider.options);
462
- }, timeoutMs, {
463
- logWriter,
464
- projectRoot,
465
- platform,
466
- onLine
467
- });
468
- if (outcome.timedOut) return { timedOut: true };
469
- if (outcome.error) return { failed: firstLine(outcome.error) };
470
- if (typeof outcome.value !== "string" || outcome.value.trim() === "") {
471
- const authLine = outcome.lines.find((line) => isEasAuthFailureText(line));
472
- return { failed: authLine ? firstLine(authLine) : "the provider returned no upload destination" };
473
- }
474
- const destination = uploadDestination(outcome.lines);
475
- return destination ? {
476
- uploaded: true,
477
- destination
478
- } : { uploaded: true };
479
- }
480
- async function providerFingerprint({ provider, platform, projectRoot, runOptions }) {
481
- if (typeof provider.plugin.calculateFingerprintHash !== "function") return null;
482
- try {
483
- const hash = await provider.plugin.calculateFingerprintHash({
484
- projectRoot,
485
- platform,
486
- runOptions
487
- }, provider.options);
488
- return typeof hash === "string" && hash.trim() !== "" ? hash.trim() : null;
489
- } catch {
490
- return null;
491
- }
492
- }
493
- async function withBudget(factory, ms, capture) {
494
- let timer = null;
495
- const timeout = new Promise((resolve) => {
496
- timer = setTimeout(() => resolve(TIMED_OUT), ms);
497
- timer?.unref?.();
498
- });
499
- const frame = beginCapture(capture || {});
500
- const work = Promise.resolve().then(() => PROVIDER_CONTEXT.run(frame, factory)).then((value) => ({ value }), (error) => ({ error }));
501
- try {
502
- const settled = await Promise.race([work, timeout]);
503
- if (settled === TIMED_OUT) {
504
- abandonCapture(frame, work);
505
- return {
506
- timedOut: true,
507
- lines: frame.lines
508
- };
509
- }
510
- endCapture(frame);
511
- return {
512
- ...settled,
513
- lines: frame.lines
514
- };
515
- } catch (err) {
516
- endCapture(frame);
517
- throw err;
518
- } finally {
519
- if (timer) clearTimeout(timer);
520
- }
521
- }
522
- function firstLine(err) {
523
- const line = (String(err?.message || err || "unknown error").trim().split("\n")[0] ?? "").trim();
524
- return line.length > 200 ? `${line.slice(0, 197)}...` : line;
525
- }
526
- const POOL_SETTING_REMEDY = "Run `stim guide settings` for the device pool bounds and where it can be set.";
527
- const MAX_SETTING = {
528
- ios: {
529
- key: "iosParkedMax",
530
- env: "STIM_POOL_IOS_PARKED_MAX"
531
- },
532
- android: {
533
- key: "androidParkedMax",
534
- env: "STIM_POOL_ANDROID_PARKED_MAX"
535
- }
536
- };
537
- function parseMax(raw, strings) {
538
- const value = strings && typeof raw === "string" ? /^\d+$/.test(raw.trim()) ? Number(raw.trim()) : NaN : raw;
539
- if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 0) return null;
540
- return value;
541
- }
542
- function parkedMaxSetting(platform, { config, env = process.env } = {}) {
543
- const { key, env: envKey } = MAX_SETTING[platform];
544
- const fromEnv = env[envKey];
545
- const explicit = fromEnv !== void 0 && fromEnv !== "";
546
- const pool = (config === void 0 ? loadConfig() : config)?.pool;
547
- if (!explicit && pool !== void 0 && (pool === null || typeof pool !== "object" || Array.isArray(pool))) return {
548
- max: 0,
549
- error: "Invalid pool value. Expected an object with simulator and emulator bounds."
550
- };
551
- const fromConfig = pool !== null && typeof pool === "object" && !Array.isArray(pool) ? pool[key] : void 0;
552
- const raw = explicit ? fromEnv : fromConfig;
553
- if (raw === void 0) return {
554
- max: env.STIM_HOME ? 0 : 3,
555
- error: null
556
- };
557
- const parsed = parseMax(raw, explicit);
558
- if (parsed === null) return {
559
- max: 0,
560
- error: `Invalid ${explicit ? envKey : `pool.${key}`} value ${JSON.stringify(raw)}. Expected a whole number of parked ${platform === "ios" ? "simulators" : "emulators"}, 0 or more.`
561
- };
562
- return {
563
- max: explicit ? parsed : env.STIM_HOME ? 0 : parsed,
564
- error: null
565
- };
566
- }
567
- function isParkedRecord(value, platform) {
568
- if (value === null || typeof value !== "object" || Array.isArray(value)) return false;
569
- const record = value;
570
- 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"));
571
- }
572
- function poolBlock(config) {
573
- const raw = config?.parked;
574
- const block = raw !== null && typeof raw === "object" && !Array.isArray(raw) ? raw : {};
575
- const read = (platform) => {
576
- const list = block[platform];
577
- return Array.isArray(list) ? list.filter((record) => isParkedRecord(record, platform)) : [];
578
- };
579
- return {
580
- ios: read("ios"),
581
- android: read("android")
582
- };
583
- }
584
- function readParked(platform, { config } = {}) {
585
- return poolBlock(config === void 0 ? loadConfig() : config)[platform];
586
- }
587
- function writeParked(config, platform, records) {
588
- config.parked = {
589
- ...poolBlock(config),
590
- [platform]: records
591
- };
592
- }
593
- function oldestFirst(records) {
594
- return records.toSorted((a, b) => String(a.parkedAt).localeCompare(String(b.parkedAt)));
595
- }
596
- function isLegacyDeletionClaim(value) {
597
- if (value === void 0) return false;
598
- if (value === null || typeof value !== "object" || Array.isArray(value)) return true;
599
- const marker = value;
600
- return marker.kind !== "ownership-claim" || typeof marker.claimId !== "string" || marker.claimId.length === 0;
601
- }
602
- function selectParked(records, { deviceTypeIdentifier, runtimeIdentifier }) {
603
- return oldestFirst(records.filter((r) => !isLegacyDeletionClaim(r.deletionClaim) && r.deviceTypeIdentifier === deviceTypeIdentifier && r.runtimeIdentifier === runtimeIdentifier));
604
- }
605
- function evictOverflow(records, max) {
606
- if (records.length <= max) return {
607
- keep: [...records],
608
- evicted: []
609
- };
610
- const ordered = oldestFirst(records);
611
- const evicted = ordered.slice(0, ordered.length - max);
612
- const dropped = new Set(evicted.map((r) => r.udid));
613
- return {
614
- keep: records.filter((r) => !dropped.has(r.udid)),
615
- evicted
616
- };
617
- }
618
- function parkSim({ platform, projectPath, slot = "default", record, max }) {
619
- return withConfigLock(() => {
620
- const cfg = ensureConfig();
621
- const current = deviceSlotPlatforms(cfg.projects[projectPath], slot)?.[platform];
622
- const currentId = platform === "ios" ? current?.deviceUdid : current?.avdName;
623
- if (!current?.owned || currentId !== record.udid) throw new Error(`The ${platform === "ios" ? "simulator" : "emulator"} assignment changed before parking.`);
624
- const { keep, evicted } = evictOverflow([...readParked(platform, { config: cfg }).filter((r) => r.udid !== record.udid), record], max);
625
- writeParked(cfg, platform, [...keep, ...evicted]);
626
- const project = cfg.projects[projectPath];
627
- if (project) removeSlotDevice(project, platform, slot);
628
- saveConfig(cfg);
629
- return evicted;
630
- });
631
- }
632
- function adoptParked({ platform, projectPath, slot = "default", udid, device }) {
633
- const claim = claimParkedOperation(platform, udid);
634
- if (!claim) return null;
635
- try {
636
- return withConfigLock(() => {
637
- const cfg = ensureConfig();
638
- const records = readParked(platform, { config: cfg });
639
- const taken = records.find((r) => r.udid === udid);
640
- if (!taken || isLegacyDeletionClaim(taken.deletionClaim)) return null;
641
- if (deviceSlotPlatforms(cfg.projects[projectPath], slot)?.[platform]) return null;
642
- writeParked(cfg, platform, records.filter((r) => r.udid !== udid));
643
- const project = cfg.projects[projectPath];
644
- if (!project) throw new Error(`Project not registered: ${projectPath}`);
645
- assignSlotDevice(project, platform, device, slot);
646
- saveConfig(cfg);
647
- const adopted = { ...taken };
648
- delete adopted.deletionClaim;
649
- return adopted;
650
- });
651
- } finally {
652
- (0, ownership_claim_exports.releaseClaim)(claim);
653
- }
654
- }
655
- function claimParkedOperation(platform, udid) {
656
- const attempt = (0, ownership_claim_exports.tryAcquireClaim)({
657
- root: join(getConfigDir(), "pool-locks", platform, `${encodeURIComponent(udid.toLowerCase())}.lock`),
658
- mode: "exclusive",
659
- label: `parked ${platform} device ${udid}`
660
- });
661
- if (attempt.pending) (0, ownership_claim_exports.releaseClaim)(attempt.pending);
662
- return attempt.acquired ?? null;
663
- }
664
- function removeParkedAfter(platform, udid, beforeRemove) {
665
- const claim = claimParkedOperation(platform, udid);
666
- if (!claim) return null;
667
- try {
668
- const claimed = withConfigLock(() => {
669
- const cfg = loadConfig();
670
- if (!cfg) return null;
671
- const records = readParked(platform, { config: cfg });
672
- const current = records.find((candidate) => candidate.udid === udid);
673
- if (!current) return null;
674
- if (isLegacyDeletionClaim(current.deletionClaim)) throw new Error(`Parked ${platform} device ${udid} has a legacy deletionClaim in ${getConfigPath()}. Its PID does not establish whether the original operation finished. Keep the device and pool record; after verifying that neither the old Stim process nor its native child is using it, remove only that record's deletionClaim field and retry.`);
675
- const record = { ...current };
676
- delete record.deletionClaim;
677
- const marked = {
678
- ...record,
679
- deletionClaim: {
680
- kind: "ownership-claim",
681
- claimId: claim.claimId
682
- }
683
- };
684
- writeParked(cfg, platform, records.map((candidate) => candidate.udid === udid ? marked : candidate));
685
- saveConfig(cfg);
686
- return {
687
- record,
688
- marked
689
- };
690
- });
691
- if (!claimed) return null;
692
- let completed = false;
693
- let removed = null;
694
- try {
695
- (0, ownership_claim_exports.markClaimChildPending)(claim);
696
- try {
697
- beforeRemove(claimed.record);
698
- } finally {
699
- (0, ownership_claim_exports.clearClaimChild)(claim);
700
- }
701
- completed = true;
702
- } finally {
703
- withConfigLock(() => {
704
- const cfg = loadConfig();
705
- if (!cfg) return;
706
- const records = readParked(platform, { config: cfg });
707
- const current = records.find((candidate) => candidate.udid === udid);
708
- if (!isDeepStrictEqual(current, claimed.marked)) return;
709
- writeParked(cfg, platform, completed ? records.filter((candidate) => candidate.udid !== udid) : records.map((candidate) => candidate.udid === udid ? claimed.record : candidate));
710
- saveConfig(cfg);
711
- if (completed) removed = claimed.record;
712
- });
713
- }
714
- return removed;
715
- } finally {
716
- (0, ownership_claim_exports.releaseClaim)(claim);
717
- }
718
- }
719
- function dropParked(platform, udid) {
720
- return removeParkedAfter(platform, udid, () => {}) !== null;
721
- }
722
- //#endregion
723
- export { uploadRemote as S, loadProjectProvider as _, parkSim as a, resolveEasCliBin as b, removeParkedAfter as c, UPLOAD_TIMEOUT_MS as d, cacheLevel as f, isEasAuthFailureText as g, exitAfterFlush as h, isLegacyDeletionClaim as i, selectParked as l, easAuthNote as m, adoptParked as n, parkedMaxSetting as o, checkEasAuth as p, dropParked as r, readParked as s, POOL_SETTING_REMEDY as t, RESOLVE_TIMEOUT_MS as u, ownerFromConfig as v, resolveRemote as x, providerFromConfig as y };