@wdio/native-core 1.0.0 → 1.2.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.
@@ -0,0 +1,60 @@
1
+ import type { DevServer } from '@wdio/native-types';
2
+ import { type Result } from '@wdio/native-utils';
3
+ import { type DevServerReadyProbe } from './devServerProcess.js';
4
+ export declare const BROWSER_MODE_SUPPORTED_BROWSER = "chrome";
5
+ /**
6
+ * Validate a user-supplied `browserName` for browser mode.
7
+ *
8
+ * Returns an actionable error message when `browserName` is set to a value the
9
+ * service can't drive in browser mode; returns `undefined` when the value is
10
+ * acceptable (unset, or one of `allowed`). Each launcher throws its own
11
+ * `SevereServiceError` with this message so the runner stops with a clear
12
+ * explanation instead of silently rewriting the capability.
13
+ *
14
+ * `allowed` defaults to `['chrome']`. Electron passes its native detection
15
+ * value too (`['chrome', 'electron']`), since the launcher rewrites a
16
+ * legitimate `browserName: 'electron'` to chrome for the browser-mode session.
17
+ */
18
+ export declare function nonChromeBrowserNameError(browserName: unknown, allowed?: readonly string[]): string | undefined;
19
+ /**
20
+ * Preflight the dev server before the worker navigates to it.
21
+ *
22
+ * A HEAD request with a short timeout. Any non-network response (even 404/405)
23
+ * proves the server is listening, so only a thrown fetch error (connection
24
+ * refused, DNS failure, timeout) counts as unreachable. Runs in the launcher's
25
+ * main process where outbound network is available.
26
+ */
27
+ export declare function probeDevServerReachable(url: string, timeoutMs?: number): Promise<Result<void, Error>>;
28
+ /**
29
+ * Poll {@link probeDevServerReachable} until the server answers or the budget elapses.
30
+ *
31
+ * The single-shot `probeDevServerReachable` is a preflight for a server the user already started;
32
+ * this is the "wait for a server we (or the user's function) just started to come up" variant.
33
+ */
34
+ export declare function waitForDevServerReachable(url: string, { timeoutMs, pollMs, }?: {
35
+ timeoutMs?: number;
36
+ pollMs?: number;
37
+ }): Promise<Result<void, Error>>;
38
+ /**
39
+ * Start (or reuse) a dev server for browser mode and return a handle to tear it down.
40
+ *
41
+ * Handles all three {@link DevServer} forms so each launcher stays a few lines:
42
+ * - **function** — call it, poll its returned `url` for readiness, and teardown is its `close()`
43
+ * (no subprocess spawn/kill involved). The returned `url` supplies/overrides `devServerUrl`.
44
+ * - **string / object** — if `reuseExistingServer` (default `!CI`) and `devServerUrl` is already
45
+ * reachable, skip the spawn; otherwise spawn a {@link DevServerProcess} and poll `devServerUrl`.
46
+ *
47
+ * The caller stores the returned `stop` and must call it in `onComplete` *and* on an `onPrepare`
48
+ * failure (WDIO does not call `onComplete` after `onPrepare` throws). `stop` is idempotent.
49
+ */
50
+ export declare function startManagedDevServer(devServer: DevServer, devServerUrl: string, deps?: {
51
+ spawn?: typeof import('node:child_process').spawn;
52
+ probe?: DevServerReadyProbe;
53
+ isCI?: boolean;
54
+ readinessTimeoutMs?: number;
55
+ readinessPollMs?: number;
56
+ }): Promise<{
57
+ url: string;
58
+ stop: () => Promise<void>;
59
+ }>;
60
+ //# sourceMappingURL=browserMode.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"browserMode.d.ts","sourceRoot":"","sources":["../../src/browserMode.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,oBAAoB,CAAC;AACpD,OAAO,EAAsC,KAAK,MAAM,EAAE,MAAM,oBAAoB,CAAC;AACrF,OAAO,EAAoB,KAAK,mBAAmB,EAAE,MAAM,uBAAuB,CAAC;AAOnF,eAAO,MAAM,8BAA8B,WAAW,CAAC;AAIvD;;;;;;;;;;;;GAYG;AACH,wBAAgB,yBAAyB,CACvC,WAAW,EAAE,OAAO,EACpB,OAAO,GAAE,SAAS,MAAM,EAAqC,GAC5D,MAAM,GAAG,SAAS,CAWpB;AAED;;;;;;;GAOG;AACH,wBAAsB,uBAAuB,CAC3C,GAAG,EAAE,MAAM,EACX,SAAS,GAAE,MAAoC,GAC9C,OAAO,CAAC,MAAM,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC,CAQ9B;AAOD;;;;;GAKG;AACH,wBAAsB,yBAAyB,CAC7C,GAAG,EAAE,MAAM,EACX,EACE,SAAuC,EACvC,MAAiC,GAClC,GAAE;IAAE,SAAS,CAAC,EAAE,MAAM,CAAC;IAAC,MAAM,CAAC,EAAE,MAAM,CAAA;CAAO,GAC9C,OAAO,CAAC,MAAM,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC,CAQ9B;AAED;;;;;;;;;;;GAWG;AACH,wBAAsB,qBAAqB,CACzC,SAAS,EAAE,SAAS,EACpB,YAAY,EAAE,MAAM,EACpB,IAAI,GAAE;IACJ,KAAK,CAAC,EAAE,cAAc,oBAAoB,EAAE,KAAK,CAAC;IAClD,KAAK,CAAC,EAAE,mBAAmB,CAAC;IAC5B,IAAI,CAAC,EAAE,OAAO,CAAC;IACf,kBAAkB,CAAC,EAAE,MAAM,CAAC;IAC5B,eAAe,CAAC,EAAE,MAAM,CAAC;CACrB,GACL,OAAO,CAAC;IAAE,GAAG,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,CAAA;CAAE,CAAC,CAsCrD"}
@@ -0,0 +1,31 @@
1
+ import { type ChildProcess, spawn as nodeSpawn } from 'node:child_process';
2
+ /** A reachability probe — resolves `true` once the dev server answers at `url`. */
3
+ export type DevServerReadyProbe = (url: string) => Promise<boolean>;
4
+ /** Kill a spawned child (and, where possible, its process group) with `signal`. */
5
+ export type DevServerKill = (proc: ChildProcess, signal: NodeJS.Signals) => void;
6
+ export interface DevServerStartOptions {
7
+ /** Command run in a shell to start the dev server, e.g. `'pnpm dev'`. */
8
+ command: string;
9
+ /** Working directory. Default `process.cwd()`. */
10
+ cwd?: string;
11
+ /** Extra environment variables, merged over `process.env`. */
12
+ env?: Record<string, string>;
13
+ /** Readiness target — the URL polled until reachable (i.e. `devServerUrl`). */
14
+ url: string;
15
+ /** Readiness budget (ms). Default 60s locally, 120s in CI. */
16
+ timeoutMs?: number;
17
+ /** Readiness poll interval (ms). Default 500. */
18
+ pollMs?: number;
19
+ }
20
+ export declare class DevServerProcess {
21
+ #private;
22
+ constructor(deps?: {
23
+ spawn?: typeof nodeSpawn;
24
+ probe?: DevServerReadyProbe;
25
+ kill?: DevServerKill;
26
+ });
27
+ isRunning(): boolean;
28
+ start(options: DevServerStartOptions): Promise<void>;
29
+ stop(): Promise<void>;
30
+ }
31
+ //# sourceMappingURL=devServerProcess.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"devServerProcess.d.ts","sourceRoot":"","sources":["../../src/devServerProcess.ts"],"names":[],"mappings":"AAOA,OAAO,EAAE,KAAK,YAAY,EAAE,KAAK,IAAI,SAAS,EAAE,MAAM,oBAAoB,CAAC;AAa3E,mFAAmF;AACnF,MAAM,MAAM,mBAAmB,GAAG,CAAC,GAAG,EAAE,MAAM,KAAK,OAAO,CAAC,OAAO,CAAC,CAAC;AAEpE,mFAAmF;AACnF,MAAM,MAAM,aAAa,GAAG,CAAC,IAAI,EAAE,YAAY,EAAE,MAAM,EAAE,MAAM,CAAC,OAAO,KAAK,IAAI,CAAC;AAEjF,MAAM,WAAW,qBAAqB;IACpC,yEAAyE;IACzE,OAAO,EAAE,MAAM,CAAC;IAChB,kDAAkD;IAClD,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,8DAA8D;IAC9D,GAAG,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAC7B,+EAA+E;IAC/E,GAAG,EAAE,MAAM,CAAC;IACZ,8DAA8D;IAC9D,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,iDAAiD;IACjD,MAAM,CAAC,EAAE,MAAM,CAAC;CACjB;AAmCD,qBAAa,gBAAgB;;gBAYf,IAAI,GAAE;QAAE,KAAK,CAAC,EAAE,OAAO,SAAS,CAAC;QAAC,KAAK,CAAC,EAAE,mBAAmB,CAAC;QAAC,IAAI,CAAC,EAAE,aAAa,CAAA;KAAO;IAMtG,SAAS,IAAI,OAAO;IAgBd,KAAK,CAAC,OAAO,EAAE,qBAAqB,GAAG,OAAO,CAAC,IAAI,CAAC;IAwEpD,IAAI,IAAI,OAAO,CAAC,IAAI,CAAC;CAsC5B"}
@@ -1,5 +1,7 @@
1
1
  export * from './baseLauncher.js';
2
+ export * from './browserMode.js';
2
3
  export * from './deeplink.js';
4
+ export * from './devServerProcess.js';
3
5
  export * from './driverPool.js';
4
6
  export * from './driverProcess.js';
5
7
  export * from './logCapture.js';
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAOA,cAAc,mBAAmB,CAAC;AAClC,cAAc,eAAe,CAAC;AAC9B,cAAc,iBAAiB,CAAC;AAChC,cAAc,oBAAoB,CAAC;AACnC,cAAc,iBAAiB,CAAC;AAChC,cAAc,eAAe,CAAC;AAC9B,cAAc,gBAAgB,CAAC;AAC/B,cAAc,kBAAkB,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAOA,cAAc,mBAAmB,CAAC;AAClC,cAAc,kBAAkB,CAAC;AACjC,cAAc,eAAe,CAAC;AAC9B,cAAc,uBAAuB,CAAC;AACtC,cAAc,iBAAiB,CAAC;AAChC,cAAc,oBAAoB,CAAC;AACnC,cAAc,iBAAiB,CAAC;AAChC,cAAc,eAAe,CAAC;AAC9B,cAAc,gBAAgB,CAAC;AAC/B,cAAc,kBAAkB,CAAC"}
package/dist/cjs/index.js CHANGED
@@ -25,7 +25,7 @@ var node_path = require('node:path');
25
25
  // Electron's `LogCaptureManager` (packages/electron-service/src/logCapture.ts)
26
26
  // is intentionally NOT migrated here — it consumes CDP `Runtime.consoleAPICalled`
27
27
  // events on a running Electron app, a fundamentally different domain.
28
- const log$5 = nativeUtils.createLogger('native-core', 'launcher');
28
+ const log$7 = nativeUtils.createLogger('native-core', 'launcher');
29
29
  /**
30
30
  * Create a log capture handler for a child-process stream (stdout/stderr).
31
31
  *
@@ -54,7 +54,7 @@ function createLogCapture(opts) {
54
54
  onLine(line, instanceId);
55
55
  });
56
56
  rl.on('error', (err) => {
57
- log$5.warn(`[${identifier}] Stream error: ${err.message}`);
57
+ log$7.warn(`[${identifier}] Stream error: ${err.message}`);
58
58
  });
59
59
  return rl;
60
60
  }
@@ -79,7 +79,7 @@ function createLogCapture(opts) {
79
79
  // The poll-for-readiness behaviour (TCP open + HTTP /status reachable),
80
80
  // SIGTERM-then-SIGKILL shutdown sequence, and CI-aware timeouts all
81
81
  // transfer unchanged — they're generic.
82
- const log$4 = nativeUtils.createLogger('native-core', 'launcher');
82
+ const log$6 = nativeUtils.createLogger('native-core', 'launcher');
83
83
  /**
84
84
  * Manages a single driver subprocess lifecycle (Tauri's tauri-driver,
85
85
  * Dioxus's wdio-dioxus-driver, or any other WebDriver proxy).
@@ -111,11 +111,11 @@ class DriverProcess {
111
111
  this._port = port;
112
112
  this._nativePort = nativePort;
113
113
  this._dataDir = options.dataDir;
114
- log$4.info(`Starting ${driverName} [${identifier}] on port ${port} (native port: ${nativePort})`);
114
+ log$6.info(`Starting ${driverName} [${identifier}] on port ${port} (native port: ${nativePort})`);
115
115
  const args = ['--port', port.toString(), '--native-port', nativePort.toString()];
116
116
  if (nativeDriverPath) {
117
117
  args.push('--native-driver', nativeDriverPath);
118
- log$4.debug(`[${identifier}] Using native driver: ${nativeDriverPath}`);
118
+ log$6.debug(`[${identifier}] Using native driver: ${nativeDriverPath}`);
119
119
  }
120
120
  return new Promise((resolve, reject) => {
121
121
  let settled = false;
@@ -142,7 +142,7 @@ class DriverProcess {
142
142
  env: spawnEnv,
143
143
  shell: process.platform === 'win32',
144
144
  });
145
- log$4.info(`[${identifier}] Spawned process with PID: ${this._proc.pid ?? 'unknown'}`);
145
+ log$6.info(`[${identifier}] Spawned process with PID: ${this._proc.pid ?? 'unknown'}`);
146
146
  this.startupTimeout = setTimeout(() => {
147
147
  if (!settled) {
148
148
  safeReject(new Error(`${driverName} [${identifier}] failed to start within ${this.startTimeout}ms`));
@@ -156,7 +156,7 @@ class DriverProcess {
156
156
  // through the TCP/HTTP poll loop. safeResolve is idempotent, so the poll
157
157
  // path remains a safety net if no marker is seen.
158
158
  const onStartupDetected = () => {
159
- log$4.info(`✅ ${driverName} [${identifier}] startup marker detected`);
159
+ log$6.info(`✅ ${driverName} [${identifier}] startup marker detected`);
160
160
  // this._proc is non-null here (we just spawned it above), but the
161
161
  // signature widens with cleanup() — assert via the original ref.
162
162
  if (this._proc) {
@@ -232,7 +232,7 @@ class DriverProcess {
232
232
  if (isPortOpen) {
233
233
  try {
234
234
  await this.waitForHttpReady(port, 1000);
235
- log$4.info(`✅ ${driverName} [${identifier}] is ready on port ${port}`);
235
+ log$6.info(`✅ ${driverName} [${identifier}] is ready on port ${port}`);
236
236
  resolve({
237
237
  proc,
238
238
  port,
@@ -301,11 +301,11 @@ class DriverProcess {
301
301
  // the full stopTimeout + 5s SIGKILL grace because the `exit` event already
302
302
  // fired before this listener was attached.
303
303
  if (this._proc.exitCode !== null || this._proc.signalCode !== null) {
304
- log$4.debug(`${driverName} already exited (code=${this._proc.exitCode}, signal=${this._proc.signalCode})`);
304
+ log$6.debug(`${driverName} already exited (code=${this._proc.exitCode}, signal=${this._proc.signalCode})`);
305
305
  this.cleanup();
306
306
  return;
307
307
  }
308
- log$4.debug(`Stopping ${driverName}...`);
308
+ log$6.debug(`Stopping ${driverName}...`);
309
309
  this._proc.kill('SIGTERM');
310
310
  await this.waitForExit(driverName);
311
311
  this.cleanup();
@@ -338,15 +338,15 @@ class DriverProcess {
338
338
  };
339
339
  const onExit = () => {
340
340
  cleanup();
341
- log$4.debug(`${driverName} process exited`);
341
+ log$6.debug(`${driverName} process exited`);
342
342
  resolve();
343
343
  };
344
344
  this._proc?.once('exit', onExit);
345
345
  shutdownTimeout = setTimeout(() => {
346
- log$4.warn(`${driverName} did not stop gracefully after ${stopTimeout}ms, forcing kill`);
346
+ log$6.warn(`${driverName} did not stop gracefully after ${stopTimeout}ms, forcing kill`);
347
347
  this._proc?.kill('SIGKILL');
348
348
  killTimeout = setTimeout(() => {
349
- log$4.warn(`${driverName} force kill timeout, giving up`);
349
+ log$6.warn(`${driverName} force kill timeout, giving up`);
350
350
  cleanup();
351
351
  resolve();
352
352
  }, 5000);
@@ -386,12 +386,12 @@ class DriverProcess {
386
386
  // resolution path), so the responsibility shifts to the caller: resolve the
387
387
  // driver path + native driver path first, then pass them via
388
388
  // `DriverStartConfig`. The pool itself stays a thin lifecycle manager.
389
- const log$3 = nativeUtils.createLogger('native-core', 'launcher');
389
+ const log$5 = nativeUtils.createLogger('native-core', 'launcher');
390
390
  class DriverPool {
391
391
  drivers = new Map();
392
392
  async startDriver(config) {
393
393
  if (config.nativeDriverPath) {
394
- log$3.debug(`[${config.identifier}] Using native driver: ${config.nativeDriverPath}`);
394
+ log$5.debug(`[${config.identifier}] Using native driver: ${config.nativeDriverPath}`);
395
395
  }
396
396
  const driverProcess = new DriverProcess();
397
397
  await driverProcess.start({
@@ -417,34 +417,34 @@ class DriverPool {
417
417
  driverName: config.driverName,
418
418
  };
419
419
  this.drivers.set(config.identifier, info);
420
- log$3.info(`[${config.identifier}] Driver ready on port ${config.port} (native port: ${config.nativePort})`);
420
+ log$5.info(`[${config.identifier}] Driver ready on port ${config.port} (native port: ${config.nativePort})`);
421
421
  return info;
422
422
  }
423
423
  async stopDriver(identifier) {
424
424
  const info = this.drivers.get(identifier);
425
425
  if (!info) {
426
- log$3.debug(`No driver found for ${identifier}`);
426
+ log$5.debug(`No driver found for ${identifier}`);
427
427
  return;
428
428
  }
429
- log$3.info(`Stopping driver [${identifier}]`);
429
+ log$5.info(`Stopping driver [${identifier}]`);
430
430
  await info.process.stop(info.driverName);
431
431
  this.drivers.delete(identifier);
432
- log$3.debug(`Driver [${identifier}] stopped and cleaned up`);
432
+ log$5.debug(`Driver [${identifier}] stopped and cleaned up`);
433
433
  }
434
434
  async stopAll() {
435
435
  const count = this.drivers.size;
436
436
  if (count === 0) {
437
437
  return;
438
438
  }
439
- log$3.info(`Stopping ${count} driver(s)...`);
439
+ log$5.info(`Stopping ${count} driver(s)...`);
440
440
  const stopPromises = [];
441
441
  for (const [identifier, info] of this.drivers.entries()) {
442
- log$3.debug(`Stopping driver [${identifier}]...`);
442
+ log$5.debug(`Stopping driver [${identifier}]...`);
443
443
  stopPromises.push(info.process.stop(info.driverName));
444
444
  }
445
445
  await Promise.all(stopPromises);
446
446
  this.drivers.clear();
447
- log$3.debug('All drivers stopped');
447
+ log$5.debug('All drivers stopped');
448
448
  }
449
449
  getDriver(identifier) {
450
450
  return this.drivers.get(identifier);
@@ -482,7 +482,7 @@ class DriverPool {
482
482
  //
483
483
  // Services that use a single port (e.g., the embedded provider) call
484
484
  // `allocatePort` instead of `allocatePortPair`.
485
- const log$2 = nativeUtils.createLogger('native-core', 'launcher');
485
+ const log$4 = nativeUtils.createLogger('native-core', 'launcher');
486
486
  class PortManager {
487
487
  usedPorts = new Set();
488
488
  basePort;
@@ -498,7 +498,7 @@ class PortManager {
498
498
  exclude: Array.from(this.usedPorts),
499
499
  });
500
500
  this.usedPorts.add(port);
501
- log$2.debug(`Allocated port: ${port}`);
501
+ log$4.debug(`Allocated port: ${port}`);
502
502
  return port;
503
503
  }
504
504
  async allocatePortPair(preferredPort, preferredNativePort) {
@@ -521,7 +521,7 @@ class PortManager {
521
521
  throw error;
522
522
  }
523
523
  this.usedPorts.add(nativePort);
524
- log$2.debug(`Allocated port pair: main=${port}, native=${nativePort}`);
524
+ log$4.debug(`Allocated port pair: main=${port}, native=${nativePort}`);
525
525
  return { port, nativePort };
526
526
  }
527
527
  async allocatePorts(count) {
@@ -532,25 +532,25 @@ class PortManager {
532
532
  const pair = await this.allocatePortPair(preferredPort, preferredNativePort);
533
533
  pairs.push(pair);
534
534
  }
535
- log$2.info(`Allocated ${count} port pairs`);
535
+ log$4.info(`Allocated ${count} port pairs`);
536
536
  return pairs;
537
537
  }
538
538
  releasePort(port) {
539
539
  this.usedPorts.delete(port);
540
- log$2.debug(`Released port: ${port}`);
540
+ log$4.debug(`Released port: ${port}`);
541
541
  }
542
542
  releasePorts(ports) {
543
543
  for (const port of ports) {
544
544
  this.usedPorts.delete(port);
545
545
  }
546
- log$2.debug(`Released ${ports.length} ports`);
546
+ log$4.debug(`Released ${ports.length} ports`);
547
547
  }
548
548
  getUsedPorts() {
549
549
  return Array.from(this.usedPorts);
550
550
  }
551
551
  clear() {
552
552
  this.usedPorts.clear();
553
- log$2.debug('Cleared all used ports');
553
+ log$4.debug('Cleared all used ports');
554
554
  }
555
555
  }
556
556
 
@@ -589,6 +589,305 @@ class BaseLauncher {
589
589
  }
590
590
  }
591
591
 
592
+ // Dev-server lifecycle for browser mode (opt-in) — spawns a user command (e.g. `pnpm dev`), polls
593
+ // `devServerUrl` for readiness, and tears the process *tree* down. Mirrors the SIGTERM→SIGKILL
594
+ // discipline of native-core's DriverProcess / react-native-service's MetroProcess, but a free-form
595
+ // shell command + a full-URL readiness probe don't fit DriverProcess.start()'s fixed arg shape, so
596
+ // the process handling is local. Unlike those, a shell-spawned dev server spawns grandchildren
597
+ // (`pnpm dev` → vite → esbuild), so teardown kills the process group, not just the direct child.
598
+ const log$3 = nativeUtils.createLogger('native-core', 'launcher');
599
+ const isWindows = process.platform === 'win32';
600
+ const DEFAULT_READY_TIMEOUT_MS = 60_000;
601
+ const CI_READY_TIMEOUT_MS = 120_000;
602
+ const DEFAULT_POLL_MS = 500;
603
+ const DEFAULT_PROBE_TIMEOUT_MS = 3_000;
604
+ const delay$1 = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
605
+ /** Default readiness probe: a HEAD request — any HTTP response (even 404) means the server is listening. */
606
+ const defaultProbe = async (url) => {
607
+ try {
608
+ await fetch(url, { method: 'HEAD', signal: AbortSignal.timeout(DEFAULT_PROBE_TIMEOUT_MS) });
609
+ return true;
610
+ }
611
+ catch {
612
+ return false;
613
+ }
614
+ };
615
+ /**
616
+ * Kill the whole process tree. The child is spawned `detached` on POSIX so it leads its own process
617
+ * group (pgid === pid); signalling `-pid` reaches the shell *and* its grandchildren. Windows has no
618
+ * POSIX groups — `taskkill /T /F` walks the tree instead. Falls back to a direct child kill.
619
+ */
620
+ const defaultKill = (proc, signal) => {
621
+ const pid = proc.pid;
622
+ if (pid === undefined) {
623
+ proc.kill(signal);
624
+ return;
625
+ }
626
+ if (isWindows) {
627
+ node_child_process.spawn('taskkill', ['/pid', String(pid), '/T', '/F'], { stdio: 'ignore' }).on('error', () => { });
628
+ return;
629
+ }
630
+ try {
631
+ process.kill(-pid, signal);
632
+ }
633
+ catch {
634
+ // Group already gone, or the child never became a group leader — signal it directly.
635
+ proc.kill(signal);
636
+ }
637
+ };
638
+ class DevServerProcess {
639
+ #proc;
640
+ // A spawn 'error' (e.g. ENOENT) leaves exitCode/signalCode null, so the readiness loop would spin
641
+ // to the full timeout. Capture it to fail fast.
642
+ #spawnError;
643
+ // Last few stderr lines so a startup failure (port in use, bad config) surfaces its real cause in
644
+ // the thrown error rather than only at debug level.
645
+ #stderrTail = [];
646
+ #spawn;
647
+ #probe;
648
+ #kill;
649
+ constructor(deps = {}) {
650
+ this.#spawn = deps.spawn ?? node_child_process.spawn;
651
+ this.#probe = deps.probe ?? defaultProbe;
652
+ this.#kill = deps.kill ?? defaultKill;
653
+ }
654
+ isRunning() {
655
+ // A failed spawn fires 'error' but leaves exitCode/signalCode/killed in their "never started"
656
+ // state, so guard on #spawnError first.
657
+ if (this.#spawnError) {
658
+ return false;
659
+ }
660
+ const p = this.#proc;
661
+ if (!p) {
662
+ return false;
663
+ }
664
+ if (p.exitCode !== null || p.signalCode !== null) {
665
+ return false;
666
+ }
667
+ return !p.killed;
668
+ }
669
+ async start(options) {
670
+ const cwd = options.cwd ?? process.cwd();
671
+ this.#spawnError = undefined;
672
+ this.#stderrTail = [];
673
+ log$3.info(`Starting dev server: ${options.command} (cwd: ${cwd})`);
674
+ const proc = this.#spawn(options.command, {
675
+ cwd,
676
+ shell: true,
677
+ // Own process group so teardown can kill the tree (see defaultKill).
678
+ detached: !isWindows,
679
+ stdio: ['ignore', 'pipe', 'pipe'],
680
+ env: { ...process.env, ...options.env },
681
+ });
682
+ this.#proc = proc;
683
+ proc.stdout?.on('data', (d) => log$3.debug(`[dev-server] ${d.toString().trim()}`));
684
+ proc.stderr?.on('data', (d) => {
685
+ const line = d.toString().trim();
686
+ log$3.debug(`[dev-server] ${line}`);
687
+ if (line) {
688
+ this.#stderrTail.push(line);
689
+ if (this.#stderrTail.length > 20) {
690
+ this.#stderrTail.shift();
691
+ }
692
+ }
693
+ });
694
+ proc.on('error', (e) => {
695
+ this.#spawnError = e;
696
+ log$3.error(`Dev server spawn error: ${e.message}`);
697
+ });
698
+ await this.#waitForReady(options);
699
+ }
700
+ async #waitForReady(options) {
701
+ const timeout = options.timeoutMs ?? (process.env.CI ? CI_READY_TIMEOUT_MS : DEFAULT_READY_TIMEOUT_MS);
702
+ const interval = options.pollMs ?? DEFAULT_POLL_MS;
703
+ const start = Date.now();
704
+ while (Date.now() - start < timeout) {
705
+ if (this.#spawnError) {
706
+ throw new Error(`Dev server failed to start: ${this.#spawnError.message}`);
707
+ }
708
+ const p = this.#proc;
709
+ if (p && (p.exitCode !== null || p.signalCode !== null)) {
710
+ throw new Error(this.#withStderr('Dev server process exited during startup'));
711
+ }
712
+ if (await this.#probe(options.url)) {
713
+ // A spawn 'error' may have fired during the probe await; assert to defeat the stale
714
+ // control-flow narrowing from the loop-top guard.
715
+ const spawnError = this.#spawnError;
716
+ if (spawnError) {
717
+ throw new Error(`Dev server failed to start: ${spawnError.message}`);
718
+ }
719
+ // Likewise, the owned process may have exited during the probe await while a pre-existing
720
+ // server answered the URL — a fresh read of #proc reflects its current exit state.
721
+ const proc = this.#proc;
722
+ if (proc && (proc.exitCode !== null || proc.signalCode !== null)) {
723
+ throw new Error(this.#withStderr('Dev server process exited during startup'));
724
+ }
725
+ log$3.info(`Dev server ready at ${options.url}`);
726
+ return;
727
+ }
728
+ await delay$1(interval);
729
+ }
730
+ throw new Error(this.#withStderr(`Dev server did not become ready within ${timeout}ms at ${options.url}`));
731
+ }
732
+ /** Append the buffered stderr tail to a startup-failure message so the cause is visible. */
733
+ #withStderr(message) {
734
+ return this.#stderrTail.length > 0 ? `${message}\nDev server stderr:\n${this.#stderrTail.join('\n')}` : message;
735
+ }
736
+ async stop() {
737
+ const proc = this.#proc;
738
+ if (!proc || proc.killed) {
739
+ return;
740
+ }
741
+ if (this.#spawnError) {
742
+ // Spawn failed: Node fired 'error' but never will fire 'exit' — no live process to kill.
743
+ this.#proc = undefined;
744
+ return;
745
+ }
746
+ if (proc.exitCode !== null || proc.signalCode !== null) {
747
+ this.#proc = undefined;
748
+ return;
749
+ }
750
+ log$3.debug('Stopping dev server...');
751
+ this.#kill(proc, 'SIGTERM');
752
+ await this.#waitForExit(proc);
753
+ this.#proc = undefined;
754
+ }
755
+ #waitForExit(proc) {
756
+ const stopTimeout = process.env.CI ? 10_000 : 5_000;
757
+ return new Promise((resolve) => {
758
+ let killTimer;
759
+ const graceTimer = setTimeout(() => {
760
+ log$3.warn(`Dev server did not stop gracefully after ${stopTimeout}ms, forcing kill`);
761
+ this.#kill(proc, 'SIGKILL');
762
+ killTimer = setTimeout(resolve, 5_000);
763
+ }, stopTimeout);
764
+ proc.once('exit', () => {
765
+ clearTimeout(graceTimer);
766
+ if (killTimer) {
767
+ clearTimeout(killTimer);
768
+ }
769
+ resolve();
770
+ });
771
+ });
772
+ }
773
+ }
774
+
775
+ const log$2 = nativeUtils.createLogger('native-core', 'launcher');
776
+ // Browser mode drives the app's web UI through a real Chrome session (WDIO enables
777
+ // BiDi by default for browserName: 'chrome'). Any other browserName is a
778
+ // misconfiguration the launcher must reject rather than silently overwrite.
779
+ const BROWSER_MODE_SUPPORTED_BROWSER = 'chrome';
780
+ const DEV_SERVER_PROBE_TIMEOUT_MS = 3000;
781
+ /**
782
+ * Validate a user-supplied `browserName` for browser mode.
783
+ *
784
+ * Returns an actionable error message when `browserName` is set to a value the
785
+ * service can't drive in browser mode; returns `undefined` when the value is
786
+ * acceptable (unset, or one of `allowed`). Each launcher throws its own
787
+ * `SevereServiceError` with this message so the runner stops with a clear
788
+ * explanation instead of silently rewriting the capability.
789
+ *
790
+ * `allowed` defaults to `['chrome']`. Electron passes its native detection
791
+ * value too (`['chrome', 'electron']`), since the launcher rewrites a
792
+ * legitimate `browserName: 'electron'` to chrome for the browser-mode session.
793
+ */
794
+ function nonChromeBrowserNameError(browserName, allowed = [BROWSER_MODE_SUPPORTED_BROWSER]) {
795
+ if (typeof browserName !== 'string' || allowed.includes(browserName.toLowerCase())) {
796
+ return undefined;
797
+ }
798
+ // `allowed` also carries each service's native detection name (e.g. 'electron', 'wry') so a
799
+ // carried-over native cap isn't rejected — but those aren't something to advise setting, so the
800
+ // message guides the user to 'chrome' (or removal), not the full allow-list.
801
+ return (`Browser mode only supports browserName: '${BROWSER_MODE_SUPPORTED_BROWSER}', but got '${browserName}'. ` +
802
+ `Remove the browserName from your capability (it is set automatically) or set it to '${BROWSER_MODE_SUPPORTED_BROWSER}'.`);
803
+ }
804
+ /**
805
+ * Preflight the dev server before the worker navigates to it.
806
+ *
807
+ * A HEAD request with a short timeout. Any non-network response (even 404/405)
808
+ * proves the server is listening, so only a thrown fetch error (connection
809
+ * refused, DNS failure, timeout) counts as unreachable. Runs in the launcher's
810
+ * main process where outbound network is available.
811
+ */
812
+ async function probeDevServerReachable(url, timeoutMs = DEV_SERVER_PROBE_TIMEOUT_MS) {
813
+ try {
814
+ await fetch(url, { method: 'HEAD', signal: AbortSignal.timeout(timeoutMs) });
815
+ return nativeUtils.Ok(undefined);
816
+ }
817
+ catch (error) {
818
+ const detail = error instanceof Error ? error.message : String(error);
819
+ return nativeUtils.Err(new Error(`Dev server not reachable at ${url} — is it running? (${detail})`));
820
+ }
821
+ }
822
+ const DEV_SERVER_READY_TIMEOUT_MS = 60_000;
823
+ const DEV_SERVER_READY_POLL_MS = 500;
824
+ const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
825
+ /**
826
+ * Poll {@link probeDevServerReachable} until the server answers or the budget elapses.
827
+ *
828
+ * The single-shot `probeDevServerReachable` is a preflight for a server the user already started;
829
+ * this is the "wait for a server we (or the user's function) just started to come up" variant.
830
+ */
831
+ async function waitForDevServerReachable(url, { timeoutMs = DEV_SERVER_READY_TIMEOUT_MS, pollMs = DEV_SERVER_READY_POLL_MS, } = {}) {
832
+ const start = Date.now();
833
+ let last = await probeDevServerReachable(url);
834
+ while (nativeUtils.isErr(last) && Date.now() - start < timeoutMs) {
835
+ await delay(pollMs);
836
+ last = await probeDevServerReachable(url);
837
+ }
838
+ return last;
839
+ }
840
+ /**
841
+ * Start (or reuse) a dev server for browser mode and return a handle to tear it down.
842
+ *
843
+ * Handles all three {@link DevServer} forms so each launcher stays a few lines:
844
+ * - **function** — call it, poll its returned `url` for readiness, and teardown is its `close()`
845
+ * (no subprocess spawn/kill involved). The returned `url` supplies/overrides `devServerUrl`.
846
+ * - **string / object** — if `reuseExistingServer` (default `!CI`) and `devServerUrl` is already
847
+ * reachable, skip the spawn; otherwise spawn a {@link DevServerProcess} and poll `devServerUrl`.
848
+ *
849
+ * The caller stores the returned `stop` and must call it in `onComplete` *and* on an `onPrepare`
850
+ * failure (WDIO does not call `onComplete` after `onPrepare` throws). `stop` is idempotent.
851
+ */
852
+ async function startManagedDevServer(devServer, devServerUrl, deps = {}) {
853
+ if (typeof devServer === 'function') {
854
+ const { url, close } = await devServer();
855
+ const ready = await waitForDevServerReachable(url, {
856
+ timeoutMs: deps.readinessTimeoutMs,
857
+ pollMs: deps.readinessPollMs,
858
+ });
859
+ if (nativeUtils.isErr(ready)) {
860
+ await close();
861
+ throw ready.error;
862
+ }
863
+ return { url, stop: close };
864
+ }
865
+ const config = typeof devServer === 'string' ? { command: devServer } : devServer;
866
+ const isCI = deps.isCI ?? Boolean(process.env.CI);
867
+ const reuseExisting = config.reuseExistingServer ?? !isCI;
868
+ if (reuseExisting && nativeUtils.isOk(await probeDevServerReachable(devServerUrl))) {
869
+ log$2.info(`Reusing dev server already reachable at ${devServerUrl}`);
870
+ return { url: devServerUrl, stop: async () => { } };
871
+ }
872
+ const proc = new DevServerProcess({ spawn: deps.spawn, probe: deps.probe });
873
+ try {
874
+ await proc.start({
875
+ command: config.command,
876
+ cwd: config.cwd,
877
+ env: config.env,
878
+ url: devServerUrl,
879
+ timeoutMs: config.timeoutMs,
880
+ });
881
+ }
882
+ catch (error) {
883
+ // start() can throw *after* the process spawned (readiness timeout) — stop the live-but-unready
884
+ // process before propagating, or it orphans (holding the port). Mirrors the function form's close().
885
+ await proc.stop();
886
+ throw error;
887
+ }
888
+ return { url: devServerUrl, stop: () => proc.stop() };
889
+ }
890
+
592
891
  // Platform-specific deeplink (URL protocol-handler) helpers.
593
892
  //
594
893
  // Extracted from packages/tauri-service/src/commands/triggerDeeplink.ts.
@@ -886,7 +1185,9 @@ function isStandaloneLogWriterInitialized() {
886
1185
  return isLogWriterInitialized('electron-service');
887
1186
  }
888
1187
 
1188
+ exports.BROWSER_MODE_SUPPORTED_BROWSER = BROWSER_MODE_SUPPORTED_BROWSER;
889
1189
  exports.BaseLauncher = BaseLauncher;
1190
+ exports.DevServerProcess = DevServerProcess;
890
1191
  exports.DriverPool = DriverPool;
891
1192
  exports.DriverProcess = DriverProcess;
892
1193
  exports.LOG_LEVEL_PRIORITY = LOG_LEVEL_PRIORITY;
@@ -901,6 +1202,10 @@ exports.getPlatformCommand = getPlatformCommand;
901
1202
  exports.getStandaloneLogWriter = getStandaloneLogWriter;
902
1203
  exports.isLogWriterInitialized = isLogWriterInitialized;
903
1204
  exports.isStandaloneLogWriterInitialized = isStandaloneLogWriterInitialized;
1205
+ exports.nonChromeBrowserNameError = nonChromeBrowserNameError;
1206
+ exports.probeDevServerReachable = probeDevServerReachable;
904
1207
  exports.shouldLog = shouldLog;
1208
+ exports.startManagedDevServer = startManagedDevServer;
905
1209
  exports.validateDeeplinkUrl = validateDeeplinkUrl;
1210
+ exports.waitForDevServerReachable = waitForDevServerReachable;
906
1211
  //# sourceMappingURL=index.js.map