@wdio/native-core 0.0.1

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 (44) hide show
  1. package/LICENSE +21 -0
  2. package/dist/cjs/baseLauncher.d.ts +24 -0
  3. package/dist/cjs/baseLauncher.d.ts.map +1 -0
  4. package/dist/cjs/deeplink.d.ts +44 -0
  5. package/dist/cjs/deeplink.d.ts.map +1 -0
  6. package/dist/cjs/driverPool.d.ts +45 -0
  7. package/dist/cjs/driverPool.d.ts.map +1 -0
  8. package/dist/cjs/driverProcess.d.ts +69 -0
  9. package/dist/cjs/driverProcess.d.ts.map +1 -0
  10. package/dist/cjs/index.d.ts +9 -0
  11. package/dist/cjs/index.d.ts.map +1 -0
  12. package/dist/cjs/index.js +906 -0
  13. package/dist/cjs/index.js.map +1 -0
  14. package/dist/cjs/logCapture.d.ts +43 -0
  15. package/dist/cjs/logCapture.d.ts.map +1 -0
  16. package/dist/cjs/logLevel.d.ts +12 -0
  17. package/dist/cjs/logLevel.d.ts.map +1 -0
  18. package/dist/cjs/logWriter.d.ts +71 -0
  19. package/dist/cjs/logWriter.d.ts.map +1 -0
  20. package/dist/cjs/package.json +1 -0
  21. package/dist/cjs/portManager.d.ts +18 -0
  22. package/dist/cjs/portManager.d.ts.map +1 -0
  23. package/dist/esm/baseLauncher.d.ts +24 -0
  24. package/dist/esm/baseLauncher.d.ts.map +1 -0
  25. package/dist/esm/deeplink.d.ts +44 -0
  26. package/dist/esm/deeplink.d.ts.map +1 -0
  27. package/dist/esm/driverPool.d.ts +45 -0
  28. package/dist/esm/driverPool.d.ts.map +1 -0
  29. package/dist/esm/driverProcess.d.ts +69 -0
  30. package/dist/esm/driverProcess.d.ts.map +1 -0
  31. package/dist/esm/index.d.ts +9 -0
  32. package/dist/esm/index.d.ts.map +1 -0
  33. package/dist/esm/index.js +888 -0
  34. package/dist/esm/index.js.map +1 -0
  35. package/dist/esm/logCapture.d.ts +43 -0
  36. package/dist/esm/logCapture.d.ts.map +1 -0
  37. package/dist/esm/logLevel.d.ts +12 -0
  38. package/dist/esm/logLevel.d.ts.map +1 -0
  39. package/dist/esm/logWriter.d.ts +71 -0
  40. package/dist/esm/logWriter.d.ts.map +1 -0
  41. package/dist/esm/package.json +1 -0
  42. package/dist/esm/portManager.d.ts +18 -0
  43. package/dist/esm/portManager.d.ts.map +1 -0
  44. package/package.json +80 -0
@@ -0,0 +1,888 @@
1
+ import { createLogger } from '@wdio/native-utils';
2
+ import { spawn } from 'node:child_process';
3
+ import http from 'node:http';
4
+ import net from 'node:net';
5
+ import { createInterface } from 'node:readline';
6
+ import getPort from 'get-port';
7
+ import { existsSync, mkdirSync, createWriteStream } from 'node:fs';
8
+ import { join } from 'node:path';
9
+
10
+ // Stream-based log capture skeleton.
11
+ //
12
+ // Extracted from packages/tauri-service/src/logCapture.ts. Provides the
13
+ // readline plumbing and driver-bring-up marker detection shared between
14
+ // Tauri and Dioxus (both spawn an external driver subprocess and need to
15
+ // surface its stdout/stderr).
16
+ //
17
+ // Parsing and forwarding are injected as callbacks because each service has
18
+ // its own log format (Tauri: `[Tauri:Backend]` prefixes filtered against
19
+ // `tauri-driver` patterns; Dioxus: TBD; Electron uses CDP, not streams).
20
+ // Keeping this module callback-driven means core has zero knowledge of any
21
+ // service's log conventions.
22
+ //
23
+ // Electron's `LogCaptureManager` (packages/electron-service/src/logCapture.ts)
24
+ // is intentionally NOT migrated here — it consumes CDP `Runtime.consoleAPICalled`
25
+ // events on a running Electron app, a fundamentally different domain.
26
+ const log$5 = createLogger('native-core', 'launcher');
27
+ /**
28
+ * Create a log capture handler for a child-process stream (stdout/stderr).
29
+ *
30
+ * Wraps the stream in a readline interface, runs each line through
31
+ * driver-bring-up marker detection (if callbacks are wired), and then
32
+ * delegates to `onLine` for parsing and forwarding.
33
+ *
34
+ * Returns `undefined` if `stream` is null (caller can skip cleanup).
35
+ */
36
+ function createLogCapture(opts) {
37
+ const { stream, identifier, instanceId, onStartupDetected, onErrorDetected, startupMarkers, errorMarkers, onLine } = opts;
38
+ if (!stream) {
39
+ return undefined;
40
+ }
41
+ const rl = createInterface({
42
+ input: stream,
43
+ crlfDelay: Infinity,
44
+ });
45
+ rl.on('line', (line) => {
46
+ if (onStartupDetected && startupMarkers?.some((m) => line.includes(m))) {
47
+ onStartupDetected();
48
+ }
49
+ if (onErrorDetected && errorMarkers?.some((m) => line.includes(m))) {
50
+ onErrorDetected(`Failed to bind: ${line}`);
51
+ }
52
+ onLine(line, instanceId);
53
+ });
54
+ rl.on('error', (err) => {
55
+ log$5.warn(`[${identifier}] Stream error: ${err.message}`);
56
+ });
57
+ return rl;
58
+ }
59
+
60
+ // Generic driver subprocess lifecycle.
61
+ //
62
+ // Extracted from packages/tauri-service/src/driverProcess.ts. Generalised so
63
+ // both `wdio-tauri-service` (tauri-driver) and `wdio-dioxus-service`
64
+ // (wdio-dioxus-driver) can use it without subclassing.
65
+ //
66
+ // Tauri-isms scrubbed:
67
+ // - `tauriDriverPath` → `driverPath`.
68
+ // - `TauriServiceOptions` import removed; log forwarding is now injected
69
+ // via the `onLogLine` callback (caller decides parser + forwarder).
70
+ // - Log strings parameterised on `driverName` (default 'driver'); callers
71
+ // pass 'tauri-driver' or 'wdio-dioxus-driver' to keep diagnostics
72
+ // readable.
73
+ // - `startupMarkers` / `errorMarkers` moved out of the file's defaults
74
+ // into the caller's `DriverStartOptions` so each service supplies its
75
+ // own (we used to hardcode Tauri's strings).
76
+ //
77
+ // The poll-for-readiness behaviour (TCP open + HTTP /status reachable),
78
+ // SIGTERM-then-SIGKILL shutdown sequence, and CI-aware timeouts all
79
+ // transfer unchanged — they're generic.
80
+ const log$4 = createLogger('native-core', 'launcher');
81
+ /**
82
+ * Manages a single driver subprocess lifecycle (Tauri's tauri-driver,
83
+ * Dioxus's wdio-dioxus-driver, or any other WebDriver proxy).
84
+ */
85
+ class DriverProcess {
86
+ _proc;
87
+ streamHandlers = [];
88
+ startupTimeout;
89
+ pollTimer;
90
+ startTimeout = 30000; // 30 seconds
91
+ _port;
92
+ _nativePort;
93
+ _dataDir;
94
+ get proc() {
95
+ return this._proc;
96
+ }
97
+ get port() {
98
+ return this._port;
99
+ }
100
+ get nativePort() {
101
+ return this._nativePort;
102
+ }
103
+ get dataDir() {
104
+ return this._dataDir;
105
+ }
106
+ async start(options) {
107
+ const { identifier, port, nativePort, driverPath, nativeDriverPath, env, onLogLine, startupMarkers, errorMarkers, instanceId, } = options;
108
+ const driverName = options.driverName ?? 'driver';
109
+ this._port = port;
110
+ this._nativePort = nativePort;
111
+ this._dataDir = options.dataDir;
112
+ log$4.info(`Starting ${driverName} [${identifier}] on port ${port} (native port: ${nativePort})`);
113
+ const args = ['--port', port.toString(), '--native-port', nativePort.toString()];
114
+ if (nativeDriverPath) {
115
+ args.push('--native-driver', nativeDriverPath);
116
+ log$4.debug(`[${identifier}] Using native driver: ${nativeDriverPath}`);
117
+ }
118
+ return new Promise((resolve, reject) => {
119
+ let settled = false;
120
+ const safeResolve = (info) => {
121
+ if (!settled) {
122
+ settled = true;
123
+ this.cleanupTimeout();
124
+ resolve(info);
125
+ }
126
+ };
127
+ const safeReject = (err) => {
128
+ if (!settled) {
129
+ settled = true;
130
+ this.cleanupTimeout();
131
+ this.cleanup();
132
+ reject(err);
133
+ }
134
+ };
135
+ try {
136
+ const spawnEnv = env ? { ...process.env, ...env } : process.env;
137
+ this._proc = spawn(driverPath, args, {
138
+ stdio: ['ignore', 'pipe', 'pipe'],
139
+ detached: false,
140
+ env: spawnEnv,
141
+ shell: process.platform === 'win32',
142
+ });
143
+ log$4.info(`[${identifier}] Spawned process with PID: ${this._proc.pid ?? 'unknown'}`);
144
+ this.startupTimeout = setTimeout(() => {
145
+ if (!settled) {
146
+ safeReject(new Error(`${driverName} [${identifier}] failed to start within ${this.startTimeout}ms`));
147
+ }
148
+ }, this.startTimeout);
149
+ const noop = () => {
150
+ /* caller didn't wire log capture */
151
+ };
152
+ // When the driver emits a known startupMarker (e.g. 'tauri-driver started'),
153
+ // resolve immediately rather than waiting for pollForReadiness to round-trip
154
+ // through the TCP/HTTP poll loop. safeResolve is idempotent, so the poll
155
+ // path remains a safety net if no marker is seen.
156
+ const onStartupDetected = () => {
157
+ log$4.info(`✅ ${driverName} [${identifier}] startup marker detected`);
158
+ // this._proc is non-null here (we just spawned it above), but the
159
+ // signature widens with cleanup() — assert via the original ref.
160
+ if (this._proc) {
161
+ safeResolve({
162
+ proc: this._proc,
163
+ port,
164
+ nativePort,
165
+ dataDir: options.dataDir,
166
+ });
167
+ }
168
+ };
169
+ const stdoutHandler = createLogCapture({
170
+ stream: this._proc.stdout,
171
+ identifier,
172
+ instanceId,
173
+ startupMarkers,
174
+ errorMarkers,
175
+ onStartupDetected,
176
+ onErrorDetected: (message) => safeReject(new Error(message)),
177
+ onLine: onLogLine ?? noop,
178
+ });
179
+ const stderrHandler = createLogCapture({
180
+ stream: this._proc.stderr,
181
+ identifier,
182
+ instanceId,
183
+ startupMarkers,
184
+ errorMarkers,
185
+ onStartupDetected,
186
+ onErrorDetected: (message) => safeReject(new Error(message)),
187
+ onLine: onLogLine ?? noop,
188
+ });
189
+ if (stdoutHandler)
190
+ this.streamHandlers.push(stdoutHandler);
191
+ if (stderrHandler)
192
+ this.streamHandlers.push(stderrHandler);
193
+ this._proc.once('exit', (code, signal) => {
194
+ if (!settled) {
195
+ safeReject(new Error(`${driverName} [${identifier}] exited unexpectedly during startup (code: ${code}, signal: ${signal})`));
196
+ }
197
+ });
198
+ this._proc.once('error', (err) => {
199
+ safeReject(new Error(`${driverName} [${identifier}] failed to start: ${err.message}`));
200
+ });
201
+ this.pollForReadiness(driverName, identifier, port, nativePort, options.dataDir, safeResolve, safeReject);
202
+ }
203
+ catch (error) {
204
+ safeReject(error instanceof Error ? error : new Error(String(error)));
205
+ }
206
+ });
207
+ }
208
+ async pollForReadiness(driverName, identifier, port, nativePort, dataDir, resolve, reject) {
209
+ const startTime = Date.now();
210
+ const timeout = 10000;
211
+ const pollInterval = 100;
212
+ const poll = async () => {
213
+ // Snapshot this._proc into a local so the narrowing survives awaits and
214
+ // the resolve() call below doesn't need a non-null assertion. The next
215
+ // poll() invocation re-reads this._proc fresh, so a between-tick
216
+ // cleanup() that nulls the field is still caught.
217
+ const proc = this._proc;
218
+ // Match the stop()/isRunning() guard: ChildProcess.killed only flips
219
+ // after an explicit subprocess.kill() call, so a process that exited
220
+ // naturally has killed=false but exitCode or signalCode set.
221
+ if (!proc || proc.killed || proc.exitCode !== null || proc.signalCode !== null) {
222
+ reject(new Error(`${driverName} [${identifier}] process died during startup`));
223
+ return;
224
+ }
225
+ if (Date.now() - startTime > timeout) {
226
+ reject(new Error(`${driverName} [${identifier}] failed to become ready within ${timeout}ms`));
227
+ return;
228
+ }
229
+ const isPortOpen = await this.isPortOpen(port, 500);
230
+ if (isPortOpen) {
231
+ try {
232
+ await this.waitForHttpReady(port, 1000);
233
+ log$4.info(`✅ ${driverName} [${identifier}] is ready on port ${port}`);
234
+ resolve({
235
+ proc,
236
+ port,
237
+ nativePort,
238
+ dataDir,
239
+ });
240
+ return;
241
+ }
242
+ catch {
243
+ // Port open, HTTP not ready yet — keep polling.
244
+ }
245
+ }
246
+ this.pollTimer = setTimeout(poll, pollInterval);
247
+ };
248
+ poll();
249
+ }
250
+ async isPortOpen(port, timeout) {
251
+ return new Promise((resolve) => {
252
+ const socket = new net.Socket();
253
+ let settled = false;
254
+ const cleanup = () => {
255
+ if (!settled) {
256
+ settled = true;
257
+ socket.destroy();
258
+ }
259
+ };
260
+ socket.setTimeout(timeout);
261
+ socket.once('error', () => {
262
+ cleanup();
263
+ resolve(false);
264
+ });
265
+ socket.once('timeout', () => {
266
+ cleanup();
267
+ resolve(false);
268
+ });
269
+ socket.connect(port, '127.0.0.1', () => {
270
+ cleanup();
271
+ resolve(true);
272
+ });
273
+ });
274
+ }
275
+ async waitForHttpReady(port, timeout) {
276
+ return new Promise((resolve, reject) => {
277
+ const request = http.get(`http://127.0.0.1:${port}/status`, (res) => {
278
+ res.resume();
279
+ request.destroy();
280
+ resolve();
281
+ });
282
+ request.setTimeout(timeout, () => {
283
+ request.destroy();
284
+ reject(new Error('HTTP request timeout'));
285
+ });
286
+ request.on('error', (err) => {
287
+ request.destroy();
288
+ reject(err);
289
+ });
290
+ });
291
+ }
292
+ async stop(driverName = 'driver') {
293
+ if (!this._proc || this._proc.killed) {
294
+ return;
295
+ }
296
+ // Process already exited naturally (crash or normal exit). `killed` is only
297
+ // set by an explicit `.kill()` call, so the guard above misses this case —
298
+ // without the early return, SIGTERM is a no-op and waitForExit() hangs for
299
+ // the full stopTimeout + 5s SIGKILL grace because the `exit` event already
300
+ // fired before this listener was attached.
301
+ if (this._proc.exitCode !== null || this._proc.signalCode !== null) {
302
+ log$4.debug(`${driverName} already exited (code=${this._proc.exitCode}, signal=${this._proc.signalCode})`);
303
+ this.cleanup();
304
+ return;
305
+ }
306
+ log$4.debug(`Stopping ${driverName}...`);
307
+ this._proc.kill('SIGTERM');
308
+ await this.waitForExit(driverName);
309
+ this.cleanup();
310
+ // Additional delay to ensure the port is fully released.
311
+ await new Promise((resolve) => setTimeout(resolve, 500));
312
+ }
313
+ isRunning() {
314
+ if (!this._proc) {
315
+ return false;
316
+ }
317
+ // `.killed` is only set by explicit subprocess.kill() calls. A process that
318
+ // exited naturally (crash / normal exit) has killed=false but exitCode or
319
+ // signalCode set, so checking only `.killed` reports a dead process as
320
+ // running. See the matching guard in stop().
321
+ if (this._proc.exitCode !== null || this._proc.signalCode !== null) {
322
+ return false;
323
+ }
324
+ return !this._proc.killed;
325
+ }
326
+ async waitForExit(driverName) {
327
+ const stopTimeout = process.env.CI ? 10000 : 5000;
328
+ return new Promise((resolve) => {
329
+ let shutdownTimeout = null;
330
+ let killTimeout = null;
331
+ const cleanup = () => {
332
+ if (shutdownTimeout)
333
+ clearTimeout(shutdownTimeout);
334
+ if (killTimeout)
335
+ clearTimeout(killTimeout);
336
+ };
337
+ const onExit = () => {
338
+ cleanup();
339
+ log$4.debug(`${driverName} process exited`);
340
+ resolve();
341
+ };
342
+ this._proc?.once('exit', onExit);
343
+ shutdownTimeout = setTimeout(() => {
344
+ log$4.warn(`${driverName} did not stop gracefully after ${stopTimeout}ms, forcing kill`);
345
+ this._proc?.kill('SIGKILL');
346
+ killTimeout = setTimeout(() => {
347
+ log$4.warn(`${driverName} force kill timeout, giving up`);
348
+ cleanup();
349
+ resolve();
350
+ }, 5000);
351
+ }, stopTimeout);
352
+ });
353
+ }
354
+ cleanup() {
355
+ this.cleanupTimeout();
356
+ for (const handler of this.streamHandlers) {
357
+ handler.close();
358
+ }
359
+ this.streamHandlers = [];
360
+ if (this._proc) {
361
+ this._proc.removeAllListeners('exit');
362
+ this._proc.removeAllListeners('error');
363
+ }
364
+ }
365
+ cleanupTimeout() {
366
+ if (this.startupTimeout) {
367
+ clearTimeout(this.startupTimeout);
368
+ this.startupTimeout = undefined;
369
+ }
370
+ if (this.pollTimer) {
371
+ clearTimeout(this.pollTimer);
372
+ this.pollTimer = undefined;
373
+ }
374
+ }
375
+ }
376
+
377
+ // Driver subprocess pool — track multiple {@link DriverProcess} instances
378
+ // by identifier, start them on demand, stop them in bulk.
379
+ //
380
+ // Extracted from packages/tauri-service/src/driverPool.ts. The original
381
+ // version called `ensureTauriDriver()` and `getWebKitWebDriverPath()` inside
382
+ // `startDriver`. Those resolutions are inherently service-specific (Tauri
383
+ // knows how to `cargo install tauri-driver`; Dioxus has its own driver-
384
+ // resolution path), so the responsibility shifts to the caller: resolve the
385
+ // driver path + native driver path first, then pass them via
386
+ // `DriverStartConfig`. The pool itself stays a thin lifecycle manager.
387
+ const log$3 = createLogger('native-core', 'launcher');
388
+ class DriverPool {
389
+ drivers = new Map();
390
+ async startDriver(config) {
391
+ if (config.nativeDriverPath) {
392
+ log$3.debug(`[${config.identifier}] Using native driver: ${config.nativeDriverPath}`);
393
+ }
394
+ const driverProcess = new DriverProcess();
395
+ await driverProcess.start({
396
+ mode: config.mode,
397
+ identifier: config.identifier,
398
+ port: config.port,
399
+ nativePort: config.nativePort,
400
+ driverPath: config.driverPath,
401
+ nativeDriverPath: config.nativeDriverPath,
402
+ env: config.env,
403
+ instanceId: config.instanceId,
404
+ driverName: config.driverName,
405
+ onLogLine: config.onLogLine,
406
+ startupMarkers: config.startupMarkers,
407
+ errorMarkers: config.errorMarkers,
408
+ });
409
+ const info = {
410
+ process: driverProcess,
411
+ port: config.port,
412
+ nativePort: config.nativePort,
413
+ mode: config.mode,
414
+ identifier: config.identifier,
415
+ driverName: config.driverName,
416
+ };
417
+ this.drivers.set(config.identifier, info);
418
+ log$3.info(`[${config.identifier}] Driver ready on port ${config.port} (native port: ${config.nativePort})`);
419
+ return info;
420
+ }
421
+ async stopDriver(identifier) {
422
+ const info = this.drivers.get(identifier);
423
+ if (!info) {
424
+ log$3.debug(`No driver found for ${identifier}`);
425
+ return;
426
+ }
427
+ log$3.info(`Stopping driver [${identifier}]`);
428
+ await info.process.stop(info.driverName);
429
+ this.drivers.delete(identifier);
430
+ log$3.debug(`Driver [${identifier}] stopped and cleaned up`);
431
+ }
432
+ async stopAll() {
433
+ const count = this.drivers.size;
434
+ if (count === 0) {
435
+ return;
436
+ }
437
+ log$3.info(`Stopping ${count} driver(s)...`);
438
+ const stopPromises = [];
439
+ for (const [identifier, info] of this.drivers.entries()) {
440
+ log$3.debug(`Stopping driver [${identifier}]...`);
441
+ stopPromises.push(info.process.stop(info.driverName));
442
+ }
443
+ await Promise.all(stopPromises);
444
+ this.drivers.clear();
445
+ log$3.debug('All drivers stopped');
446
+ }
447
+ getDriver(identifier) {
448
+ return this.drivers.get(identifier);
449
+ }
450
+ getDriverProcess(identifier) {
451
+ return this.drivers.get(identifier)?.process;
452
+ }
453
+ getStatus() {
454
+ const identifiers = Array.from(this.drivers.keys());
455
+ const runningCount = Array.from(this.drivers.values()).filter((info) => info.process.isRunning()).length;
456
+ return {
457
+ running: runningCount > 0,
458
+ count: runningCount,
459
+ identifiers,
460
+ };
461
+ }
462
+ getRunningPids() {
463
+ const pids = [];
464
+ for (const info of this.drivers.values()) {
465
+ if (info.process.isRunning() && info.process.proc?.pid) {
466
+ pids.push(info.process.proc.pid);
467
+ }
468
+ }
469
+ return pids;
470
+ }
471
+ }
472
+
473
+ // Port allocation for driver subprocesses.
474
+ //
475
+ // Extracted unchanged from packages/tauri-service/src/portManager.ts (the
476
+ // only modification is the `createLogger` argument). The "port pair"
477
+ // abstraction (main driver port + native driver port) maps directly onto
478
+ // both Tauri's (tauri-driver + msedgedriver/WebKitWebDriver) and Dioxus's
479
+ // (wdio-dioxus-driver + msedgedriver) external-provider layout.
480
+ //
481
+ // Services that use a single port (e.g., the embedded provider) call
482
+ // `allocatePort` instead of `allocatePortPair`.
483
+ const log$2 = createLogger('native-core', 'launcher');
484
+ class PortManager {
485
+ usedPorts = new Set();
486
+ basePort;
487
+ baseNativePort;
488
+ constructor(basePort = 4444, baseNativePort = 4445) {
489
+ this.basePort = basePort;
490
+ this.baseNativePort = baseNativePort;
491
+ }
492
+ async allocatePort(preferredPort) {
493
+ const port = await getPort({
494
+ port: preferredPort ?? this.basePort,
495
+ host: '127.0.0.1',
496
+ exclude: Array.from(this.usedPorts),
497
+ });
498
+ this.usedPorts.add(port);
499
+ log$2.debug(`Allocated port: ${port}`);
500
+ return port;
501
+ }
502
+ async allocatePortPair(preferredPort, preferredNativePort) {
503
+ const port = await getPort({
504
+ port: preferredPort ?? this.basePort,
505
+ host: '127.0.0.1',
506
+ exclude: Array.from(this.usedPorts),
507
+ });
508
+ this.usedPorts.add(port);
509
+ let nativePort;
510
+ try {
511
+ nativePort = await getPort({
512
+ port: preferredNativePort ?? this.baseNativePort,
513
+ host: '127.0.0.1',
514
+ exclude: Array.from(this.usedPorts),
515
+ });
516
+ }
517
+ catch (error) {
518
+ this.usedPorts.delete(port);
519
+ throw error;
520
+ }
521
+ this.usedPorts.add(nativePort);
522
+ log$2.debug(`Allocated port pair: main=${port}, native=${nativePort}`);
523
+ return { port, nativePort };
524
+ }
525
+ async allocatePorts(count) {
526
+ const pairs = [];
527
+ for (let i = 0; i < count; i++) {
528
+ const preferredPort = this.basePort + i;
529
+ const preferredNativePort = this.baseNativePort + i;
530
+ const pair = await this.allocatePortPair(preferredPort, preferredNativePort);
531
+ pairs.push(pair);
532
+ }
533
+ log$2.info(`Allocated ${count} port pairs`);
534
+ return pairs;
535
+ }
536
+ releasePort(port) {
537
+ this.usedPorts.delete(port);
538
+ log$2.debug(`Released port: ${port}`);
539
+ }
540
+ releasePorts(ports) {
541
+ for (const port of ports) {
542
+ this.usedPorts.delete(port);
543
+ }
544
+ log$2.debug(`Released ${ports.length} ports`);
545
+ }
546
+ getUsedPorts() {
547
+ return Array.from(this.usedPorts);
548
+ }
549
+ clear() {
550
+ this.usedPorts.clear();
551
+ log$2.debug('Cleared all used ports');
552
+ }
553
+ }
554
+
555
+ // Abstract base class for service launchers (Tauri, Dioxus, Electron, …).
556
+ //
557
+ // Holds the two pieces of shared launcher state every native desktop service
558
+ // needs: a {@link PortManager} for allocating driver ports, and a
559
+ // {@link DriverPool} for tracking running driver subprocesses. Subclasses
560
+ // supply their own WDIO service hooks (`onPrepare`, `onWorkerStart`,
561
+ // `onWorkerEnd`, `onComplete`) and call the protected helpers when stopping
562
+ // drivers in bulk.
563
+ //
564
+ // Intentionally minimal in v1. As `@wdio/dioxus-service` materialises and we
565
+ // see which patterns are actually shared (vs incidentally similar), more
566
+ // behaviour will migrate here. Today the priority is "give subclasses a
567
+ // place to inherit shared state from", not "lock in an interface that's
568
+ // over-fitted to one consumer."
569
+ /**
570
+ * Common launcher state shared by every native desktop service. Subclasses
571
+ * implement WDIO service hooks (`onPrepare`, `onWorkerStart`, `onWorkerEnd`,
572
+ * `onComplete`) and orchestrate driver lifecycle via the protected fields.
573
+ */
574
+ class BaseLauncher {
575
+ portManager;
576
+ driverPool;
577
+ constructor(config = {}) {
578
+ this.portManager = new PortManager(config.basePort ?? 4444, config.baseNativePort ?? 4445);
579
+ this.driverPool = new DriverPool();
580
+ }
581
+ /**
582
+ * Stop every running driver in the pool. Subclasses typically call this
583
+ * from their `onComplete` hook to ensure no subprocess leaks across runs.
584
+ */
585
+ async stopAllDrivers() {
586
+ await this.driverPool.stopAll();
587
+ }
588
+ }
589
+
590
+ // Platform-specific deeplink (URL protocol-handler) helpers.
591
+ //
592
+ // Extracted from packages/tauri-service/src/commands/triggerDeeplink.ts.
593
+ // These three helpers are framework-agnostic — every desktop service that
594
+ // needs to trigger an OS-level protocol handler (`myapp://...`) goes through
595
+ // the same `rundll32.exe` / `open` / `gio open` invocations.
596
+ //
597
+ // The service-specific orchestration (browser.execute-based injection for
598
+ // embedded mode, env-var-driven mode switching, etc.) stays in each
599
+ // service's own triggerDeeplink command.
600
+ const log$1 = createLogger('native-core', 'triggerDeeplink');
601
+ /**
602
+ * Validate a deeplink URL. Throws if the URL is malformed or uses a
603
+ * non-custom protocol (http, https, file).
604
+ *
605
+ * Returns the URL unchanged on success — the return value exists so callers
606
+ * can chain or assign in one step.
607
+ */
608
+ function validateDeeplinkUrl(url) {
609
+ let parsedUrl;
610
+ try {
611
+ parsedUrl = new URL(url);
612
+ }
613
+ catch {
614
+ throw new Error(`Invalid deeplink URL: ${url}`);
615
+ }
616
+ const disallowedProtocols = ['http:', 'https:', 'file:'];
617
+ if (disallowedProtocols.includes(parsedUrl.protocol)) {
618
+ const protocol = parsedUrl.protocol.slice(0, -1);
619
+ throw new Error(`Invalid deeplink protocol: ${protocol}. Expected a custom protocol (e.g., myapp://).`);
620
+ }
621
+ return url;
622
+ }
623
+ /**
624
+ * Generates the platform-specific command to trigger a deeplink.
625
+ *
626
+ * @param url - The deeplink URL to trigger.
627
+ * @param platform - `process.platform` value: `'win32'`, `'darwin'`, or `'linux'`.
628
+ * @returns Command and arguments for `child_process.spawn`.
629
+ * @throws If `platform` is unsupported.
630
+ *
631
+ * @example
632
+ * ```ts
633
+ * getPlatformCommand('myapp://test', 'win32');
634
+ * // { command: 'rundll32.exe', args: ['url.dll,FileProtocolHandler', 'myapp://test'] }
635
+ *
636
+ * getPlatformCommand('myapp://test', 'darwin');
637
+ * // { command: 'open', args: ['myapp://test'] }
638
+ *
639
+ * getPlatformCommand('myapp://test', 'linux');
640
+ * // { command: 'gio', args: ['open', 'myapp://test'] }
641
+ * ```
642
+ */
643
+ function getPlatformCommand(url, platform) {
644
+ switch (platform) {
645
+ case 'win32':
646
+ return {
647
+ command: 'rundll32.exe',
648
+ args: ['url.dll,FileProtocolHandler', url],
649
+ };
650
+ case 'darwin':
651
+ return {
652
+ command: 'open',
653
+ args: [url],
654
+ };
655
+ case 'linux':
656
+ return {
657
+ command: 'gio',
658
+ args: ['open', url],
659
+ };
660
+ default:
661
+ throw new Error(`Unsupported platform for deeplink triggering: ${platform}. ` +
662
+ 'Supported platforms are: win32, darwin, linux.');
663
+ }
664
+ }
665
+ /**
666
+ * Spawns the deeplink command as a detached child process. Returns once the
667
+ * process has been spawned (not when it completes — the OS handler may take
668
+ * arbitrary time and is fire-and-forget).
669
+ *
670
+ * @param command - The command to execute (e.g. `'open'`, `'rundll32.exe'`).
671
+ * @param args - Command arguments.
672
+ * @param env - Optional environment overrides. Defaults to `process.env`.
673
+ * @throws If the command fails to spawn (e.g. binary not found on PATH).
674
+ */
675
+ async function executeDeeplinkCommand(command, args, env) {
676
+ return new Promise((resolve, reject) => {
677
+ try {
678
+ const fullCommand = `${command} ${args.join(' ')}`;
679
+ log$1.info(`Spawning deeplink command: "${fullCommand}"`);
680
+ const childProcess = spawn(command, args, {
681
+ detached: true,
682
+ stdio: 'ignore',
683
+ env: env ?? process.env,
684
+ });
685
+ const pid = childProcess.pid;
686
+ log$1.info(`Deeplink process spawned with PID: ${pid}`);
687
+ childProcess.unref();
688
+ childProcess.on('error', (error) => {
689
+ log$1.error(`Failed to spawn deeplink process (PID ${pid}): ${error.message}`);
690
+ reject(new Error(`Failed to trigger deeplink: ${error.message}`));
691
+ });
692
+ process.nextTick(() => {
693
+ log$1.info(`Deeplink command spawned successfully: PID ${pid}`);
694
+ resolve();
695
+ });
696
+ }
697
+ catch (error) {
698
+ log$1.error(`Failed to trigger deeplink: ${error instanceof Error ? error.message : String(error)}`);
699
+ reject(new Error(`Failed to trigger deeplink: ${error instanceof Error ? error.message : String(error)}`));
700
+ }
701
+ });
702
+ }
703
+
704
+ // Log-level priority comparison utility.
705
+ //
706
+ // Extracted from packages/tauri-service/src/logForwarder.ts and
707
+ // packages/electron-service/src/logForwarder.ts. The priority ordering and
708
+ // the `shouldLog` predicate are bit-for-bit identical in both services, so
709
+ // they live here. The full `forwardLog` implementations remain in each
710
+ // service because their prefix schemes ([Tauri:Backend], [Electron:Renderer],
711
+ // [Dioxus:Backend]) and multiremote conventions diverge.
712
+ /**
713
+ * Priority ordering used by {@link shouldLog}. Higher number = higher
714
+ * priority (more severe). A log at level X is emitted iff its priority is
715
+ * ≥ the configured minimum level's priority.
716
+ */
717
+ const LOG_LEVEL_PRIORITY = {
718
+ trace: 0,
719
+ debug: 1,
720
+ info: 2,
721
+ warn: 3,
722
+ error: 4,
723
+ };
724
+ /**
725
+ * True when a log at `level` meets the `minLevel` threshold.
726
+ */
727
+ function shouldLog(level, minLevel) {
728
+ return LOG_LEVEL_PRIORITY[level] >= LOG_LEVEL_PRIORITY[minLevel];
729
+ }
730
+
731
+ // Reconciled from packages/tauri-service/src/logWriter.ts and
732
+ // packages/electron-service/src/logWriter.ts.
733
+ //
734
+ // Divergences resolved by taking the superset:
735
+ // - Tauri's LogWriterContext (workerId, specName) is preserved as optional.
736
+ // - Electron's async close() with stream-flush callback is the canonical
737
+ // signature — Tauri's previous void-returning close() callers should be
738
+ // awaited where possible (no caller currently relies on synchronous
739
+ // completion).
740
+ // - Tauri's write(message, prefixedMessage?) signature is preserved;
741
+ // Electron callers pass a single arg unchanged.
742
+ // - The service-name prefix in the formatted log line (previously hardcoded
743
+ // to 'tauri-service:service:' or 'electron-service:service:') is now a
744
+ // constructor arg, so each service tags its own lines.
745
+ //
746
+ // Backwards-compat aliases (`StandaloneLogWriter`, `getStandaloneLogWriter`,
747
+ // `isStandaloneLogWriterInitialized`) are re-exported so the existing
748
+ // electron-service imports keep working until the call sites are updated.
749
+ const log = createLogger('native-core');
750
+ /**
751
+ * Captures service logs to a timestamped file under a directory.
752
+ *
753
+ * Used in both WDIO test-runner mode and standalone mode by every native
754
+ * desktop service (Tauri, Electron, Dioxus).
755
+ */
756
+ class LogWriter {
757
+ logStream;
758
+ logDir;
759
+ logFile;
760
+ serviceName;
761
+ /**
762
+ * @param serviceName - Short service identifier emitted in each log line
763
+ * (e.g. 'tauri-service', 'electron-service'). Surfaces
764
+ * in formatted output as `<iso> INFO <serviceName>:service: <message>`.
765
+ */
766
+ constructor(serviceName) {
767
+ this.serviceName = serviceName;
768
+ }
769
+ /**
770
+ * Initialise the log writer. Creates the directory if it doesn't exist and
771
+ * opens an append-mode write stream to a timestamped file.
772
+ */
773
+ initialize(logDir, context) {
774
+ this.logDir = logDir;
775
+ if (!existsSync(this.logDir)) {
776
+ mkdirSync(this.logDir, { recursive: true });
777
+ }
778
+ const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
779
+ const contextSuffix = context?.workerId ? `-${context.workerId}` : '';
780
+ this.logFile = join(this.logDir, `wdio${contextSuffix}-${timestamp}.log`);
781
+ this.logStream = createWriteStream(this.logFile, { flags: 'a' });
782
+ }
783
+ /**
784
+ * Write a log message. If `prefixedMessage` is supplied, it's used instead
785
+ * of `message` (callers use this to embed an already-decorated line). If
786
+ * the writer hasn't been initialised, falls back to stdout.
787
+ */
788
+ write(message, prefixedMessage) {
789
+ if (!this.logStream) {
790
+ console.log(message);
791
+ return;
792
+ }
793
+ const timestamp = new Date().toISOString();
794
+ const logMessage = prefixedMessage ?? message;
795
+ const formattedMessage = `${timestamp} INFO ${this.serviceName}:service: ${logMessage}\n`;
796
+ this.logStream.write(formattedMessage);
797
+ }
798
+ /**
799
+ * Close the underlying write stream. Resolves once the stream has flushed.
800
+ */
801
+ close() {
802
+ return new Promise((resolve) => {
803
+ if (this.logStream) {
804
+ this.logStream.end(() => {
805
+ this.logStream = undefined;
806
+ resolve();
807
+ });
808
+ }
809
+ else {
810
+ resolve();
811
+ }
812
+ });
813
+ }
814
+ getLogDir() {
815
+ return this.logDir;
816
+ }
817
+ getLogFile() {
818
+ return this.logFile;
819
+ }
820
+ }
821
+ const singletons = new Map();
822
+ /**
823
+ * Get or create the singleton LogWriter for a given service name.
824
+ * Each service gets its own singleton so multi-service tests don't collide.
825
+ */
826
+ function getLogWriter(serviceName) {
827
+ let instance = singletons.get(serviceName);
828
+ if (!instance) {
829
+ instance = new LogWriter(serviceName);
830
+ singletons.set(serviceName, instance);
831
+ }
832
+ return instance;
833
+ }
834
+ /**
835
+ * True when a LogWriter for `serviceName` exists and has been initialised
836
+ * (i.e. `initialize()` has been called and a log file path is set).
837
+ */
838
+ function isLogWriterInitialized(serviceName) {
839
+ return !!singletons.get(serviceName)?.getLogFile();
840
+ }
841
+ /**
842
+ * Close the LogWriter for a given service name and release the singleton.
843
+ */
844
+ async function closeLogWriter(serviceName) {
845
+ const instance = singletons.get(serviceName);
846
+ if (instance) {
847
+ await instance.close();
848
+ singletons.delete(serviceName);
849
+ log.debug(`Log writer closed for ${serviceName}`);
850
+ }
851
+ }
852
+ // ---- Backwards-compat aliases ----
853
+ // These keep packages/electron-service/src/logWriter.ts call sites working
854
+ // during the migration. They will be removed once all callers import the
855
+ // canonical names directly.
856
+ /**
857
+ * @deprecated Use {@link LogWriter} with a `serviceName` argument.
858
+ * Bound to `'electron-service'` for back-compat with the Electron call sites
859
+ * that historically instantiated this directly.
860
+ */
861
+ class StandaloneLogWriter extends LogWriter {
862
+ constructor() {
863
+ super('electron-service');
864
+ }
865
+ }
866
+ /** @deprecated Use {@link getLogWriter}(serviceName). */
867
+ function getStandaloneLogWriter() {
868
+ let instance = singletons.get('electron-service');
869
+ if (!instance || !(instance instanceof StandaloneLogWriter)) {
870
+ // If we're replacing an initialised LogWriter, flush + close its stream
871
+ // first so the previous WriteStream isn't orphaned and leaking an fd.
872
+ if (instance?.getLogFile()) {
873
+ void instance.close().catch((err) => {
874
+ log.warn(`Failed to close orphaned LogWriter for electron-service: ${err}`);
875
+ });
876
+ }
877
+ instance = new StandaloneLogWriter();
878
+ singletons.set('electron-service', instance);
879
+ }
880
+ return instance;
881
+ }
882
+ /** @deprecated Use {@link isLogWriterInitialized}(serviceName). */
883
+ function isStandaloneLogWriterInitialized() {
884
+ return isLogWriterInitialized('electron-service');
885
+ }
886
+
887
+ export { BaseLauncher, DriverPool, DriverProcess, LOG_LEVEL_PRIORITY, LogWriter, PortManager, StandaloneLogWriter, closeLogWriter, createLogCapture, executeDeeplinkCommand, getLogWriter, getPlatformCommand, getStandaloneLogWriter, isLogWriterInitialized, isStandaloneLogWriterInitialized, shouldLog, validateDeeplinkUrl };
888
+ //# sourceMappingURL=index.js.map