spana-test 0.7.0 → 0.9.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 (96) hide show
  1. package/dist/agent/index.d.ts +2 -2
  2. package/dist/agent/index.js +9 -9
  3. package/dist/{allure-RNMEYTXS.js → allure-RAEK4SIH.js} +2 -2
  4. package/dist/allure-RAEK4SIH.js.map +1 -0
  5. package/dist/{android-4NVTZMHL.js → android-6BOQTMM3.js} +2 -2
  6. package/dist/app-DSh1ejLh.d.ts +1266 -0
  7. package/dist/{chunk-H27IBIGA.js → chunk-2AFWVHQK.js} +63 -43
  8. package/dist/chunk-2AFWVHQK.js.map +1 -0
  9. package/dist/{chunk-RURZVMZ7.js → chunk-2KRVN4WN.js} +3 -3
  10. package/dist/{chunk-T5CROOR7.js → chunk-3UVSUVHW.js} +1828 -299
  11. package/dist/chunk-3UVSUVHW.js.map +1 -0
  12. package/dist/{chunk-6B5Y75V4.js → chunk-ALPQES3J.js} +1001 -281
  13. package/dist/chunk-ALPQES3J.js.map +1 -0
  14. package/dist/{chunk-2IXXEXTL.js → chunk-FP6PVHHR.js} +2 -2
  15. package/dist/{chunk-KNSAHEXI.js → chunk-IGTK5MHB.js} +8 -8
  16. package/dist/chunk-JPZCZHL4.js +79 -0
  17. package/dist/chunk-JPZCZHL4.js.map +1 -0
  18. package/dist/{chunk-JYFPZRCN.js → chunk-JZZ2W2XH.js} +5 -2
  19. package/dist/chunk-JZZ2W2XH.js.map +1 -0
  20. package/dist/{chunk-HCG4CJKR.js → chunk-SF7UYW4I.js} +3 -3
  21. package/dist/{chunk-T3EBOYLS.js → chunk-UEWZ2EXL.js} +1314 -129
  22. package/dist/chunk-UEWZ2EXL.js.map +1 -0
  23. package/dist/{chunk-HYSTRWYN.js → chunk-VP6V4XEJ.js} +4 -4
  24. package/dist/{chunk-S5JNNDXS.js → chunk-WV3ALL3H.js} +65 -37
  25. package/dist/chunk-WV3ALL3H.js.map +1 -0
  26. package/dist/chunk-Z6K4QQAR.js +358 -0
  27. package/dist/chunk-Z6K4QQAR.js.map +1 -0
  28. package/dist/cli.js +23 -11
  29. package/dist/cli.js.map +1 -1
  30. package/dist/config-loader-F5YAY7RP.js +9 -0
  31. package/dist/{console-MI2XB5RG.js → console-BGAK7Z2L.js} +11 -1
  32. package/dist/{console-MI2XB5RG.js.map → console-BGAK7Z2L.js.map} +1 -1
  33. package/dist/{daemon-manager-FBISTX24.js → daemon-manager-2EQDVUVM.js} +10 -2
  34. package/dist/{discover-LHEBSUIP.js → discover-RLSKEBAX.js} +5 -5
  35. package/dist/{doctor-command-WPEVZEZ4.js → doctor-command-YTCQ2SC7.js} +26 -18
  36. package/dist/doctor-command-YTCQ2SC7.js.map +1 -0
  37. package/dist/{flow-g6AICPAl.d.ts → flow-CSMwD9Fh.d.ts} +3 -29
  38. package/dist/gherkin/steps.d.ts +2 -2
  39. package/dist/{html-IKCTZH2U.js → html-JO2YNRWX.js} +3 -3
  40. package/dist/html-JO2YNRWX.js.map +1 -0
  41. package/dist/index.d.ts +215 -21
  42. package/dist/index.js +246 -147
  43. package/dist/index.js.map +1 -1
  44. package/dist/{installer-VUPFWP5X.js → installer-5UHTYQTB.js} +4 -4
  45. package/dist/{ios-JPK43TFZ.js → ios-Y4TO5MBR.js} +7 -3
  46. package/dist/{server-EBPYK3VE.js → server-4YLBAZEM.js} +50 -36
  47. package/dist/server-4YLBAZEM.js.map +1 -0
  48. package/dist/{server-IGLBFEU7.js → server-IS4K5FCT.js} +2 -2
  49. package/dist/{session-cJ_tZjCL.d.ts → session-CgvT-Oso.d.ts} +3 -1
  50. package/dist/session-K7FCRKOC.js +18 -0
  51. package/dist/{studio-command-FLA5HKRK.js → studio-command-RFPV2DS7.js} +2 -2
  52. package/dist/{test-command-P5W7UD52.js → test-command-UEJG5AI6.js} +223 -27
  53. package/dist/test-command-UEJG5AI6.js.map +1 -0
  54. package/native/darwin-arm64/libspana_native.dylib +0 -0
  55. package/native/darwin-x64/libspana_native.dylib +0 -0
  56. package/native/linux-arm64/libspana_native.so +0 -0
  57. package/native/linux-x64/libspana_native.so +0 -0
  58. package/native/win32-x64/spana_native.dll +0 -0
  59. package/package.json +1 -1
  60. package/studio-dist/assets/index-CBFsOh-9.js +193 -0
  61. package/studio-dist/assets/index-DH_18EyL.css +1 -0
  62. package/studio-dist/index.html +2 -2
  63. package/dist/allure-RNMEYTXS.js.map +0 -1
  64. package/dist/app-D_UyZBsl.d.ts +0 -915
  65. package/dist/chunk-6B5Y75V4.js.map +0 -1
  66. package/dist/chunk-DTNK54C2.js +0 -127
  67. package/dist/chunk-DTNK54C2.js.map +0 -1
  68. package/dist/chunk-H27IBIGA.js.map +0 -1
  69. package/dist/chunk-JYFPZRCN.js.map +0 -1
  70. package/dist/chunk-OBCFACUW.js +0 -28
  71. package/dist/chunk-OBCFACUW.js.map +0 -1
  72. package/dist/chunk-S5JNNDXS.js.map +0 -1
  73. package/dist/chunk-T3EBOYLS.js.map +0 -1
  74. package/dist/chunk-T5CROOR7.js.map +0 -1
  75. package/dist/config-loader-NIDQGP3K.js +0 -9
  76. package/dist/doctor-command-WPEVZEZ4.js.map +0 -1
  77. package/dist/html-IKCTZH2U.js.map +0 -1
  78. package/dist/server-EBPYK3VE.js.map +0 -1
  79. package/dist/session-QRWH3SPW.js +0 -18
  80. package/dist/test-command-P5W7UD52.js.map +0 -1
  81. package/studio-dist/assets/index-C-Io44gy.js +0 -193
  82. package/studio-dist/assets/index-DfM9lK4p.css +0 -1
  83. /package/dist/{android-4NVTZMHL.js.map → android-6BOQTMM3.js.map} +0 -0
  84. /package/dist/{chunk-RURZVMZ7.js.map → chunk-2KRVN4WN.js.map} +0 -0
  85. /package/dist/{chunk-2IXXEXTL.js.map → chunk-FP6PVHHR.js.map} +0 -0
  86. /package/dist/{chunk-KNSAHEXI.js.map → chunk-IGTK5MHB.js.map} +0 -0
  87. /package/dist/{chunk-HCG4CJKR.js.map → chunk-SF7UYW4I.js.map} +0 -0
  88. /package/dist/{chunk-HYSTRWYN.js.map → chunk-VP6V4XEJ.js.map} +0 -0
  89. /package/dist/{config-loader-NIDQGP3K.js.map → config-loader-F5YAY7RP.js.map} +0 -0
  90. /package/dist/{daemon-manager-FBISTX24.js.map → daemon-manager-2EQDVUVM.js.map} +0 -0
  91. /package/dist/{discover-LHEBSUIP.js.map → discover-RLSKEBAX.js.map} +0 -0
  92. /package/dist/{installer-VUPFWP5X.js.map → installer-5UHTYQTB.js.map} +0 -0
  93. /package/dist/{ios-JPK43TFZ.js.map → ios-Y4TO5MBR.js.map} +0 -0
  94. /package/dist/{server-IGLBFEU7.js.map → server-IS4K5FCT.js.map} +0 -0
  95. /package/dist/{session-QRWH3SPW.js.map → session-K7FCRKOC.js.map} +0 -0
  96. /package/dist/{studio-command-FLA5HKRK.js.map → studio-command-RFPV2DS7.js.map} +0 -0
@@ -1,11 +1,11 @@
1
1
  import {
2
2
  getHealthyWarmDaemon,
3
3
  registerWarmDaemon
4
- } from "./chunk-DTNK54C2.js";
4
+ } from "./chunk-Z6K4QQAR.js";
5
5
  import {
6
6
  allocatePort,
7
7
  releasePort
8
- } from "./chunk-OBCFACUW.js";
8
+ } from "./chunk-JPZCZHL4.js";
9
9
 
10
10
  // src/drivers/wda/installer.ts
11
11
  import { execSync, spawn } from "child_process";
@@ -214,7 +214,7 @@ async function setupWDAForDevice(deviceUDID, port = 8100, teamId, signingIdentit
214
214
  buildWDAForDevice(deviceUDID, teamId, signingIdentity);
215
215
  }
216
216
  wdaProcess = startWDAOnDevice(deviceUDID, 8100, derivedDataPath);
217
- const { startIproxy } = await import("./ios-JPK43TFZ.js");
217
+ const { startIproxy } = await import("./ios-Y4TO5MBR.js");
218
218
  tunnel = startIproxy(deviceUDID, port, 8100);
219
219
  const maxRetries = 45;
220
220
  for (let i = 0; i < maxRetries; i++) {
@@ -342,4 +342,4 @@ export {
342
342
  setupWDAForDevice,
343
343
  setupWDA
344
344
  };
345
- //# sourceMappingURL=chunk-HYSTRWYN.js.map
345
+ //# sourceMappingURL=chunk-VP6V4XEJ.js.map
@@ -1,17 +1,16 @@
1
1
  import {
2
2
  allocatePort,
3
3
  releasePort
4
- } from "./chunk-OBCFACUW.js";
5
- import {
6
- __require
7
- } from "./chunk-DGUM43GV.js";
4
+ } from "./chunk-JPZCZHL4.js";
8
5
 
9
6
  // src/device/ios.ts
10
- import { execFileSync, execSync } from "child_process";
7
+ import { execFileSync, spawn } from "child_process";
11
8
  import { readFileSync, unlinkSync } from "fs";
12
9
  function listIOSSimulators() {
13
10
  try {
14
- const output = execSync("xcrun simctl list devices -j", { encoding: "utf-8" });
11
+ const output = execFileSync("xcrun", ["simctl", "list", "devices", "-j"], {
12
+ encoding: "utf-8"
13
+ });
15
14
  const data = JSON.parse(output);
16
15
  const simulators = [];
17
16
  for (const [runtime, devices] of Object.entries(data.devices ?? {})) {
@@ -43,7 +42,9 @@ function firstIOSSimulator() {
43
42
  function hasAppInstalledOnSimulator(udid, bundleId) {
44
43
  if (!bundleId) return false;
45
44
  try {
46
- execSync(`xcrun simctl get_app_container ${udid} ${bundleId} app`, { stdio: "ignore" });
45
+ execFileSync("xcrun", ["simctl", "get_app_container", udid, bundleId, "app"], {
46
+ stdio: "ignore"
47
+ });
47
48
  return true;
48
49
  } catch {
49
50
  return false;
@@ -69,15 +70,15 @@ function ensureIOSSimulator(bundleId) {
69
70
  }
70
71
  function bootSimulator(udid) {
71
72
  try {
72
- execSync(`xcrun simctl boot ${udid}`, { stdio: "ignore" });
73
+ execFileSync("xcrun", ["simctl", "boot", udid], { stdio: "ignore" });
73
74
  } catch {
74
75
  }
75
76
  }
76
77
  function installOnSimulator(udid, appPath) {
77
- execSync(`xcrun simctl install ${udid} ${appPath}`);
78
+ execFileSync("xcrun", ["simctl", "install", udid, appPath]);
78
79
  }
79
80
  function launchOnSimulator(udid, bundleId) {
80
- execSync(`xcrun simctl launch ${udid} ${bundleId}`);
81
+ execFileSync("xcrun", ["simctl", "launch", udid, bundleId]);
81
82
  }
82
83
  function launchWithUrlOnSimulator(udid, bundleId, url) {
83
84
  execFileSync("xcrun", ["simctl", "launch", udid, bundleId, "--open-url", url]);
@@ -85,7 +86,7 @@ function launchWithUrlOnSimulator(udid, bundleId, url) {
85
86
  function installedUrlSchemesOnSimulator(udid, bundleId) {
86
87
  if (!bundleId) return [];
87
88
  try {
88
- const appPath = execSync(`xcrun simctl get_app_container ${udid} ${bundleId} app`, {
89
+ const appPath = execFileSync("xcrun", ["simctl", "get_app_container", udid, bundleId, "app"], {
89
90
  encoding: "utf-8"
90
91
  }).trim();
91
92
  const raw = execFileSync(
@@ -106,15 +107,33 @@ function openUrlOnSimulator(udid, url) {
106
107
  }
107
108
  function terminateOnSimulator(udid, bundleId) {
108
109
  try {
109
- execSync(`xcrun simctl terminate ${udid} ${bundleId}`, { stdio: "ignore" });
110
+ execFileSync("xcrun", ["simctl", "terminate", udid, bundleId], { stdio: "ignore" });
110
111
  } catch {
111
112
  }
112
113
  }
114
+ function cloneIOSSimulator(sourceUdid, cloneName) {
115
+ const out = execFileSync("xcrun", ["simctl", "clone", sourceUdid, cloneName], {
116
+ encoding: "utf-8"
117
+ });
118
+ const udid = out.trim();
119
+ if (!udid) {
120
+ throw new Error(`xcrun simctl clone returned empty UDID for ${sourceUdid}`);
121
+ }
122
+ return udid;
123
+ }
124
+ function deleteIOSSimulator(udid) {
125
+ try {
126
+ execFileSync("xcrun", ["simctl", "shutdown", udid], { stdio: "ignore" });
127
+ } catch {
128
+ }
129
+ execFileSync("xcrun", ["simctl", "delete", udid], { stdio: "ignore" });
130
+ }
113
131
  function listIOSPhysicalDevices() {
114
132
  try {
115
133
  const tmpFile = `/tmp/spana-devicectl-${Date.now()}.json`;
116
- execSync(`xcrun devicectl list devices --json-output ${tmpFile} 2>/dev/null`, {
117
- timeout: 1e4
134
+ execFileSync("xcrun", ["devicectl", "list", "devices", "--json-output", tmpFile], {
135
+ timeout: 1e4,
136
+ stdio: "ignore"
118
137
  });
119
138
  const output = readFileSync(tmpFile, "utf-8");
120
139
  try {
@@ -152,9 +171,10 @@ function listIOSPhysicalDevices() {
152
171
  }
153
172
  };
154
173
  var walkUSB = walkUSB2;
155
- const output = execSync("system_profiler SPUSBDataType -json 2>/dev/null", {
174
+ const output = execFileSync("system_profiler", ["SPUSBDataType", "-json"], {
156
175
  encoding: "utf-8",
157
- timeout: 1e4
176
+ timeout: 1e4,
177
+ stdio: ["ignore", "pipe", "ignore"]
158
178
  });
159
179
  const data = JSON.parse(output);
160
180
  const devices = [];
@@ -170,11 +190,10 @@ function firstIOSPhysicalDevice() {
170
190
  }
171
191
  function startIproxy(udid, localPort, devicePort) {
172
192
  try {
173
- execSync("which iproxy", { stdio: "ignore" });
193
+ execFileSync("which", ["iproxy"], { stdio: "ignore" });
174
194
  } catch {
175
195
  throw new Error("iproxy not found. Install with: brew install libimobiledevice");
176
196
  }
177
- const { spawn } = __require("child_process");
178
197
  const proc = spawn("iproxy", [`${localPort}:${devicePort}`, "-u", udid], {
179
198
  stdio: "ignore",
180
199
  detached: true
@@ -212,7 +231,7 @@ function connectPhysicalDevice(udid, wdaPort = 8100) {
212
231
  }
213
232
  function installOnPhysicalDevice(udid, appPath) {
214
233
  try {
215
- execSync(`xcrun devicectl device install app --device ${udid} ${appPath}`, {
234
+ execFileSync("xcrun", ["devicectl", "device", "install", "app", "--device", udid, appPath], {
216
235
  stdio: "inherit",
217
236
  timeout: 12e4
218
237
  });
@@ -226,9 +245,10 @@ function hasAppOnPhysicalDevice(udid, bundleId) {
226
245
  if (!bundleId) return false;
227
246
  try {
228
247
  const tmpFile = `/tmp/spana-applist-${Date.now()}.json`;
229
- execSync(
230
- `xcrun devicectl device info apps --device ${udid} --json-output ${tmpFile} 2>/dev/null`,
231
- { timeout: 15e3 }
248
+ execFileSync(
249
+ "xcrun",
250
+ ["devicectl", "device", "info", "apps", "--device", udid, "--json-output", tmpFile],
251
+ { timeout: 15e3, stdio: "ignore" }
232
252
  );
233
253
  const output = readFileSync(tmpFile, "utf-8");
234
254
  try {
@@ -243,44 +263,50 @@ function hasAppOnPhysicalDevice(udid, bundleId) {
243
263
  var SPANA_ANCHOR = "com.spana.network";
244
264
  function pfctlSetOffline(enable) {
245
265
  if (enable) {
246
- execSync(`echo "block out all
247
- " | sudo pfctl -a ${SPANA_ANCHOR} -f -`, { stdio: "ignore" });
266
+ execFileSync("sudo", ["pfctl", "-a", SPANA_ANCHOR, "-f", "-"], {
267
+ input: "block out all\n",
268
+ stdio: ["pipe", "ignore", "ignore"]
269
+ });
248
270
  try {
249
- execSync("sudo pfctl -e 2>/dev/null", { stdio: "ignore" });
271
+ execFileSync("sudo", ["pfctl", "-e"], { stdio: "ignore" });
250
272
  } catch {
251
273
  }
252
274
  } else {
253
275
  try {
254
- execSync(`sudo pfctl -a ${SPANA_ANCHOR} -F all`, { stdio: "ignore" });
276
+ execFileSync("sudo", ["pfctl", "-a", SPANA_ANCHOR, "-F", "all"], { stdio: "ignore" });
255
277
  } catch {
256
278
  }
257
279
  }
258
280
  }
259
281
  function pfctlSetThrottle(throughputKbps, delayMs) {
260
- execSync(`sudo dnctl pipe 1 config bw ${throughputKbps}Kbit/s delay ${delayMs}ms`, {
261
- stdio: "ignore"
262
- });
263
- execSync(`echo "dummynet out all pipe 1
264
- " | sudo pfctl -a ${SPANA_ANCHOR} -f -`, {
265
- stdio: "ignore"
282
+ execFileSync(
283
+ "sudo",
284
+ ["dnctl", "pipe", "1", "config", "bw", `${throughputKbps}Kbit/s`, "delay", `${delayMs}ms`],
285
+ {
286
+ stdio: "ignore"
287
+ }
288
+ );
289
+ execFileSync("sudo", ["pfctl", "-a", SPANA_ANCHOR, "-f", "-"], {
290
+ input: "dummynet out all pipe 1\n",
291
+ stdio: ["pipe", "ignore", "ignore"]
266
292
  });
267
293
  try {
268
- execSync("sudo pfctl -e 2>/dev/null", { stdio: "ignore" });
294
+ execFileSync("sudo", ["pfctl", "-e"], { stdio: "ignore" });
269
295
  } catch {
270
296
  }
271
297
  }
272
298
  function pfctlResetNetwork() {
273
299
  try {
274
- execSync(`sudo pfctl -a ${SPANA_ANCHOR} -F all`, { stdio: "ignore" });
300
+ execFileSync("sudo", ["pfctl", "-a", SPANA_ANCHOR, "-F", "all"], { stdio: "ignore" });
275
301
  } catch {
276
302
  }
277
303
  try {
278
- execSync("sudo dnctl -q flush", { stdio: "ignore" });
304
+ execFileSync("sudo", ["dnctl", "-q", "flush"], { stdio: "ignore" });
279
305
  } catch {
280
306
  }
281
307
  }
282
308
  function resetSimulatorKeychain(udid) {
283
- execSync(`xcrun simctl keychain ${udid} reset`, { stdio: "ignore" });
309
+ execFileSync("xcrun", ["simctl", "keychain", udid, "reset"], { stdio: "ignore" });
284
310
  }
285
311
  function ensureAppInstalled(opts) {
286
312
  const { udid, bundleId, appPath, isPhysicalDevice } = opts;
@@ -311,6 +337,8 @@ export {
311
337
  installedUrlSchemesOnSimulator,
312
338
  openUrlOnSimulator,
313
339
  terminateOnSimulator,
340
+ cloneIOSSimulator,
341
+ deleteIOSSimulator,
314
342
  listIOSPhysicalDevices,
315
343
  firstIOSPhysicalDevice,
316
344
  startIproxy,
@@ -324,4 +352,4 @@ export {
324
352
  resetSimulatorKeychain,
325
353
  ensureAppInstalled
326
354
  };
327
- //# sourceMappingURL=chunk-S5JNNDXS.js.map
355
+ //# sourceMappingURL=chunk-WV3ALL3H.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/device/ios.ts"],"sourcesContent":["import { execFileSync, spawn } from \"node:child_process\";\nimport { readFileSync, unlinkSync } from \"node:fs\";\nimport { allocatePort, releasePort } from \"../core/port-allocator.js\";\n\nexport interface IOSSimulator {\n udid: string;\n name: string;\n state: \"Booted\" | \"Shutdown\" | string;\n runtime: string; // e.g. \"iOS 17.5\"\n isAvailable: boolean;\n}\n\nexport interface IOSDevice {\n udid: string;\n name: string;\n type: \"simulator\" | \"device\";\n state: string;\n runtime?: string;\n}\n\n/** List iOS simulators */\nexport function listIOSSimulators(): IOSSimulator[] {\n try {\n const output = execFileSync(\"xcrun\", [\"simctl\", \"list\", \"devices\", \"-j\"], {\n encoding: \"utf-8\",\n });\n const data = JSON.parse(output);\n const simulators: IOSSimulator[] = [];\n\n for (const [runtime, devices] of Object.entries(data.devices ?? {})) {\n // runtime looks like \"com.apple.CoreSimulator.SimRuntime.iOS-17-5\"\n const runtimeName = runtime\n .replace(\"com.apple.CoreSimulator.SimRuntime.\", \"\")\n .replaceAll(\"-\", \".\");\n\n for (const device of devices as any[]) {\n simulators.push({\n udid: device.udid,\n name: device.name,\n state: device.state,\n runtime: runtimeName,\n isAvailable: device.isAvailable ?? true,\n });\n }\n }\n\n return simulators;\n } catch {\n return [];\n }\n}\n\n/** List booted iOS simulators */\nexport function listBootedSimulators(): IOSSimulator[] {\n return listIOSSimulators().filter((s) => s.state === \"Booted\" && s.isAvailable);\n}\n\n/** Get first booted simulator, or first available if none booted */\nexport function firstIOSSimulator(): IOSSimulator | null {\n const booted = listBootedSimulators();\n if (booted.length > 0) return booted[0]!;\n\n const available = listIOSSimulators().filter((s) => s.isAvailable);\n return available[0] ?? null;\n}\n\n/** Check whether an app is installed on a simulator */\nexport function hasAppInstalledOnSimulator(udid: string, bundleId: string): boolean {\n if (!bundleId) return false;\n\n try {\n execFileSync(\"xcrun\", [\"simctl\", \"get_app_container\", udid, bundleId, \"app\"], {\n stdio: \"ignore\",\n });\n return true;\n } catch {\n return false;\n }\n}\n\n/** Prefer a simulator that already has the requested app installed */\nexport function firstIOSSimulatorWithApp(bundleId: string): IOSSimulator | null {\n const bootedWithApp = listBootedSimulators().find((sim) =>\n hasAppInstalledOnSimulator(sim.udid, bundleId),\n );\n if (bootedWithApp) return bootedWithApp;\n\n const availableWithApp = listIOSSimulators()\n .filter((sim) => sim.isAvailable)\n .find((sim) => hasAppInstalledOnSimulator(sim.udid, bundleId));\n if (availableWithApp) return availableWithApp;\n\n return firstIOSSimulator();\n}\n\n/**\n * Ensure an iOS simulator is available and booted.\n * If none booted, boots the first available simulator (preferring one with the app installed).\n * Returns the simulator or null if none available.\n */\nexport function ensureIOSSimulator(bundleId?: string): IOSSimulator | null {\n const sim = bundleId ? firstIOSSimulatorWithApp(bundleId) : firstIOSSimulator();\n if (!sim) return null;\n\n if (sim.state !== \"Booted\") {\n console.log(`Booting iOS simulator \"${sim.name}\"...`);\n bootSimulator(sim.udid);\n }\n\n return sim;\n}\n\n/** Boot a simulator by UDID */\nexport function bootSimulator(udid: string): void {\n try {\n execFileSync(\"xcrun\", [\"simctl\", \"boot\", udid], { stdio: \"ignore\" });\n } catch {\n // May already be booted — ignore\n }\n}\n\n/** Install app on simulator */\nexport function installOnSimulator(udid: string, appPath: string): void {\n execFileSync(\"xcrun\", [\"simctl\", \"install\", udid, appPath]);\n}\n\n/** Launch app on simulator */\nexport function launchOnSimulator(udid: string, bundleId: string): void {\n execFileSync(\"xcrun\", [\"simctl\", \"launch\", udid, bundleId]);\n}\n\n/** Launch app on simulator with a deep link URL (bypasses system confirmation dialog) */\nexport function launchWithUrlOnSimulator(udid: string, bundleId: string, url: string): void {\n execFileSync(\"xcrun\", [\"simctl\", \"launch\", udid, bundleId, \"--open-url\", url]);\n}\n\n/** List URL schemes registered by the installed app on simulator */\nexport function installedUrlSchemesOnSimulator(udid: string, bundleId: string): string[] {\n if (!bundleId) return [];\n\n try {\n const appPath = execFileSync(\"xcrun\", [\"simctl\", \"get_app_container\", udid, bundleId, \"app\"], {\n encoding: \"utf-8\",\n }).trim();\n\n const raw = execFileSync(\n \"plutil\",\n [\"-extract\", \"CFBundleURLTypes\", \"json\", \"-o\", \"-\", `${appPath}/Info.plist`],\n {\n encoding: \"utf-8\",\n },\n );\n\n const urlTypes = JSON.parse(raw) as Array<{\n CFBundleURLSchemes?: string[];\n }>;\n\n return urlTypes.flatMap((entry) => entry.CFBundleURLSchemes ?? []);\n } catch {\n return [];\n }\n}\n\n/** Open a URL or deep link on simulator */\nexport function openUrlOnSimulator(udid: string, url: string): void {\n execFileSync(\"xcrun\", [\"simctl\", \"openurl\", udid, url], { stdio: \"ignore\" });\n}\n\n/** Terminate app on simulator */\nexport function terminateOnSimulator(udid: string, bundleId: string): void {\n try {\n execFileSync(\"xcrun\", [\"simctl\", \"terminate\", udid, bundleId], { stdio: \"ignore\" });\n } catch {\n // May not be running\n }\n}\n\n/**\n * Clone an existing iOS Simulator for parallel multi-worker CI execution (`xcrun simctl clone`).\n * Returns the newly created simulator UDID.\n */\nexport function cloneIOSSimulator(sourceUdid: string, cloneName: string): string {\n const out = execFileSync(\"xcrun\", [\"simctl\", \"clone\", sourceUdid, cloneName], {\n encoding: \"utf-8\",\n });\n const udid = out.trim();\n if (!udid) {\n throw new Error(`xcrun simctl clone returned empty UDID for ${sourceUdid}`);\n }\n return udid;\n}\n\n/** Shut down and delete a temporary cloned iOS Simulator (`xcrun simctl delete`). */\nexport function deleteIOSSimulator(udid: string): void {\n try {\n execFileSync(\"xcrun\", [\"simctl\", \"shutdown\", udid], { stdio: \"ignore\" });\n } catch {\n // already shut down\n }\n execFileSync(\"xcrun\", [\"simctl\", \"delete\", udid], { stdio: \"ignore\" });\n}\n\n// ---------------------------------------------------------------------------\n// Physical device support\n// ---------------------------------------------------------------------------\n\nexport interface IOSPhysicalDevice {\n udid: string;\n name: string;\n connectionType: \"USB\" | \"Wi-Fi\" | string;\n}\n\n/**\n * List connected physical iOS devices using xcrun devicectl (Xcode 15+).\n * Falls back to system_profiler if devicectl is unavailable.\n */\nexport function listIOSPhysicalDevices(): IOSPhysicalDevice[] {\n // Try xcrun devicectl first (Xcode 15+)\n try {\n const tmpFile = `/tmp/spana-devicectl-${Date.now()}.json`;\n execFileSync(\"xcrun\", [\"devicectl\", \"list\", \"devices\", \"--json-output\", tmpFile], {\n timeout: 10_000,\n stdio: \"ignore\",\n });\n const output = readFileSync(tmpFile, \"utf-8\");\n try {\n unlinkSync(tmpFile);\n } catch {\n /* cleanup */\n }\n\n const data = JSON.parse(output);\n const devices: IOSPhysicalDevice[] = [];\n\n for (const device of data?.result?.devices ?? []) {\n const deviceType = device.hardwareProperties?.deviceType ?? \"\";\n const transport = device.connectionProperties?.transportType;\n const state = device.connectionProperties?.tunnelState;\n\n // Only treat iPhones/iPads with an active tunnel as available physical\n // devices. devicectl can report remembered Wi-Fi devices with a transport\n // but tunnelState \"disconnected\", which should not trigger a device-first\n // test run attempt.\n if (\n (deviceType === \"iPhone\" || deviceType === \"iPad\") &&\n transport &&\n state === \"connected\"\n ) {\n devices.push({\n udid: device.hardwareProperties?.udid ?? device.identifier,\n name: device.deviceProperties?.name ?? \"Unknown\",\n connectionType: transport === \"wired\" ? \"USB\" : (transport ?? \"unknown\"),\n });\n }\n }\n\n return devices;\n } catch {\n // Fall back to system_profiler for older Xcode\n }\n\n try {\n const output = execFileSync(\"system_profiler\", [\"SPUSBDataType\", \"-json\"], {\n encoding: \"utf-8\",\n timeout: 10_000,\n stdio: [\"ignore\", \"pipe\", \"ignore\"],\n });\n const data = JSON.parse(output);\n const devices: IOSPhysicalDevice[] = [];\n\n function walkUSB(items: any[]): void {\n for (const item of items) {\n // iOS devices have serial_num and contain \"iPhone\" or \"iPad\" in name\n if (item.serial_num && /iPhone|iPad|iPod/i.test(item._name ?? \"\")) {\n devices.push({\n udid: item.serial_num.replaceAll(\"-\", \"\"),\n name: item._name ?? \"iOS Device\",\n connectionType: \"USB\",\n });\n }\n if (item._items) walkUSB(item._items);\n }\n }\n\n walkUSB(data.SPUSBDataType ?? []);\n return devices;\n } catch {\n return [];\n }\n}\n\n/** Get first connected physical iOS device */\nexport function firstIOSPhysicalDevice(): IOSPhysicalDevice | null {\n const devices = listIOSPhysicalDevices();\n return devices[0] ?? null;\n}\n\n/**\n * Start iproxy to tunnel a port from localhost to a physical device via USB.\n * Requires libimobiledevice (`brew install libimobiledevice`).\n *\n * @returns A cleanup function to kill the iproxy process.\n */\nexport function startIproxy(\n udid: string,\n localPort: number,\n devicePort: number,\n): { host: string; port: number; cleanup: () => void } {\n // Check iproxy is available\n try {\n execFileSync(\"which\", [\"iproxy\"], { stdio: \"ignore\" });\n } catch {\n throw new Error(\"iproxy not found. Install with: brew install libimobiledevice\");\n }\n\n const proc = spawn(\"iproxy\", [`${localPort}:${devicePort}`, \"-u\", udid], {\n stdio: \"ignore\",\n detached: true,\n });\n proc.unref();\n\n // Give iproxy a moment to bind\n const waitUntil = Date.now() + 1500;\n while (Date.now() < waitUntil) {\n /* busy wait */\n }\n\n return {\n host: \"localhost\",\n port: localPort,\n cleanup: () => {\n try {\n proc.kill();\n } catch {\n // already dead\n }\n },\n };\n}\n\n/**\n * Connect to a physical iOS device for testing.\n * Sets up iproxy tunnel and returns connection info for WDA.\n *\n * WDA must be pre-installed and running on the device.\n * Install with: xcodebuild -project WebDriverAgent.xcodeproj -scheme WebDriverAgentRunner\n * -destination \"id=<UDID>\" test\n */\nexport function connectPhysicalDevice(\n udid: string,\n wdaPort = 8100,\n): { host: string; port: number; cleanup: () => void } {\n const localPort = allocatePort(8100);\n\n try {\n const tunnel = startIproxy(udid, localPort, wdaPort);\n return {\n ...tunnel,\n cleanup: () => {\n tunnel.cleanup();\n releasePort(localPort);\n },\n };\n } catch (error) {\n releasePort(localPort);\n throw error;\n }\n}\n\n/**\n * Install an app on a physical iOS device using xcrun devicectl (Xcode 15+).\n * Accepts .app bundles or .ipa files.\n */\nexport function installOnPhysicalDevice(udid: string, appPath: string): void {\n try {\n execFileSync(\"xcrun\", [\"devicectl\", \"device\", \"install\", \"app\", \"--device\", udid, appPath], {\n stdio: \"inherit\",\n timeout: 120_000,\n });\n } catch {\n throw new Error(\n `Failed to install app on device ${udid}. Ensure the app is signed for this device.`,\n );\n }\n}\n\n/**\n * Check if an app is installed on a physical device.\n */\nexport function hasAppOnPhysicalDevice(udid: string, bundleId: string): boolean {\n if (!bundleId) return false;\n try {\n const tmpFile = `/tmp/spana-applist-${Date.now()}.json`;\n execFileSync(\n \"xcrun\",\n [\"devicectl\", \"device\", \"info\", \"apps\", \"--device\", udid, \"--json-output\", tmpFile],\n { timeout: 15_000, stdio: \"ignore\" },\n );\n const output = readFileSync(tmpFile, \"utf-8\");\n try {\n unlinkSync(tmpFile);\n } catch {\n /* cleanup */\n }\n return output.includes(bundleId);\n } catch {\n return false;\n }\n}\n\n// ---------------------------------------------------------------------------\n// Network control helpers (pfctl / dnctl)\n// ---------------------------------------------------------------------------\n// WARNING: These functions affect the entire host Mac's network stack.\n// iOS simulators share the host network — there is no per-simulator isolation.\n// Requires sudo.\n\n/** pfctl anchor name used by spana for network rules */\nexport const SPANA_ANCHOR = \"com.spana.network\";\n\n/**\n * Block or unblock all outbound network traffic using pfctl.\n * When enabled, adds a \"block out all\" rule to the spana anchor.\n * When disabled, flushes all rules from the spana anchor.\n */\nexport function pfctlSetOffline(enable: boolean): void {\n if (enable) {\n execFileSync(\"sudo\", [\"pfctl\", \"-a\", SPANA_ANCHOR, \"-f\", \"-\"], {\n input: \"block out all\\n\",\n stdio: [\"pipe\", \"ignore\", \"ignore\"],\n });\n try {\n execFileSync(\"sudo\", [\"pfctl\", \"-e\"], { stdio: \"ignore\" });\n } catch {\n // May already be enabled\n }\n } else {\n try {\n execFileSync(\"sudo\", [\"pfctl\", \"-a\", SPANA_ANCHOR, \"-F\", \"all\"], { stdio: \"ignore\" });\n } catch {\n // Ignore errors\n }\n }\n}\n\n/**\n * Throttle network using dnctl pipe and pfctl dummynet rules.\n * Configures bandwidth and delay for all outbound traffic.\n */\nexport function pfctlSetThrottle(throughputKbps: number, delayMs: number): void {\n execFileSync(\n \"sudo\",\n [\"dnctl\", \"pipe\", \"1\", \"config\", \"bw\", `${throughputKbps}Kbit/s`, \"delay\", `${delayMs}ms`],\n {\n stdio: \"ignore\",\n },\n );\n execFileSync(\"sudo\", [\"pfctl\", \"-a\", SPANA_ANCHOR, \"-f\", \"-\"], {\n input: \"dummynet out all pipe 1\\n\",\n stdio: [\"pipe\", \"ignore\", \"ignore\"],\n });\n try {\n execFileSync(\"sudo\", [\"pfctl\", \"-e\"], { stdio: \"ignore\" });\n } catch {\n // May already be enabled\n }\n}\n\n/**\n * Reset all network modifications — flush pfctl anchor rules and dnctl pipes.\n */\nexport function pfctlResetNetwork(): void {\n try {\n execFileSync(\"sudo\", [\"pfctl\", \"-a\", SPANA_ANCHOR, \"-F\", \"all\"], { stdio: \"ignore\" });\n } catch {\n // Ignore errors\n }\n try {\n execFileSync(\"sudo\", [\"dnctl\", \"-q\", \"flush\"], { stdio: \"ignore\" });\n } catch {\n // Ignore errors\n }\n}\n\n/** Reset simulator keychain (removes all stored passwords and certificates) */\nexport function resetSimulatorKeychain(udid: string): void {\n execFileSync(\"xcrun\", [\"simctl\", \"keychain\", udid, \"reset\"], { stdio: \"ignore\" });\n}\n\n/**\n * Ensure an app is installed on the target device (simulator or physical).\n * Installs from appPath if not already present.\n */\nexport function ensureAppInstalled(opts: {\n udid: string;\n bundleId: string;\n appPath: string;\n isPhysicalDevice: boolean;\n}): void {\n const { udid, bundleId, appPath, isPhysicalDevice } = opts;\n\n if (isPhysicalDevice) {\n if (!hasAppOnPhysicalDevice(udid, bundleId)) {\n console.log(`Installing ${bundleId} on physical device...`);\n installOnPhysicalDevice(udid, appPath);\n }\n } else {\n if (!hasAppInstalledOnSimulator(udid, bundleId)) {\n console.log(`Installing ${bundleId} on simulator...`);\n installOnSimulator(udid, appPath);\n }\n }\n}\n"],"mappings":";;;;;;AAAA,SAAS,cAAc,aAAa;AACpC,SAAS,cAAc,kBAAkB;AAoBlC,SAAS,oBAAoC;AAClD,MAAI;AACF,UAAM,SAAS,aAAa,SAAS,CAAC,UAAU,QAAQ,WAAW,IAAI,GAAG;AAAA,MACxE,UAAU;AAAA,IACZ,CAAC;AACD,UAAM,OAAO,KAAK,MAAM,MAAM;AAC9B,UAAM,aAA6B,CAAC;AAEpC,eAAW,CAAC,SAAS,OAAO,KAAK,OAAO,QAAQ,KAAK,WAAW,CAAC,CAAC,GAAG;AAEnE,YAAM,cAAc,QACjB,QAAQ,uCAAuC,EAAE,EACjD,WAAW,KAAK,GAAG;AAEtB,iBAAW,U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;AACF;AAGO,SAAS,uBAAuB,MAAoB;AACzD,eAAa,SAAS,CAAC,UAAU,YAAY,MAAM,OAAO,GAAG,EAAE,OAAO,SAAS,CAAC;AAClF;AAMO,SAAS,mBAAmB,MAK1B;AACP,QAAM,EAAE,MAAM,UAAU,SAAS,iBAAiB,IAAI;AAEtD,MAAI,kBAAkB;AACpB,QAAI,CAAC,uBAAuB,MAAM,QAAQ,GAAG;AAC3C,cAAQ,IAAI,cAAc,QAAQ,wBAAwB;AAC1D,8BAAwB,MAAM,OAAO;AAAA,IACvC;AAAA,EACF,OAAO;AACL,QAAI,CAAC,2BAA2B,MAAM,QAAQ,GAAG;AAC/C,cAAQ,IAAI,cAAc,QAAQ,kBAAkB;AACpD,yBAAmB,MAAM,OAAO;AAAA,IAClC;AAAA,EACF;AACF;","names":["walkUSB"]}
@@ -0,0 +1,358 @@
1
+ // src/runtime/daemon-manager.ts
2
+ import { execFileSync } from "child_process";
3
+ import { createHash } from "crypto";
4
+ import {
5
+ existsSync,
6
+ mkdirSync,
7
+ readdirSync,
8
+ readFileSync,
9
+ renameSync,
10
+ rmSync,
11
+ unlinkSync,
12
+ writeFileSync
13
+ } from "fs";
14
+ import { tmpdir } from "os";
15
+ import { dirname, join } from "path";
16
+ var DEFAULT_WARM_DAEMON_IDLE_TTL_MS = 30 * 60 * 1e3;
17
+ function defaultDaemonStatePath() {
18
+ return join(tmpdir(), "spana-warm-daemons.json");
19
+ }
20
+ function defaultDaemonStateDir() {
21
+ return join(tmpdir(), "spana-daemons");
22
+ }
23
+ function daemonKey(kind, deviceId) {
24
+ return `${kind}:${deviceId}`;
25
+ }
26
+ function scopeRecordPath(kind, deviceId) {
27
+ const safe = `${kind}-${deviceId}`.replaceAll(/[^a-zA-Z0-9._-]/g, "_").slice(0, 64);
28
+ const hash = createHash("sha256").update(daemonKey(kind, deviceId)).digest("hex").slice(0, 10);
29
+ return join(defaultDaemonStateDir(), `${safe}-${hash}.json`);
30
+ }
31
+ function isUsingDefaultStateFile(stateFile) {
32
+ return !stateFile || stateFile === defaultDaemonStatePath();
33
+ }
34
+ function atomicWriteJson(filePath, data) {
35
+ mkdirSync(dirname(filePath), { recursive: true });
36
+ const tmpPath = `${filePath}.${process.pid}.${Math.random().toString(36).slice(2, 8)}.tmp`;
37
+ writeFileSync(tmpPath, JSON.stringify(data, null, 2), "utf-8");
38
+ renameSync(tmpPath, filePath);
39
+ }
40
+ function loadScopeRecords() {
41
+ const dir = defaultDaemonStateDir();
42
+ const out = {};
43
+ if (!existsSync(dir)) return out;
44
+ try {
45
+ for (const file of readdirSync(dir)) {
46
+ if (!file.endsWith(".json")) continue;
47
+ try {
48
+ const parsed = JSON.parse(readFileSync(join(dir, file), "utf-8"));
49
+ if (parsed && typeof parsed.kind === "string" && typeof parsed.deviceId === "string") {
50
+ out[daemonKey(parsed.kind, parsed.deviceId)] = parsed;
51
+ }
52
+ } catch {
53
+ }
54
+ }
55
+ } catch {
56
+ }
57
+ return out;
58
+ }
59
+ function readScopeRecord(kind, deviceId) {
60
+ const filePath = scopeRecordPath(kind, deviceId);
61
+ if (!existsSync(filePath)) return void 0;
62
+ try {
63
+ return JSON.parse(readFileSync(filePath, "utf-8"));
64
+ } catch {
65
+ return void 0;
66
+ }
67
+ }
68
+ function deleteScopeRecord(kind, deviceId) {
69
+ const filePath = scopeRecordPath(kind, deviceId);
70
+ try {
71
+ if (existsSync(filePath)) unlinkSync(filePath);
72
+ } catch {
73
+ }
74
+ }
75
+ function killPidTree(pid) {
76
+ if (!pid || pid <= 0 || pid === process.pid) return;
77
+ const targets = process.platform !== "win32" ? [-pid, pid] : [pid];
78
+ for (const target of targets) {
79
+ try {
80
+ process.kill(target, "SIGTERM");
81
+ } catch {
82
+ }
83
+ }
84
+ if (isPidAlive(pid)) {
85
+ for (const target of targets) {
86
+ try {
87
+ process.kill(target, "SIGKILL");
88
+ } catch {
89
+ }
90
+ }
91
+ }
92
+ }
93
+ function loadDaemonRegistry(stateFile = defaultDaemonStatePath()) {
94
+ const merged = {};
95
+ if (existsSync(stateFile)) {
96
+ try {
97
+ const raw = readFileSync(stateFile, "utf-8");
98
+ const parsed = JSON.parse(raw);
99
+ if (parsed && parsed.version === 1 && typeof parsed.daemons === "object") {
100
+ Object.assign(merged, parsed.daemons);
101
+ }
102
+ } catch {
103
+ }
104
+ }
105
+ if (isUsingDefaultStateFile(stateFile)) {
106
+ Object.assign(merged, loadScopeRecords());
107
+ }
108
+ return { version: 1, daemons: merged };
109
+ }
110
+ function saveDaemonRegistry(registry, stateFile = defaultDaemonStatePath()) {
111
+ atomicWriteJson(stateFile, registry);
112
+ }
113
+ function resolveIdleTtlMs(explicit) {
114
+ if (explicit !== void 0) return explicit;
115
+ const envRaw = process.env["SPANA_DAEMON_IDLE_TTL_MS"];
116
+ if (envRaw !== void 0) {
117
+ const parsed = Number(envRaw);
118
+ if (Number.isFinite(parsed) && parsed >= 0) return parsed;
119
+ }
120
+ return DEFAULT_WARM_DAEMON_IDLE_TTL_MS;
121
+ }
122
+ function registerWarmDaemon(record, stateFile = defaultDaemonStatePath()) {
123
+ const key = daemonKey(record.kind, record.deviceId);
124
+ const existing = loadDaemonRegistry(stateFile);
125
+ for (const [otherKey, other] of Object.entries(existing.daemons)) {
126
+ if (otherKey !== key && other.host === record.host && other.port === record.port && isPidAlive(other.pid)) {
127
+ throw new Error(
128
+ `Warm daemon port clash on ${record.host}:${record.port}: scope "${otherKey}" (pid ${other.pid}) already owns this port.`
129
+ );
130
+ }
131
+ }
132
+ const prev = existing.daemons[key];
133
+ if (prev) {
134
+ if (prev.pid && prev.pid !== record.pid && isPidAlive(prev.pid)) {
135
+ killPidTree(prev.pid);
136
+ }
137
+ if (prev.tunnelPid && prev.tunnelPid !== record.tunnelPid && isPidAlive(prev.tunnelPid)) {
138
+ killPidTree(prev.tunnelPid);
139
+ }
140
+ if (prev.userDataDir && prev.userDataDir !== record.userDataDir) {
141
+ try {
142
+ rmSync(prev.userDataDir, { recursive: true, force: true });
143
+ } catch {
144
+ }
145
+ }
146
+ }
147
+ const stamped = {
148
+ ...record,
149
+ lastUsedAt: record.lastUsedAt ?? record.startedAt ?? (/* @__PURE__ */ new Date()).toISOString()
150
+ };
151
+ if (isUsingDefaultStateFile(stateFile)) {
152
+ atomicWriteJson(scopeRecordPath(record.kind, record.deviceId), stamped);
153
+ return;
154
+ }
155
+ existing.daemons[key] = stamped;
156
+ saveDaemonRegistry(existing, stateFile);
157
+ }
158
+ function updateWarmDaemonSession(kind, deviceId, sessionId, bundleId, stateFile = defaultDaemonStatePath()) {
159
+ if (isUsingDefaultStateFile(stateFile)) {
160
+ const scopeRec = readScopeRecord(kind, deviceId);
161
+ if (scopeRec) {
162
+ atomicWriteJson(scopeRecordPath(kind, deviceId), {
163
+ ...scopeRec,
164
+ sessionId,
165
+ ...bundleId ? { bundleId } : {}
166
+ });
167
+ return;
168
+ }
169
+ }
170
+ const registry = loadDaemonRegistry(stateFile);
171
+ const key = daemonKey(kind, deviceId);
172
+ const existing = registry.daemons[key];
173
+ if (!existing) return;
174
+ registry.daemons[key] = { ...existing, sessionId, ...bundleId ? { bundleId } : {} };
175
+ saveDaemonRegistry(registry, stateFile);
176
+ }
177
+ function unregisterWarmDaemon(kind, deviceId, stateFile = defaultDaemonStatePath()) {
178
+ if (isUsingDefaultStateFile(stateFile)) {
179
+ deleteScopeRecord(kind, deviceId);
180
+ }
181
+ if (existsSync(stateFile)) {
182
+ const raw = loadDaemonRegistry(stateFile);
183
+ if (daemonKey(kind, deviceId) in raw.daemons) {
184
+ delete raw.daemons[daemonKey(kind, deviceId)];
185
+ saveDaemonRegistry(raw, stateFile);
186
+ }
187
+ }
188
+ }
189
+ function listWarmDaemons(stateFile = defaultDaemonStatePath()) {
190
+ return Object.values(loadDaemonRegistry(stateFile).daemons);
191
+ }
192
+ function isPidAlive(pid) {
193
+ if (!pid || pid <= 0) return false;
194
+ try {
195
+ process.kill(pid, 0);
196
+ return true;
197
+ } catch {
198
+ return false;
199
+ }
200
+ }
201
+ async function getHealthyWarmDaemon(kind, deviceId, options = {}) {
202
+ const stateFile = options.stateFile ?? defaultDaemonStatePath();
203
+ const fetchFn = options.fetchFn ?? fetch;
204
+ const timeoutMs = options.timeoutMs ?? 1500;
205
+ const statusPath = options.statusPath ?? (kind === "chromium" ? "/json/version" : "/status");
206
+ const idleTtlMs = resolveIdleTtlMs(options.idleTtlMs);
207
+ const nowMs = options.nowMs ?? Date.now();
208
+ const record = isUsingDefaultStateFile(stateFile) ? readScopeRecord(kind, deviceId) ?? loadDaemonRegistry(stateFile).daemons[daemonKey(kind, deviceId)] : loadDaemonRegistry(stateFile).daemons[daemonKey(kind, deviceId)];
209
+ if (!record) return null;
210
+ if (idleTtlMs > 0) {
211
+ const lastTs = Date.parse(record.lastUsedAt ?? record.startedAt);
212
+ if (Number.isFinite(lastTs) && nowMs - lastTs > idleTtlMs) {
213
+ stopWarmDaemon(kind, deviceId, stateFile);
214
+ return null;
215
+ }
216
+ }
217
+ try {
218
+ const controller = new AbortController();
219
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
220
+ try {
221
+ const res = await fetchFn(`http://${record.host}:${record.port}${statusPath}`, {
222
+ signal: controller.signal
223
+ });
224
+ if (res.ok) {
225
+ const touched = {
226
+ ...record,
227
+ lastUsedAt: new Date(nowMs).toISOString()
228
+ };
229
+ if (isUsingDefaultStateFile(stateFile)) {
230
+ try {
231
+ atomicWriteJson(scopeRecordPath(kind, deviceId), touched);
232
+ } catch {
233
+ }
234
+ } else {
235
+ try {
236
+ const registry = loadDaemonRegistry(stateFile);
237
+ registry.daemons[daemonKey(kind, deviceId)] = touched;
238
+ saveDaemonRegistry(registry, stateFile);
239
+ } catch {
240
+ }
241
+ }
242
+ return touched;
243
+ }
244
+ } finally {
245
+ clearTimeout(timer);
246
+ }
247
+ } catch {
248
+ }
249
+ stopWarmDaemon(kind, deviceId, stateFile);
250
+ return null;
251
+ }
252
+ function reapIdleWarmDaemons(options = {}) {
253
+ const stateFile = options.stateFile ?? defaultDaemonStatePath();
254
+ const idleTtlMs = resolveIdleTtlMs(options.idleTtlMs);
255
+ if (idleTtlMs <= 0) return 0;
256
+ const nowMs = options.nowMs ?? Date.now();
257
+ const records = listWarmDaemons(stateFile);
258
+ let reaped = 0;
259
+ for (const record of records) {
260
+ const lastTs = Date.parse(record.lastUsedAt ?? record.startedAt);
261
+ if (Number.isFinite(lastTs) && nowMs - lastTs > idleTtlMs) {
262
+ if (stopWarmDaemon(record.kind, record.deviceId, stateFile)) {
263
+ reaped++;
264
+ }
265
+ }
266
+ }
267
+ return reaped;
268
+ }
269
+ var SPANA_BROWSER_PROFILE_MARKERS = [
270
+ "spana-cdp-profile-",
271
+ "spana-pw-profile-",
272
+ "spana-browser-profile-"
273
+ ];
274
+ function sweepOrphanedSpanaBrowsers(options = {}) {
275
+ if (process.platform === "win32") return 0;
276
+ let psOut = "";
277
+ try {
278
+ psOut = execFileSync("ps", ["-ax", "-o", "pid=,command="], {
279
+ encoding: "utf8",
280
+ stdio: ["ignore", "pipe", "ignore"]
281
+ });
282
+ } catch {
283
+ return 0;
284
+ }
285
+ const exclude = options.excludePids ?? /* @__PURE__ */ new Set();
286
+ let killed = 0;
287
+ const profileDirsToClean = /* @__PURE__ */ new Set();
288
+ for (const rawLine of psOut.split("\n")) {
289
+ const line = rawLine.trim();
290
+ if (!line) continue;
291
+ const match = /^(\d+)\s+(.*)$/.exec(line);
292
+ if (!match) continue;
293
+ const pid = Number.parseInt(match[1], 10);
294
+ const cmd = match[2] ?? "";
295
+ if (!Number.isFinite(pid) || pid <= 0 || pid === process.pid || exclude.has(pid)) continue;
296
+ if (!SPANA_BROWSER_PROFILE_MARKERS.some((marker) => cmd.includes(marker))) continue;
297
+ const dirMatch = /--user-data-dir=([^\s]+)/.exec(cmd);
298
+ if (dirMatch?.[1] && SPANA_BROWSER_PROFILE_MARKERS.some((m) => dirMatch[1].includes(m))) {
299
+ profileDirsToClean.add(dirMatch[1]);
300
+ }
301
+ killPidTree(pid);
302
+ killed++;
303
+ }
304
+ for (const dir of profileDirsToClean) {
305
+ try {
306
+ rmSync(dir, { recursive: true, force: true });
307
+ } catch {
308
+ }
309
+ }
310
+ return killed;
311
+ }
312
+ function stopWarmDaemon(kind, deviceId, stateFile = defaultDaemonStatePath()) {
313
+ const key = daemonKey(kind, deviceId);
314
+ const record = isUsingDefaultStateFile(stateFile) ? readScopeRecord(kind, deviceId) ?? loadDaemonRegistry(stateFile).daemons[key] : loadDaemonRegistry(stateFile).daemons[key];
315
+ if (!record) return false;
316
+ killPidTree(record.pid);
317
+ killPidTree(record.tunnelPid);
318
+ if (record.userDataDir) {
319
+ try {
320
+ rmSync(record.userDataDir, { recursive: true, force: true });
321
+ } catch {
322
+ }
323
+ }
324
+ unregisterWarmDaemon(kind, deviceId, stateFile);
325
+ return true;
326
+ }
327
+ function stopAllWarmDaemons(stateFile = defaultDaemonStatePath()) {
328
+ const records = listWarmDaemons(stateFile);
329
+ let stopped = 0;
330
+ for (const record of records) {
331
+ if (stopWarmDaemon(record.kind, record.deviceId, stateFile)) {
332
+ stopped++;
333
+ }
334
+ }
335
+ if (isUsingDefaultStateFile(stateFile)) {
336
+ stopped += sweepOrphanedSpanaBrowsers();
337
+ }
338
+ return stopped;
339
+ }
340
+
341
+ export {
342
+ DEFAULT_WARM_DAEMON_IDLE_TTL_MS,
343
+ defaultDaemonStatePath,
344
+ defaultDaemonStateDir,
345
+ loadDaemonRegistry,
346
+ saveDaemonRegistry,
347
+ registerWarmDaemon,
348
+ updateWarmDaemonSession,
349
+ unregisterWarmDaemon,
350
+ listWarmDaemons,
351
+ isPidAlive,
352
+ getHealthyWarmDaemon,
353
+ reapIdleWarmDaemons,
354
+ sweepOrphanedSpanaBrowsers,
355
+ stopWarmDaemon,
356
+ stopAllWarmDaemons
357
+ };
358
+ //# sourceMappingURL=chunk-Z6K4QQAR.js.map