stim 1.8.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 (91) hide show
  1. package/README.md +23 -155
  2. package/dist/{android-DWssqHQ8.mjs → android-787HhP5w.mjs} +168 -39
  3. package/dist/{android-BRgBYzU0.mjs → android-DBkeHwpm.mjs} +250 -200
  4. package/dist/{android-DeYdjjBP.mjs → android-DPov-fv2.mjs} +2 -2
  5. package/dist/{android-cas-SWIjzeuL.mjs → android-cas-CITmIeWY.mjs} +22 -14
  6. package/dist/android-cas-compiler.mjs +2 -2
  7. package/dist/app-install-CrJ6t_bv.mjs +819 -0
  8. package/dist/budget-BP4jZZL4.mjs +620 -0
  9. package/dist/build-progress-BXx-ZBe4.mjs +512 -0
  10. package/dist/{cache-manifest-CYJi8-Hx.mjs → cache-manifest-Pubfp8wV.mjs} +4 -4
  11. package/dist/cache-manifest.mjs +1 -1
  12. package/dist/cli.mjs +22 -19
  13. package/dist/collector-run.d.mts +7 -1
  14. package/dist/collector-run.mjs +10 -9
  15. package/dist/{command-output-B3ycpsYv.mjs → command-output-D5z2_bcF.mjs} +11 -2
  16. package/dist/{config-B7iyKWkL.mjs → config-BEq0Qw_a.mjs} +134 -121
  17. package/dist/{dependency-state-D0M7oKA7.mjs → dependency-state-r9UesA9a.mjs} +2 -2
  18. package/dist/{deps-oCXVNEqQ.mjs → deps-DP4eWqea.mjs} +8 -5
  19. package/dist/{detached-entry-Bpo6ZY_I.mjs → detached-entry-DJHoca49.mjs} +1 -1
  20. package/dist/{device-BUoZyMoR.mjs → dev-client-92U593KT.mjs} +1090 -660
  21. package/dist/{device-RdujjHLB.mjs → device-DhTZe7L4.mjs} +13 -20
  22. package/dist/{build-lock-CgtsB6TV.mjs → device-lease-CbEaIk7b.mjs} +481 -27
  23. package/dist/{device-pool-BxRwdufO.mjs → device-pool-Di8Q-9Ro.mjs} +7 -7
  24. package/dist/{device-remote-ByN8P6CB.mjs → device-remote-Dy1jGj3U.mjs} +645 -119
  25. package/dist/{doctor-BMt156qe.mjs → doctor-B-inAJmt.mjs} +137 -113
  26. package/dist/{error-diagnostics-D1Kaf-eT.mjs → error-diagnostics-xxWKNO3-.mjs} +22 -17
  27. package/dist/exec-DK8KaVHK.mjs +133 -0
  28. package/dist/{gc-v2YcoJvm.mjs → gc-ChPFZMRC.mjs} +836 -813
  29. package/dist/{guide-BTAlD1_y.mjs → guide-DwmaD_Wa.mjs} +953 -209
  30. package/dist/guide-status-CWvti2Lg.mjs +125 -0
  31. package/dist/idle-DpRLp5lj.mjs +157 -0
  32. package/dist/{build-slots-C-oAHRT1.mjs → in-use-CjUluqIX.mjs} +102 -8
  33. package/dist/{ios-BcCiI4TS.mjs → ios-B2Fpqvlb.mjs} +60 -71
  34. package/dist/{ios-BP04pY5f.mjs → ios-Dd-hYJBh.mjs} +241 -234
  35. package/dist/{ios-device-CFXA46ez.mjs → ios-device-BiOsSVzd.mjs} +3 -2
  36. package/dist/{ios-device-CauFJiYx.mjs → ios-device-CtRdEVjx.mjs} +149 -52
  37. package/dist/launch-verify-CQS_Kg-C.mjs +365 -0
  38. package/dist/{logs-CakdBTtm.mjs → logs-MARIy6m9.mjs} +20 -15
  39. package/dist/metro-BWLOJ_Wr.mjs +409 -0
  40. package/dist/{named-ports-DzMOlmaX.mjs → named-ports-DiTfSz6p.mjs} +4 -4
  41. package/dist/{ndjson-BZwI1NBv.mjs → ndjson-CDY9IkVC.mjs} +23 -43
  42. package/dist/{ndjson-DvHSsNU9.d.mts → ndjson-Du3j0AQ9.d.mts} +1 -0
  43. package/dist/{ownership-Cp52QAK1.mjs → ownership-D2xbLVoz.mjs} +2 -3
  44. package/dist/{teardown-BJqEzPo_.mjs → ownership-DZjdx8Gq.mjs} +664 -612
  45. package/dist/{ports-BIbJaKNW.mjs → ports-CLSSFOuz.mjs} +3 -3
  46. package/dist/{process-output-Dl5uKE03.mjs → process-output-Fpl8PYi8.mjs} +1 -1
  47. package/dist/{project-DDZWf_16.mjs → project-BXZzOABt.mjs} +8 -3
  48. package/dist/{reload-BdypPbjM.mjs → reload-DoETJ3rl.mjs} +11 -13
  49. package/dist/{server-bare-BQkyxa_b.mjs → server-bare-DVbb7kXH.mjs} +2 -2
  50. package/dist/{server-expo-BVAA1OqJ.mjs → server-expo-BvOCeakp.mjs} +8 -7
  51. package/dist/server-expo-DBVTdult.mjs +2 -0
  52. package/dist/{settings-BXXorVM2.mjs → settings-DOugPlPz.mjs} +59 -159
  53. package/dist/settings-EWYNwe72.mjs +378 -0
  54. package/dist/settings.schema.json +1064 -0
  55. package/dist/simslim-Ca3487H6.mjs +436 -0
  56. package/dist/{slot-launch-ZUUe0TQP.mjs → slot-launch-C5cg0fmk.mjs} +4 -4
  57. package/dist/spawn-claims-CUleC2cM.mjs +49 -0
  58. package/dist/{start-CmxtOKjU.mjs → start-F9gv5dcC.mjs} +159 -114
  59. package/dist/start-VoFsPSes.mjs +2 -0
  60. package/dist/{state-DZobzxLW.mjs → state-WGdIbi_d.mjs} +5 -3
  61. package/dist/{stats-BYcZ6n1h.mjs → stats-BAgJaLA4.mjs} +66 -5
  62. package/dist/{stats-CLg5RuDS.mjs → stats-DBYJ5bxL.mjs} +4 -4
  63. package/dist/status-DLCD-o3s.mjs +764 -0
  64. package/dist/status-Dr4fRkym.mjs +216 -0
  65. package/dist/{guide-status-Craq9z0t.mjs → stim-installations-CINXy_su.mjs} +3 -122
  66. package/dist/{stop-C8JW6kKp.mjs → stop-Dj4pfmyv.mjs} +111 -31
  67. package/dist/{stop-B1kOpYei.mjs → stop-ZvOeTmKb.mjs} +2 -2
  68. package/dist/supervisor-run.d.mts +11 -2
  69. package/dist/supervisor-run.mjs +228 -42
  70. package/dist/{workspace-process-lock-BYfZz_S-.mjs → workspace-process-lock-BXA96myD.mjs} +14 -9
  71. package/dist/workspaces-BTUyFfkv.mjs +1003 -0
  72. package/dist/worktree-4aZg2NnI.mjs +2 -0
  73. package/dist/{worktree-CFLA-6MX.mjs → worktree-BMS7GeqB.mjs} +523 -61
  74. package/dist/{worktree-FG_ZKKdb.mjs → worktree-BlizKDpZ.mjs} +200 -54
  75. package/dist/{xcode-B6YaWeg0.mjs → xcode-B2tBkf0m.mjs} +66 -57
  76. package/package.json +6 -6
  77. package/skill/SKILL.md +2 -0
  78. package/dist/app-install-BDbsSgCl.mjs +0 -1175
  79. package/dist/dev-client-BmT-ioFI.mjs +0 -797
  80. package/dist/device-lease-Ffz_M5t0.mjs +0 -359
  81. package/dist/exec-B29XNuhP.mjs +0 -77
  82. package/dist/logs-query-BGL-Pl12.mjs +0 -290
  83. package/dist/metro-C7bcJ0uo.mjs +0 -233
  84. package/dist/ownership-wolE-0Do.mjs +0 -470
  85. package/dist/public-http-probe-CyMDrQ3c.mjs +0 -61
  86. package/dist/reclaim-KJ-0uWEF.mjs +0 -361
  87. package/dist/server-expo-YDDG3eP7.mjs +0 -2
  88. package/dist/spawn-entry-nCE6m770.mjs +0 -14
  89. package/dist/status-DdkLki47.mjs +0 -426
  90. package/dist/workspace-state-BT5E3SA2.mjs +0 -146
  91. package/dist/{metro-store-CDDZHtPl.mjs → metro-store-DzeWkfqW.mjs} +1 -1
@@ -1,290 +0,0 @@
1
- import { a as parseNdjsonLine, i as levelRank, o as parseNdjsonText } from "./ndjson-BZwI1NBv.mjs";
2
- import { closeSync, openSync, readFileSync, readSync, readdirSync, statSync } from "fs";
3
- import { join } from "path";
4
- import { StringDecoder } from "string_decoder";
5
- //#region src/diagnostics/logs-query.ts
6
- const SINCE_UNITS = {
7
- s: 1e3,
8
- m: 6e4,
9
- h: 36e5
10
- };
11
- const SINCE_FORMS = "30s, 5m, 2h";
12
- function parseSince(text) {
13
- if (typeof text !== "string") return { error: `Invalid --since value ${JSON.stringify(text)}. Use a count and a unit, e.g. ${SINCE_FORMS}.` };
14
- const m = /^(\d+)\s*([smh])$/i.exec(text.trim());
15
- if (!m) return { error: `Invalid --since value "${text}". Use a count and a unit, e.g. ${SINCE_FORMS}.` };
16
- const unit = (m[2] ?? "").toLowerCase();
17
- return { ms: parseInt(m[1] ?? "", 10) * SINCE_UNITS[unit] };
18
- }
19
- function compileGrep(pattern) {
20
- if (pattern instanceof RegExp) return { re: pattern };
21
- try {
22
- return { re: new RegExp(String(pattern)) };
23
- } catch (err) {
24
- return { error: `Invalid --grep pattern "${pattern}": ${err.message}` };
25
- }
26
- }
27
- const ERROR_SOURCES = [
28
- "metro",
29
- "client",
30
- "build"
31
- ];
32
- function markerWindow(records) {
33
- let launchTs = null;
34
- let bundleTs = null;
35
- for (const r of records) {
36
- if (r?.marker !== true) continue;
37
- const ts = tsOf(r);
38
- if (ts === null) continue;
39
- if (r.src === "metro") {
40
- if (bundleTs === null || ts > bundleTs) bundleTs = ts;
41
- } else if (launchTs === null || ts > launchTs) launchTs = ts;
42
- }
43
- return {
44
- launchTs,
45
- bundleTs
46
- };
47
- }
48
- function recordMatches(record, criteria = {}) {
49
- if (!record) return false;
50
- if (criteria.slot !== void 0 && (record.slot ?? "default") !== criteria.slot) return false;
51
- const { sources, minLevel, grep, sinceTs, errorsOnly, markerTs, bundleMarkerTs } = criteria;
52
- if (sources && sources.length > 0 && !sources.includes(record.src) && !(criteria.includeNativeCrashes && record.src === "device" && record.event === "native_crash")) return false;
53
- if (minLevel && levelRank(record.level) < levelRank(minLevel)) return false;
54
- if (errorsOnly) {
55
- if (record.level !== "error" && record.level !== "fatal") return false;
56
- if (typeof markerTs === "number") {
57
- const ts = tsOf(record);
58
- if (ts === null || ts <= markerTs) return false;
59
- }
60
- if (typeof bundleMarkerTs === "number" && record.src === "metro") {
61
- const ts = tsOf(record);
62
- if (ts === null || ts < bundleMarkerTs) return false;
63
- }
64
- }
65
- if (typeof sinceTs === "number") {
66
- const ts = tsOf(record);
67
- if (ts === null || ts < sinceTs) return false;
68
- }
69
- if (grep) {
70
- const re = grep instanceof RegExp ? grep : compileGrep(grep).re;
71
- if (!re || String(record.msg ?? "").search(re) === -1) return false;
72
- }
73
- return true;
74
- }
75
- function buildCriteria({ slot, sources, minLevel, since, grep, errorsOnly, markerTs, bundleMarkerTs, now } = {}) {
76
- const criteria = {
77
- ...slot === void 0 ? {} : { slot },
78
- errorsOnly: Boolean(errorsOnly),
79
- includeNativeCrashes: Boolean(errorsOnly && !sources?.length)
80
- };
81
- if (sources && sources.length > 0) criteria.sources = sources;
82
- else if (criteria.errorsOnly) criteria.sources = ERROR_SOURCES;
83
- if (minLevel) criteria.minLevel = minLevel;
84
- if (typeof markerTs === "number") criteria.markerTs = markerTs;
85
- if (typeof bundleMarkerTs === "number") criteria.bundleMarkerTs = bundleMarkerTs;
86
- if (since !== void 0 && since !== null && since !== "") {
87
- const parsed = parseSince(since);
88
- if (parsed.error) throw new Error(parsed.error);
89
- criteria.sinceTs = (typeof now === "number" ? now : Date.now()) - parsed.ms;
90
- }
91
- if (grep !== void 0 && grep !== null && grep !== "") {
92
- const compiled = compileGrep(grep);
93
- if (compiled.error) throw new Error(compiled.error);
94
- criteria.grep = compiled.re;
95
- }
96
- return criteria;
97
- }
98
- function logFiles(dir) {
99
- let entries;
100
- try {
101
- entries = readdirSync(dir, { withFileTypes: true });
102
- } catch {
103
- return [];
104
- }
105
- return entries.filter((e) => e.isFile() && e.name.endsWith(".ndjson")).map((e) => e.name).toSorted();
106
- }
107
- function fileSizes(dir) {
108
- const sizes = {};
109
- for (const name of logFiles(dir)) try {
110
- sizes[name] = statSync(join(dir, name)).size;
111
- } catch {}
112
- return sizes;
113
- }
114
- function readLogRecords(dir) {
115
- const all = [];
116
- for (const name of logFiles(dir)) {
117
- let text;
118
- try {
119
- text = readFileSync(join(dir, name), "utf-8");
120
- } catch {
121
- continue;
122
- }
123
- for (const record of parseNdjsonText(text)) all.push(record);
124
- }
125
- return sortByTs(all);
126
- }
127
- function isExpoErrorContext(record, event) {
128
- if (record.src !== "metro" || record.raw !== true || record.event !== event || typeof record.msg !== "string") return false;
129
- return /^Code: \S/.test(record.msg) || /^\s*>?\s*\d+\s*\|/.test(record.msg) || /^\s*\|\s*\^/.test(record.msg) || /^Call Stack$/.test(record.msg) || /^\s+.+\([^()]+:\d+:\d+\)\s*$/.test(record.msg) || /^\s+at\s+\S+:\d+:\d+\s*$/.test(record.msg);
130
- }
131
- function attachExpoErrorContext(all, matched) {
132
- return matched.map((record) => {
133
- if (record.src !== "metro" || record.raw !== true || record.level !== "error" && record.level !== "fatal" || typeof record.msg !== "string") return record;
134
- const index = all.findIndex((entry) => entry.ts === record.ts && entry.src === record.src && entry.msg === record.msg && entry.event === record.event);
135
- if (index === -1) return record;
136
- const context = [];
137
- for (let i = index + 1; i < all.length; i += 1) {
138
- const next = all[i];
139
- if (next.src !== "metro") continue;
140
- if (!isExpoErrorContext(next, record.event)) break;
141
- context.push(next.msg);
142
- }
143
- return context.length > 0 ? {
144
- ...record,
145
- msg: [record.msg, ...context].join("\n")
146
- } : record;
147
- });
148
- }
149
- function includeBareErrorContext(all, matched, launchTs, sinceTs) {
150
- if (!matched.some((record) => record.src === "client" && (record.level === "error" || record.level === "fatal"))) return matched;
151
- const renderedContext = [];
152
- for (const record of all) {
153
- if (record.src !== "client" || record.event !== "client_symbolication") continue;
154
- const ts = tsOf(record);
155
- if (launchTs !== null && (ts === null || ts <= launchTs)) continue;
156
- if (sinceTs !== void 0 && (ts === null || ts < sinceTs)) continue;
157
- renderedContext.push({
158
- ...record,
159
- msg: `Metro symbolication context (not correlated to a specific client error)\n${String(record.msg ?? "")}`,
160
- errorContext: true
161
- });
162
- }
163
- return sortByTs([...matched, ...renderedContext]);
164
- }
165
- function launchMarkersBySlot(records) {
166
- const markers = /* @__PURE__ */ new Map();
167
- for (const record of records) {
168
- if (record.marker !== true || record.src === "metro") continue;
169
- const ts = tsOf(record);
170
- const slot = record.slot ?? "default";
171
- if (ts !== null && ts > (markers.get(slot) ?? -Infinity)) markers.set(slot, ts);
172
- }
173
- return markers;
174
- }
175
- function queryLogs({ slot, dir, sources, minLevel, since, grep, tail, errorsOnly, errorContext, now } = {}) {
176
- const all = readLogRecords(dir).filter((record) => slot === void 0 || (record.slot ?? "default") === slot);
177
- if (all.length === 0) return [];
178
- const { launchTs, bundleTs } = errorsOnly ? markerWindow(all) : {
179
- launchTs: null,
180
- bundleTs: null
181
- };
182
- const criteria = buildCriteria({
183
- slot,
184
- sources,
185
- minLevel,
186
- since,
187
- grep,
188
- errorsOnly,
189
- now,
190
- markerTs: launchTs === null ? void 0 : launchTs,
191
- bundleMarkerTs: bundleTs === null ? void 0 : bundleTs
192
- });
193
- const slotMarkers = launchMarkersBySlot(all);
194
- let matched = all.filter((record) => recordMatches(record, {
195
- ...criteria,
196
- markerTs: record.src === "metro" || record.src === "client" ? criteria.markerTs : slotMarkers.get(record.slot ?? "default")
197
- }));
198
- if (typeof tail === "number" && tail >= 0 && matched.length > tail) matched = matched.slice(matched.length - tail);
199
- return errorContext ? includeBareErrorContext(all, attachExpoErrorContext(all, matched), launchTs, criteria.sinceTs) : matched;
200
- }
201
- function tailRead(prev, size) {
202
- const state = prev && typeof prev.offset === "number" ? prev : {
203
- offset: 0,
204
- partial: ""
205
- };
206
- if (size < state.offset) return {
207
- start: 0,
208
- prev: {
209
- offset: 0,
210
- partial: ""
211
- }
212
- };
213
- return {
214
- start: state.offset,
215
- prev: state
216
- };
217
- }
218
- function advanceTail(prev, chunk, size) {
219
- const lines = ((prev && typeof prev.partial === "string" ? prev.partial : "") + (chunk || "")).split("\n");
220
- const partial = lines.pop();
221
- const records = [];
222
- for (const line of lines) {
223
- const record = parseNdjsonLine(line);
224
- if (record) records.push(record);
225
- }
226
- return {
227
- state: {
228
- offset: size,
229
- partial
230
- },
231
- records
232
- };
233
- }
234
- function followLogs({ dir, onRecord, criteria = {}, intervalMs = 500, offsets = null }) {
235
- const state = /* @__PURE__ */ new Map();
236
- const decoders = /* @__PURE__ */ new Map();
237
- for (const [name, size] of Object.entries(offsets || fileSizes(dir))) {
238
- state.set(name, {
239
- offset: size,
240
- partial: ""
241
- });
242
- decoders.set(name, new StringDecoder("utf8"));
243
- }
244
- function pollFile(name) {
245
- const path = join(dir, name);
246
- const size = statSync(path).size;
247
- const entry = state.get(name);
248
- const { start, prev } = tailRead(entry, size);
249
- if (prev !== entry) decoders.set(name, new StringDecoder("utf8"));
250
- if (!decoders.has(name)) decoders.set(name, new StringDecoder("utf8"));
251
- let chunk = "";
252
- if (size > start) {
253
- const fd = openSync(path, "r");
254
- try {
255
- const buf = Buffer.allocUnsafe(size - start);
256
- const read = readSync(fd, buf, 0, size - start, start);
257
- chunk = decoders.get(name).write(buf.subarray(0, read));
258
- } finally {
259
- closeSync(fd);
260
- }
261
- }
262
- const next = advanceTail(prev, chunk, size);
263
- state.set(name, next.state);
264
- for (const record of next.records) if (recordMatches(record, criteria)) onRecord(record);
265
- }
266
- function poll() {
267
- for (const name of logFiles(dir)) try {
268
- pollFile(name);
269
- } catch {}
270
- }
271
- const timer = setInterval(poll, intervalMs);
272
- return function stop() {
273
- clearInterval(timer);
274
- };
275
- }
276
- function tsOf(record) {
277
- return typeof record?.ts === "number" && Number.isFinite(record.ts) ? record.ts : null;
278
- }
279
- function sortByTs(records) {
280
- return records.toSorted((a, b) => {
281
- const ta = tsOf(a);
282
- const tb = tsOf(b);
283
- if (ta === null && tb === null) return 0;
284
- if (ta === null) return 1;
285
- if (tb === null) return -1;
286
- return ta - tb;
287
- });
288
- }
289
- //#endregion
290
- export { followLogs as a, queryLogs as c, fileSizes as i, readLogRecords as l, buildCriteria as n, logFiles as o, compileGrep as r, parseSince as s, attachExpoErrorContext as t };
@@ -1,233 +0,0 @@
1
- import { t as getExecutor } from "./exec-B29XNuhP.mjs";
2
- import { A as isOnMountedVolume, g as loadConfig, j as listMountedVolumes, n as allMetroPorts, r as claimMetroPort, v as removeProject, w as process_identity_exports } from "./config-B7iyKWkL.mjs";
3
- import { r as readWorkspaceState } from "./workspace-state-BT5E3SA2.mjs";
4
- import { existsSync, readlinkSync, realpathSync } from "fs";
5
- import { sep } from "path";
6
- import { request } from "http";
7
- import { connect } from "net";
8
- //#region src/ports.ts
9
- function isMetroRunning(port) {
10
- return new Promise((resolve) => {
11
- const req = request({
12
- hostname: "localhost",
13
- port,
14
- path: "/status",
15
- timeout: 2e3
16
- }, (res) => {
17
- let data = "";
18
- res.on("data", (chunk) => {
19
- data += chunk;
20
- });
21
- res.on("end", () => resolve(data.includes("packager-status:running")));
22
- });
23
- req.on("error", () => resolve(false));
24
- req.on("timeout", () => {
25
- req.destroy();
26
- resolve(false);
27
- });
28
- req.end();
29
- });
30
- }
31
- function isPortFree(port, { timeoutMs = 400 } = {}) {
32
- return new Promise((resolve) => {
33
- const sock = connect({
34
- port,
35
- host: "127.0.0.1"
36
- });
37
- const done = (free) => {
38
- sock.removeAllListeners();
39
- sock.destroy();
40
- resolve(free);
41
- };
42
- sock.setTimeout(timeoutMs);
43
- sock.once("connect", () => done(false));
44
- sock.once("error", () => done(true));
45
- sock.once("timeout", () => done(false));
46
- });
47
- }
48
- const FIRST_PORT = 8082;
49
- async function computeNextPort(isFree = isPortFree) {
50
- const taken = new Set(allMetroPorts());
51
- for (let port = FIRST_PORT; port < 8282; port++) {
52
- if (taken.has(port)) continue;
53
- if (await isFree(port)) return port;
54
- }
55
- throw new Error(`Found no free Metro port between ${FIRST_PORT} and 8281. Free one up, or stop a stale bundler (\`stim status\`, \`stim stop <port>\`).`);
56
- }
57
- async function findReclaimablePort(excludeProjectPath, probe = isMetroRunning, { isMounted = isOnMountedVolume, mountedVolumes } = {}) {
58
- const cfg = loadConfig();
59
- if (!cfg?.projects) return null;
60
- const mounted = mountedVolumes || listMountedVolumes();
61
- const candidates = [];
62
- for (const [path, proj] of Object.entries(cfg.projects)) {
63
- if (path === excludeProjectPath) continue;
64
- if (Object.keys(proj.ports ?? {}).length) continue;
65
- if (existsSync(path)) continue;
66
- if (!isMounted(path, mounted)) continue;
67
- if (typeof proj.metroPort === "number") candidates.push({
68
- port: proj.metroPort,
69
- ownerPath: path
70
- });
71
- }
72
- for (const c of candidates) if (!await probe(c.port)) return c;
73
- return null;
74
- }
75
- async function allocatePort(projectPath, probe = isMetroRunning, isFree = isPortFree) {
76
- const reclaim = await findReclaimablePort(projectPath, probe);
77
- if (reclaim && await isFree(reclaim.port)) {
78
- removeProject(reclaim.ownerPath);
79
- return reclaim.port;
80
- }
81
- return computeNextPort(isFree);
82
- }
83
- const RESERVE_ATTEMPTS = 5;
84
- async function reserveMetroPort(projectPath, probe = isMetroRunning, isFree = isPortFree) {
85
- for (let attempt = 0; attempt < RESERVE_ATTEMPTS; attempt++) {
86
- const port = await allocatePort(projectPath, probe, isFree);
87
- const claimed = claimMetroPort(projectPath, port);
88
- if (claimed !== null) return claimed;
89
- }
90
- throw new Error(`Could not reserve a Metro port after ${RESERVE_ATTEMPTS} attempts: another Stim run claimed each one first. Retry.`);
91
- }
92
- //#endregion
93
- //#region src/metro.ts
94
- /**
95
- * True when some process with this pid exists right now. It cannot tell a recycled pid from the
96
- * process that first held it, so it is only valid for a pid this run spawned and still holds a
97
- * handle on. For a pid read from a record on disk, decide with `inspectProcessIdentity` on that
98
- * record's process token, or take an ownership claim (`ownership-claim.ts`): this answer would keep
99
- * a dead holder's record looking live until some unrelated process exits.
100
- */
101
- function pidExists(pid) {
102
- if (!Number.isSafeInteger(pid) || pid <= 0) return false;
103
- try {
104
- process.kill(pid, 0);
105
- return true;
106
- } catch (error) {
107
- return error.code !== "ESRCH";
108
- }
109
- }
110
- function parseLsofPids(out) {
111
- if (!out) return [];
112
- return String(out).split("\n").map((s) => parseInt(s.trim(), 10)).filter((n) => Number.isFinite(n));
113
- }
114
- function addressPort(address) {
115
- const colon = String(address ?? "").lastIndexOf(":");
116
- return colon < 0 ? NaN : Number(String(address).slice(colon + 1));
117
- }
118
- function parseNetstatPids(out, port) {
119
- const pids = [];
120
- for (const line of String(out ?? "").split("\n")) {
121
- const cols = line.trim().split(/\s+/);
122
- if (cols.length < 5 || cols[0]?.toUpperCase() !== "TCP") continue;
123
- if (addressPort(cols[1]) !== port || addressPort(cols[2]) !== 0) continue;
124
- const pid = Number(cols.at(-1));
125
- if (Number.isSafeInteger(pid) && pid > 0 && !pids.includes(pid)) pids.push(pid);
126
- }
127
- return pids;
128
- }
129
- function listeningPids(port, platform = process.platform) {
130
- const pids = parseLsofPids(getExecutor().runQuiet(`lsof -nP -iTCP:${port} -sTCP:LISTEN -t`));
131
- if (pids.length > 0 || platform !== "win32") return pids;
132
- return parseNetstatPids(getExecutor().runQuiet("netstat -ano"), port);
133
- }
134
- function parseLsofCwd(out) {
135
- if (!out) return null;
136
- const lines = String(out).split("\n");
137
- const idx = lines.findIndex((l) => l === "fcwd");
138
- if (idx === -1) return null;
139
- const nLine = lines.slice(idx + 1).find((l) => l.startsWith("n"));
140
- return nLine ? nLine.slice(1) : null;
141
- }
142
- function processCwd(pid) {
143
- if (process.platform === "linux") try {
144
- return readlinkSync(`/proc/${pid}/cwd`);
145
- } catch {}
146
- return parseLsofCwd(getExecutor().runQuiet(`lsof -a -p ${pid} -d cwd -Fn`));
147
- }
148
- function canonicalPath(path) {
149
- try {
150
- return realpathSync(path);
151
- } catch {
152
- return path;
153
- }
154
- }
155
- function isInsideProject(cwd, projectPath) {
156
- if (!cwd || !projectPath) return false;
157
- const a = canonicalPath(cwd);
158
- const b = canonicalPath(projectPath);
159
- return a === b || a.startsWith(b.endsWith(sep) ? b : b + sep);
160
- }
161
- const NOT_OURS_UNRESPONSIVE = "unresponsive";
162
- const NOT_OURS_UNREADABLE_CWD = "unreadable-cwd";
163
- const NOT_OURS_FOREIGN_CWD = "foreign-cwd";
164
- function ownedSupervisor(projectPath, port) {
165
- const supervisor = readWorkspaceState(canonicalPath(projectPath))?.supervisor;
166
- if (supervisor?.port !== port || (0, process_identity_exports.inspectProcessIdentity)(supervisor) !== "same") return null;
167
- return supervisor;
168
- }
169
- async function resolveProjectMetro(port, projectPath, { probe = isMetroRunning, cwdOf = processCwd } = {}) {
170
- const pid = listeningPids(port)[0];
171
- if (pid === void 0) return { missing: true };
172
- if (!await probe(port)) return {
173
- notOurs: `pid ${pid} on port ${port} does not answer Metro's /status`,
174
- kind: NOT_OURS_UNRESPONSIVE,
175
- pid
176
- };
177
- const cwd = cwdOf(pid);
178
- if (!cwd) {
179
- const owner = ownedSupervisor(projectPath, port);
180
- if (owner && (pid === owner.pid || pid === owner.serverPid)) return { metro: {
181
- pid,
182
- leader: owner.pid,
183
- cwd: canonicalPath(projectPath),
184
- processToken: owner.processToken
185
- } };
186
- return {
187
- notOurs: `pid ${pid} on port ${port}: working directory could not be read`,
188
- kind: NOT_OURS_UNREADABLE_CWD,
189
- pid
190
- };
191
- }
192
- if (!isInsideProject(cwd, projectPath)) return {
193
- notOurs: `pid ${pid} on port ${port} runs from ${cwd}, outside ${projectPath}`,
194
- kind: NOT_OURS_FOREIGN_CWD,
195
- pid
196
- };
197
- const owner = ownedSupervisor(projectPath, port);
198
- return { metro: {
199
- pid,
200
- leader: owner ? owner.pid : pid,
201
- cwd,
202
- ...owner ? { processToken: owner.processToken } : {}
203
- } };
204
- }
205
- /**
206
- * Terminate a process and everything it spawned. On POSIX `group` signals the process group, which
207
- * is what a detached leader owns. Windows has no process groups, and its SIGTERM is
208
- * TerminateProcess: no handler runs and no child is reached, so a spawned dev server or `adb
209
- * logcat` would outlive its parent. taskkill /T is the only route to the tree there, and it is
210
- * always forceful.
211
- */
212
- function signalProcessTree(pid, signal = "SIGTERM", { group = false, platform = process.platform } = {}) {
213
- if (platform !== "win32") return process.kill(group ? -pid : pid, signal);
214
- return getExecutor().runFileQuiet("taskkill", [
215
- "/PID",
216
- String(pid),
217
- "/T",
218
- "/F"
219
- ]) !== null;
220
- }
221
- function killMetroTree(leader, processToken) {
222
- if (!leader || leader === process.pid || (0, process_identity_exports.inspectProcessIdentity)({
223
- pid: leader,
224
- processToken
225
- }) !== "same") return false;
226
- try {
227
- return signalProcessTree(leader, "SIGTERM", { group: true });
228
- } catch {
229
- return false;
230
- }
231
- }
232
- //#endregion
233
- export { resolveProjectMetro as a, isPortFree as c, pidExists as i, reserveMetroPort as l, killMetroTree as n, signalProcessTree as o, listeningPids as r, isMetroRunning as s, NOT_OURS_FOREIGN_CWD as t };