@e2e-dev/electron 0.0.0 → 0.1.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.
package/README.md CHANGED
@@ -7,10 +7,16 @@ DevTools protocol and driven with trusted input, through the same
7
7
  implement. A test written against `screen`, `expect`, `app`, and `agent` runs
8
8
  on an Electron target unchanged.
9
9
 
10
+ > [!NOTE]
11
+ > **Electron support is experimental.** The `electron()` options, the `electron`
12
+ > fixture, and how the engine behaves can change in any release, including a
13
+ > patch, until it's stable. Pin `@e2e-dev/electron` to an exact version in
14
+ > `package.json`, with no `^`, and read the
15
+ > [release notes](https://github.com/e2e-inc/e2e/releases) before you upgrade.
16
+
10
17
  It is also the reference for an engine built outside this repository: it
11
18
  imports only `@e2e-dev/core/engine` and speaks the DevTools protocol itself,
12
- with no automation library and never another engine. [Engines](https://e2e.com/docs/engines) lists what
13
- building it changed in the contract.
19
+ with no automation library and never another engine.
14
20
 
15
21
  ## Install
16
22
 
@@ -59,8 +65,10 @@ test('signs in', async ({ app, screen }) => {
59
65
  - **Windows.** The agent sees them as tabs. The `electron` fixture has
60
66
  `launch` (per-test arguments and environment), `userDataDir`, `evaluate`
61
67
  (main process), `windows`, `activeWindow`, `waitForWindow`, `window`,
62
- `waitForDownload`, `onDialog`, `locator` (CSS), `keyboard`, and `mouse`. A
63
- window has `evaluate` (its page) and `reload`.
68
+ `waitForDownload`, `onDialog`, `locator` (CSS), `keyboard`, `mouse`, and
69
+ `waitForURL`. A window has `evaluate` (its page) and `reload`.
70
+ `expect(electron)` asserts the active window's URL and title, and an
71
+ element's class.
64
72
  - **Video.** The shown window's screencast, encoded to one `.webm` by ffmpeg,
65
73
  which the engine downloads on the first recording when the machine has none.
66
74
  - **Secrets.** Password fields report no value, and screenshots paint them
package/dist/.build.json CHANGED
@@ -1 +1 @@
1
- {"version":"0.0.0"}
1
+ {"version":"0.1.0"}
@@ -45,6 +45,8 @@ export declare class AppProcess {
45
45
  private readonly dialogs;
46
46
  private app;
47
47
  private exit;
48
+ /** The exit of an app a failed launch killed, which the next quit waits for. */
49
+ private exiting;
48
50
  private directory;
49
51
  private queue;
50
52
  constructor(options: ResolvedElectronOptions, windows: Windows, dialogs: DialogRouter);
@@ -63,7 +65,7 @@ export declare class AppProcess {
63
65
  /** Quits the running app, if any: a graceful quit within `graceMs` and the budget, then its process tree killed. */
64
66
  quit(budget: {
65
67
  readonly timeoutMs: number;
66
- }, graceMs: number): Promise<void>;
68
+ }, graceMs: number, exitWaitMs?: number): Promise<void>;
67
69
  /**
68
70
  * Launches the app on the attempt's user-data directory and waits for its
69
71
  * first window to load, all within one budget: `budget` when the operation
@@ -100,6 +102,13 @@ export declare class AppProcess {
100
102
  downloads(): Promise<readonly AppDownload[]>;
101
103
  /** The OS window title of a page's `BrowserWindow`, read in the main process; undefined for a view, or when the app does not answer. */
102
104
  windowTitle(page: PageTarget): Promise<string | undefined>;
105
+ /**
106
+ * The OS window title of a page's `BrowserWindow`, as `windowTitle` reads
107
+ * it, but waited for as long as the caller waits: '' only when the app
108
+ * answered with none (a view, or an app with no main-process inspector),
109
+ * never because it answered late.
110
+ */
111
+ answeredWindowTitle(page: PageTarget): Promise<string>;
103
112
  /** Closes one window, past any `beforeunload` guard, and resolves once it is gone. */
104
113
  closeWindow(page: PageTarget): Promise<void>;
105
114
  }
@@ -24,6 +24,14 @@ export const RESTART_CLOSE_MS = 5_000;
24
24
  const ANSWER_MS = 500;
25
25
  /** How long a killed app gets to exit, and let go of its files, before its data is deleted. */
26
26
  const EXIT_WAIT_MS = 2_000;
27
+ /** How long a failed launch waits for each answer it asks the app for, to say why it failed. */
28
+ const FAILURE_ANSWER_MS = 250;
29
+ /**
30
+ * What a failed launch keeps of its time to say why and end the app: the main
31
+ * process and its ready state asked, then the app killed and its exit waited
32
+ * for as long again.
33
+ */
34
+ const FAILURE_REPORT_MS = 3 * FAILURE_ANSWER_MS;
27
35
  /** How long setting the downloads directory may take of a launch's budget. */
28
36
  const DOWNLOADS_SETUP_MS = 2_000;
29
37
  /** How long reading a window's OS title may take. */
@@ -38,12 +46,16 @@ const INSPECTOR_CONNECT_MS = 5_000;
38
46
  const INSPECTOR_GRACE_MS = 500;
39
47
  /** How many of the app's last stderr lines a failed launch quotes. */
40
48
  const QUOTED_STDERR_LINES = 10;
49
+ /** The longest stderr line a launch failure quotes, in characters. */
50
+ const QUOTED_LINE_CHARS = 500;
41
51
  export class AppProcess {
42
52
  options;
43
53
  windows;
44
54
  dialogs;
45
55
  app;
46
56
  exit;
57
+ /** The exit of an app a failed launch killed, which the next quit waits for. */
58
+ exiting;
47
59
  directory;
48
60
  queue = Promise.resolve();
49
61
  constructor(options, windows, dialogs) {
@@ -75,7 +87,13 @@ export class AppProcess {
75
87
  return run;
76
88
  }
77
89
  /** Quits the running app, if any: a graceful quit within `graceMs` and the budget, then its process tree killed. */
78
- async quit(budget, graceMs) {
90
+ async quit(budget, graceMs, exitWaitMs = EXIT_WAIT_MS) {
91
+ // A failed launch waited only briefly for the app it killed: its files in the user-data directory, removed after
92
+ // this quit, are let go of first.
93
+ const exiting = this.exiting;
94
+ this.exiting = undefined;
95
+ if (exiting !== undefined)
96
+ await answerWithin(exiting, EXIT_WAIT_MS);
79
97
  const app = this.app;
80
98
  this.app = undefined;
81
99
  this.exit = undefined;
@@ -83,7 +101,9 @@ export class AppProcess {
83
101
  this.windows.clear();
84
102
  if (app === undefined)
85
103
  return;
86
- await stop(app, Math.min(budget.timeoutMs, graceMs));
104
+ await stop(app, Math.min(budget.timeoutMs, graceMs), exitWaitMs);
105
+ if (app.process.ended === undefined && exitWaitMs < EXIT_WAIT_MS)
106
+ this.exiting = app.process.exited;
87
107
  }
88
108
  /**
89
109
  * Launches the app on the attempt's user-data directory and waits for its
@@ -95,9 +115,11 @@ export class AppProcess {
95
115
  // rather than the operation timing out; each phase gets what the ones before it left.
96
116
  // An operation cancelled, or out of time after the quit before it, starts no app.
97
117
  budget.check();
98
- const timeout = Math.max(1, budget.waits.remaining());
118
+ // A failed launch then asks the app why and quits it: that is left out of the launch's own time, up to half of it.
119
+ // With under 1.5 s left, half is less than the report can take, so a very short launch can still end in TEST_TIMEOUT.
120
+ const available = budget.waits.remaining();
121
+ const timeout = Math.max(1, available - Math.min(FAILURE_REPORT_MS, available / 2));
99
122
  const deadline = new Deadline(timeout);
100
- const left = () => Math.max(1, deadline.remaining());
101
123
  let app;
102
124
  let opened = false;
103
125
  try {
@@ -119,7 +141,10 @@ export class AppProcess {
119
141
  const window = () => raceAbort(() => Promise.race([loaded(open, deadline, operation.signal), quitEarly]), operation.signal, 'waiting for the first window to load');
120
142
  let first = await window();
121
143
  opened = true;
122
- // Still inside the launch: an app that quits here, or a caller that stopped waiting, fails it.
144
+ // Still inside the launch: an app that quits here, or a caller that stopped waiting, fails it. A window that loaded
145
+ // as the wait for one ran out still gets the operation's time to connect its main process and place its downloads:
146
+ // with none left, an app with an inspector would be taken for one with none, and save downloads where it likes.
147
+ const left = () => Math.max(1, budget.waits.remaining());
123
148
  const reported = await raceAbort(() => Promise.race([this.setUp(app, setup, left), quitEarly]), operation.signal, 'setting up the app');
124
149
  // A splash screen can close while the app is set up: the launch ends on a window that is there.
125
150
  while (first.isClosed())
@@ -133,11 +158,13 @@ export class AppProcess {
133
158
  catch (cause) {
134
159
  // Read before the engine's own quit, which ends the process too.
135
160
  const exited = app.process.ended;
136
- const main = exited === undefined ? await answerWithin(app.main, ANSWER_MS) : undefined;
161
+ const main = exited === undefined ? await answerWithin(app.main, FAILURE_ANSWER_MS) : undefined;
137
162
  // Electron can stall before its ready event on a loaded machine; say so rather than blame the app's window.
138
- const ready = main === undefined ? undefined : await answerWithin(main.evaluate(({ app: electronApp }) => electronApp.isReady(), undefined), ANSWER_MS);
163
+ const ready = main === undefined ? undefined : await answerWithin(main.evaluate(({ app: electronApp }) => electronApp.isReady(), undefined), FAILURE_ANSWER_MS);
139
164
  const stuck = [...app.pages.values()].filter((page) => !this.windows.has(page)).length;
140
- await this.quit({ timeoutMs: DISCARD_CLOSE_MS }, DISCARD_CLOSE_MS);
165
+ // Killed, with no graceful quit and only a moment's wait for its exit: an app that failed to launch has nothing to
166
+ // save, and the time is the report's. The next quit waits for the rest.
167
+ await this.quit({ timeoutMs: 0 }, 0, FAILURE_ANSWER_MS);
141
168
  if (cause instanceof EngineError)
142
169
  throw cause;
143
170
  throw launchError(setup, app.process, { exited, ready, stuck, timeout, opened }, cause);
@@ -371,12 +398,24 @@ export class AppProcess {
371
398
  const main = this.app === undefined ? undefined : await answerWithin(this.app.main, TITLE_MS);
372
399
  if (main === undefined)
373
400
  return undefined;
374
- const title = await answerWithin(main.evaluate(({ BrowserWindow, webContents }, targetId) => {
375
- const contents = webContents.fromDevToolsTargetId(targetId);
376
- return contents === undefined ? undefined : BrowserWindow.fromWebContents(contents)?.getTitle();
377
- }, page.targetId), TITLE_MS);
401
+ const title = await answerWithin(main.evaluate(osWindowTitle, page.targetId), TITLE_MS);
378
402
  return title ?? undefined;
379
403
  }
404
+ /**
405
+ * The OS window title of a page's `BrowserWindow`, as `windowTitle` reads
406
+ * it, but waited for as long as the caller waits: '' only when the app
407
+ * answered with none (a view, or an app with no main-process inspector),
408
+ * never because it answered late.
409
+ */
410
+ async answeredWindowTitle(page) {
411
+ const app = this.app;
412
+ if (app === undefined)
413
+ throw this.notRunning();
414
+ const main = await app.main;
415
+ if (main === undefined)
416
+ return '';
417
+ return (await main.evaluate(osWindowTitle, page.targetId)) ?? '';
418
+ }
380
419
  /** Closes one window, past any `beforeunload` guard, and resolves once it is gone. */
381
420
  async closeWindow(page) {
382
421
  const app = this.app;
@@ -399,12 +438,30 @@ export class AppProcess {
399
438
  await gone;
400
439
  }
401
440
  }
402
- const NO_INSPECTOR = 'the app\'s main process opened no inspector, so electron.evaluate cannot run in it and windows are known by their document titles only: a packaged app built with the EnableNodeCliInspectArguments fuse off ignores --inspect';
441
+ /**
442
+ * A stderr line as a failed launch quotes it: whole up to `QUOTED_LINE_CHARS`
443
+ * characters, and only its length past that. Any cut, at white space too,
444
+ * could keep the start of a secret, which the run's redaction, matching whole
445
+ * values only, would let through.
446
+ */
447
+ function quotedLine(line) {
448
+ return line.length <= QUOTED_LINE_CHARS ? line : `(a line of ${line.length} characters)`;
449
+ }
450
+ const NO_INSPECTOR = 'the app\'s main process opened no inspector, so electron.evaluate and electron.waitForDownload cannot run in it and windows are known by their document titles only: a packaged app built with the EnableNodeCliInspectArguments fuse off ignores --inspect';
403
451
  /** Ends an app: a graceful quit within `graceMs`, then its process tree killed and waited for. */
404
- async function stop(app, graceMs) {
452
+ async function stop(app, graceMs, exitWaitMs) {
405
453
  const { process } = app;
406
454
  if (process.ended !== undefined)
407
455
  return;
456
+ if (graceMs > 0 && (await quitGracefully(app, graceMs)))
457
+ return;
458
+ process.killNow();
459
+ // Its files in the user-data directory are deleted next: wait, briefly, until it has let go of them.
460
+ await answerWithin(process.exited, exitWaitMs);
461
+ }
462
+ /** Asks the app to quit, and whether it exited within `graceMs`. */
463
+ async function quitGracefully(app, graceMs) {
464
+ const { process } = app;
408
465
  const main = await answerWithin(app.main, ANSWER_MS);
409
466
  if (main === undefined) {
410
467
  void process.browser.root.send('Browser.close').catch(() => undefined);
@@ -418,11 +475,7 @@ async function stop(app, graceMs) {
418
475
  }, undefined), Math.min(graceMs, ANSWER_MS));
419
476
  void main.evaluate(({ app: electronApp }) => electronApp.quit(), undefined).catch(() => undefined);
420
477
  }
421
- if ((await answerWithin(process.exited, graceMs)) !== undefined)
422
- return;
423
- process.killNow();
424
- // Its files in the user-data directory are deleted next: wait, briefly, until it has let go of them.
425
- await answerWithin(process.exited, EXIT_WAIT_MS);
478
+ return (await answerWithin(process.exited, graceMs)) !== undefined;
426
479
  }
427
480
  /** The first of the app's open windows, in the order they opened, to have a parsed document: a window is read from then on. */
428
481
  async function loaded(pages, deadline, signal) {
@@ -479,7 +532,8 @@ function launchError(setup, process, seen, cause) {
479
532
  }
480
533
  /** What the app wrote to stderr, for a failure's message; empty when it wrote nothing. */
481
534
  function stderrQuote(process) {
482
- const lines = process.stderrTail(QUOTED_STDERR_LINES);
535
+ // A longer line is left out: a minified stack or a data: URL in one would fill the report.
536
+ const lines = process.stderrTail(QUOTED_STDERR_LINES).map(quotedLine);
483
537
  return lines.length === 0 ? '' : `. The app wrote to stderr:\n${lines.join('\n')}`;
484
538
  }
485
539
  /** Electron has no headless mode: on a machine with no display it exits at once, and its own message is easy to miss. */
@@ -494,6 +548,11 @@ function describeExit({ code, signal }) {
494
548
  return signal !== null ? `on ${signal}` : code !== null ? `with exit code ${code}` : '';
495
549
  }
496
550
  /** The Electron and Chromium versions of the running app, for the report's environment. */
551
+ /** Runs in the main process: the title of the `BrowserWindow` that shows a DevTools target, undefined for a view. */
552
+ function osWindowTitle({ BrowserWindow, webContents }, targetId) {
553
+ const contents = webContents.fromDevToolsTargetId(targetId);
554
+ return contents === undefined ? undefined : BrowserWindow.fromWebContents(contents)?.getTitle();
555
+ }
497
556
  async function readVersions(app, main) {
498
557
  if (main !== undefined)
499
558
  return await main.evaluate(() => ({ electron: process.versions.electron ?? '', chromium: process.versions.chrome ?? '' }), undefined);
@@ -515,11 +574,15 @@ async function placeDownloads(main, directory, withinMs) {
515
574
  electronApp.setPath('downloads', downloads);
516
575
  // Compared without case: two names that differ only in case are one file on macOS and Windows.
517
576
  const taken = new Set(earlier.map((name) => name.toLowerCase()));
577
+ // A file the app wrote there itself since launch is taken too; an Electron before getBuiltinModule knows only the list.
578
+ const files = process.getBuiltinModule?.('node:fs');
579
+ // A file's folder, its separators either way round: an app on Windows may write either.
580
+ const folderOf = (file) => file.replace(/[\\/][^\\/]*$/, '').replaceAll('\\', '/').toLowerCase();
518
581
  const unique = (name) => {
519
582
  const dot = name.lastIndexOf('.');
520
583
  const [stem, extension] = dot > 0 ? [name.slice(0, dot), name.slice(dot)] : [name, ''];
521
584
  let candidate = name;
522
- for (let count = 1; taken.has(candidate.toLowerCase()); count += 1)
585
+ for (let count = 1; taken.has(candidate.toLowerCase()) || files?.existsSync(`${downloads}/${candidate}`) === true; count += 1)
523
586
  candidate = `${stem} (${count})${extension}`;
524
587
  taken.add(candidate.toLowerCase());
525
588
  return candidate;
@@ -532,8 +595,12 @@ async function placeDownloads(main, directory, withinMs) {
532
595
  return;
533
596
  placed.add(target);
534
597
  target.on('will-download', (_event, item) => {
535
- if (item.getSavePath() === '')
598
+ const chosen = item.getSavePath();
599
+ if (chosen === '')
536
600
  item.setSavePath(`${downloads}/${unique(item.getFilename())}`);
601
+ // A path the app chose in the downloads folder is taken, so a later download is not given it.
602
+ else if (folderOf(chosen) === folderOf(`${downloads}/-`))
603
+ taken.add((chosen.split(/[\\/]/).pop() ?? '').toLowerCase());
537
604
  // What `electron.waitForDownload` reads: each download the app started, and how it ended.
538
605
  const entry = { filename: item.getFilename(), path: item.getSavePath(), state: 'progressing' };
539
606
  const log = (globalThis.e2eDownloads ??= []);
package/dist/dialogs.d.ts CHANGED
@@ -23,7 +23,9 @@ export interface OpenDialog {
23
23
  export declare class DialogRouter {
24
24
  private registrations;
25
25
  private pending;
26
- private readonly running;
26
+ private running;
27
+ /** Bumped by `reset`: a handler of an earlier attempt that is still running reports into none of the next one's state. */
28
+ private generation;
27
29
  /** Registers a handler, the newest winning, and returns what removes it. */
28
30
  add(handler: DialogHandler): () => void;
29
31
  /** Forgets the attempt's handlers and whatever it left unreported. */
package/dist/dialogs.js CHANGED
@@ -12,6 +12,8 @@ export class DialogRouter {
12
12
  registrations = [];
13
13
  pending;
14
14
  running = new Set();
15
+ /** Bumped by `reset`: a handler of an earlier attempt that is still running reports into none of the next one's state. */
16
+ generation = 0;
15
17
  /** Registers a handler, the newest winning, and returns what removes it. */
16
18
  add(handler) {
17
19
  const registration = { handler };
@@ -24,6 +26,8 @@ export class DialogRouter {
24
26
  reset() {
25
27
  this.registrations = [];
26
28
  this.pending = undefined;
29
+ this.running = new Set();
30
+ this.generation += 1;
27
31
  }
28
32
  /** The failure a dialog left for the next step, once. */
29
33
  take() {
@@ -38,15 +42,18 @@ export class DialogRouter {
38
42
  /** Answers one dialog through the newest handler. */
39
43
  dispatch(dialog) {
40
44
  const work = this.route(dialog).catch(() => undefined);
41
- this.running.add(work);
42
- void work.then(() => this.running.delete(work));
45
+ const { running } = this;
46
+ running.add(work);
47
+ void work.then(() => running.delete(work));
43
48
  }
44
49
  async route(dialog) {
45
50
  const handler = this.registrations.at(-1)?.handler;
46
51
  const { type, message } = dialog;
52
+ const { generation } = this;
47
53
  // The first failure is the one to report: the app's later dialogs follow from it.
48
54
  const fail = (error) => {
49
- this.pending ??= error;
55
+ if (this.generation === generation)
56
+ this.pending ??= error;
50
57
  };
51
58
  if (handler === undefined) {
52
59
  fail(new EngineError('INVALID_STATE', `unhandled ${type} dialog: ${message}; answer it with electron.onDialog('accept'), 'dismiss', or a handler`, { retryable: false }));
package/dist/electron.js CHANGED
@@ -4,6 +4,7 @@
4
4
  * `electron.<method>` step bounded by the action timeout.
5
5
  */
6
6
  import { ConfigurationError, isSecret, stepTimeout, TestError } from '@e2e-dev/core/engine';
7
+ import { EXPECTATION_OPERATIONS, WindowConditions } from './expectation.js';
7
8
  import { typeKeys } from './actions.js';
8
9
  import { hasKey } from './cdp/input.js';
9
10
  import { unsupported } from './errors.js';
@@ -56,7 +57,9 @@ export function createElectronFixture(surface, context) {
56
57
  throw unsupported(`the keyboard has no key ${JSON.stringify(name)}: name a key such as "Shift" or "Enter", or a character of a US keyboard`);
57
58
  await surface.input(`keyboard.${direction}`, (window, budget) => budget.send(() => window.page.keyboard[direction](name)), context.operation());
58
59
  };
60
+ const conditions = new WindowConditions(surface, context);
59
61
  const electron = {
62
+ waitForURL: (url, options) => conditions.waitForURL(url, options),
60
63
  get userDataDir() {
61
64
  return surface.dataDirectory();
62
65
  },
@@ -146,7 +149,8 @@ export function createElectronFixture(surface, context) {
146
149
  },
147
150
  };
148
151
  const input = { kind: 'resource' };
149
- return context.fixture('electron', electron, {
152
+ return context.fixture('electron', context.expectable(electron, () => context.fixture('expect', conditions.expectation(), EXPECTATION_OPERATIONS)), {
153
+ waitForURL: { kind: 'resource', timeout: false, verifies: true, label: (url) => String(url) },
150
154
  launch: { kind: 'resource', timeout: false },
151
155
  keyboard: {
152
156
  press: { ...input, label: (key) => String(key) },
@@ -10,4 +10,4 @@ export type { ElectronEngine } from './engine.ts';
10
10
  export { electron as default } from './engine.ts';
11
11
  export type { ElectronOptions } from './options.ts';
12
12
  export type { Dialog, DialogHandler } from './dialogs.ts';
13
- export type { Electron, ElectronFixtures, ElectronKeyboard, ElectronLaunchOptions, ElectronMainModule, ElectronMouse, ElectronWindow, WindowMatcher } from './fixtures.ts';
13
+ export type { Electron, ElectronExpectation, ElectronFixtures, ElectronKeyboard, ElectronLaunchOptions, ElectronMainModule, ElectronMouse, ElectronWindow, WindowMatcher } from './fixtures.ts';
package/dist/errors.js CHANGED
@@ -1,5 +1,5 @@
1
1
  /** The engine errors this surface raises, and the translation of a protocol failure into them. */
2
- import { ConfigurationError, EngineError, TestError } from '@e2e-dev/core/engine';
2
+ import { ConfigurationError, EngineError, InfrastructureError, TestError } from '@e2e-dev/core/engine';
3
3
  export function stale(message, cause) {
4
4
  return new EngineError('NODE_STALE', message, { retryable: true, ...(cause === undefined ? {} : { cause }) });
5
5
  }
@@ -29,8 +29,9 @@ export function closedWindow(cause) {
29
29
  * is `ACTION_MAY_HAVE_COMMITTED`, never something the harness retries.
30
30
  */
31
31
  export function translate(cause, label, committed) {
32
- // A refusal by policy (a screenshot it cannot mask) or of the test's own input is the harness's to report as it is.
33
- if (cause instanceof ConfigurationError || cause instanceof TestError)
32
+ // A refusal by policy (a screenshot it cannot mask), of the test's own input, or of the machine (a download of ffmpeg
33
+ // that failed) is the harness's to report as it is.
34
+ if (cause instanceof ConfigurationError || cause instanceof TestError || cause instanceof InfrastructureError)
34
35
  return cause;
35
36
  if (cause instanceof EngineError) {
36
37
  if (committed && (cause.code === 'OPERATION_TIMEOUT' || cause.code === 'CANCELLED' || cause.retryable)) {
@@ -6,14 +6,48 @@
6
6
  * before the run's clock starts, and a worker only checks it is there.
7
7
  */
8
8
  import { spawn } from 'node:child_process';
9
- import { accessSync, closeSync, constants, existsSync, openSync, readdirSync, readFileSync, readSync, statSync } from 'node:fs';
9
+ import { accessSync, closeSync, constants, existsSync, openSync, readdirSync, readFileSync, readSync, realpathSync, statSync } from 'node:fs';
10
10
  import { createRequire } from 'node:module';
11
11
  import path from 'node:path';
12
+ import { fileURLToPath } from 'node:url';
12
13
  import { ConfigurationError, InfrastructureError } from '@e2e-dev/core/engine';
14
+ import { INCOMPLETE_INSTALL } from './install-lock.js';
13
15
  /** How much of a failed download's output its error quotes, in characters. */
14
16
  const INSTALL_OUTPUT_TAIL = 2000;
17
+ /** What the package's `path.txt` names, empty when there is none: a download removes one left by an earlier download, and writes its own last. */
18
+ function namedBinary(directory) {
19
+ try {
20
+ return readFileSync(path.join(directory, 'path.txt'), 'utf8').trim();
21
+ }
22
+ catch (cause) {
23
+ if (cause.code === 'ENOENT')
24
+ return '';
25
+ throw cause;
26
+ }
27
+ }
28
+ /** Where a dist directory keeps the binary on `platform`: what the package's `install.js` writes to `path.txt`. */
29
+ function platformBinary(platform) {
30
+ if (platform === 'darwin')
31
+ return path.join('Electron.app', 'Contents', 'MacOS', 'Electron');
32
+ return platform === 'win32' ? 'electron.exe' : 'electron';
33
+ }
34
+ /** Whether this override points back into the package distribution an install has started writing: the directory is that one, or the binary found in it is really a file inside it. */
35
+ function usesIncompleteDistribution(directory, override, binary) {
36
+ if (!existsSync(path.join(directory, INCOMPLETE_INSTALL)))
37
+ return false;
38
+ const dist = path.join(directory, 'dist');
39
+ if (path.resolve(override) === dist)
40
+ return true;
41
+ try {
42
+ const written = realpathSync(dist);
43
+ return realpathSync(override) === written || (binary !== undefined && realpathSync(binary).startsWith(written + path.sep));
44
+ }
45
+ catch {
46
+ return false;
47
+ }
48
+ }
15
49
  /** The project's `electron` package, or undefined when the project has none. */
16
- function electronPackage(projectRoot, env) {
50
+ function electronPackage(projectRoot, env, platform) {
17
51
  let manifest;
18
52
  try {
19
53
  manifest = createRequire(path.join(projectRoot, 'package.json')).resolve('electron/package.json');
@@ -24,13 +58,19 @@ function electronPackage(projectRoot, env) {
24
58
  const directory = path.dirname(manifest);
25
59
  const parsed = JSON.parse(readFileSync(manifest, 'utf8'));
26
60
  const version = typeof parsed === 'object' && parsed !== null && 'version' in parsed && typeof parsed.version === 'string' ? parsed.version : 'unknown';
27
- const pathFile = path.join(directory, 'path.txt');
28
- const relative = existsSync(pathFile) ? readFileSync(pathFile, 'utf8').trim() : '';
29
- // Electron's own index.js takes the binary from ELECTRON_OVERRIDE_DIST_PATH when it is set (a build of your own, Nix).
61
+ const relative = namedBinary(directory);
62
+ // Electron's own index.js takes the binary from ELECTRON_OVERRIDE_DIST_PATH when it is set (a build of your own, Nix), under the name in `path.txt`, else `electron`. A download removes `path.txt` while it writes, so with none the platform's own name is looked for too.
30
63
  const override = env['ELECTRON_OVERRIDE_DIST_PATH'];
31
- const overridden = override !== undefined && override !== '';
32
- const binary = overridden ? path.join(override, relative === '' ? 'electron' : relative) : relative === '' ? undefined : path.join(directory, 'dist', relative);
33
- return { directory, binary: binary !== undefined && existsSync(binary) ? binary : undefined, version, ...(overridden && binary !== undefined ? { override: binary } : {}) };
64
+ if (override) {
65
+ const names = relative === '' ? ['electron', platformBinary(platform)] : [relative];
66
+ const binary = names.map((name) => path.join(override, name)).find((file) => existsSync(file));
67
+ // Check after looking for the binary: extraction can start between reading path.txt and finding the new file.
68
+ if (!usesIncompleteDistribution(directory, override, binary))
69
+ return { directory, binary, version, override: binary ?? path.join(override, relative || 'electron') };
70
+ }
71
+ const binary = relative === '' ? undefined : path.join(directory, 'dist', relative);
72
+ const ready = binary !== undefined && existsSync(binary) && namedBinary(directory) === relative;
73
+ return { directory, binary: ready ? binary : undefined, version };
34
74
  }
35
75
  /**
36
76
  * Whether a path names a regular file this process may execute: a directory
@@ -136,7 +176,7 @@ function locateExecutable(projectRoot, executablePath, env, platform) {
136
176
  }
137
177
  return { kind: 'named', file: resolved };
138
178
  }
139
- const installed = electronPackage(projectRoot, env);
179
+ const installed = electronPackage(projectRoot, env, platform);
140
180
  if (installed === undefined) {
141
181
  return {
142
182
  kind: 'misconfigured',
@@ -176,11 +216,20 @@ export async function ensureElectronBinary(projectRoot, executablePath, env, log
176
216
  if (found.kind !== 'undownloaded')
177
217
  return;
178
218
  await download(found.package, env, log, signal);
179
- if (electronPackage(projectRoot, env)?.binary === undefined) {
219
+ if (electronPackage(projectRoot, env, process.platform)?.binary === undefined) {
180
220
  throw new InfrastructureError('ELECTRON_INSTALL_FAILED', `electron ${found.package.version}'s install.js finished, but its binary is still missing at ${found.package.directory}`);
181
221
  }
182
222
  }
183
- /** Runs the package's own `install.js` (what its first `require` would run), its output sent to `log`. */
223
+ /** The engine's script that runs `install.js` under the package's install lock: `.js` in a build, `.ts` from source. */
224
+ function installProcess() {
225
+ const built = fileURLToPath(new URL('./install-process.js', import.meta.url));
226
+ return existsSync(built) ? built : fileURLToPath(new URL('./install-process.ts', import.meta.url));
227
+ }
228
+ /**
229
+ * Runs the package's own `install.js` (what its first `require` would run)
230
+ * in a process that holds the package's install lock, its output sent to
231
+ * `log`.
232
+ */
184
233
  async function download(installed, env, log, signal) {
185
234
  const script = path.join(installed.directory, 'install.js');
186
235
  if (!existsSync(script)) {
@@ -188,7 +237,8 @@ async function download(installed, env, log, signal) {
188
237
  }
189
238
  log(`downloading the Electron ${installed.version} binary`);
190
239
  const failure = await new Promise((resolve) => {
191
- const child = spawn(process.execPath, [script], { cwd: installed.directory, env, stdio: ['ignore', 'pipe', 'pipe'], signal });
240
+ // Started without ELECTRON_OVERRIDE_DIST_PATH: after extraction `install.js` would look for an `electron.d.ts` in the override directory and move it into the package.
241
+ const child = spawn(process.execPath, [installProcess(), script], { cwd: installed.directory, env: { ...env, ELECTRON_OVERRIDE_DIST_PATH: undefined }, stdio: ['ignore', 'pipe', 'pipe'], signal });
192
242
  let tail = '';
193
243
  const read = (chunk) => {
194
244
  const text = chunk.toString('utf8');
@@ -200,7 +250,7 @@ async function download(installed, env, log, signal) {
200
250
  child.stdout.on('data', read);
201
251
  child.stderr.on('data', read);
202
252
  child.on('error', (cause) => resolve(cause.message));
203
- child.on('close', (code) => resolve(code === 0 ? undefined : `install.js exited with ${code}: ${tail.trim()}`));
253
+ child.on('close', (code, killSignal) => resolve(code === 0 ? undefined : `install.js ${killSignal === null ? `exited with ${String(code)}` : `was killed (${killSignal})`}${tail.trim() === '' ? '' : `: ${tail.trim()}`}`));
204
254
  });
205
255
  if (failure !== undefined)
206
256
  throw new InfrastructureError('ELECTRON_INSTALL_FAILED', `downloading the Electron ${installed.version} binary failed: ${failure}`);
@@ -234,7 +284,8 @@ export function appPathProblem(projectRoot, appPath) {
234
284
  let main = 'index.js';
235
285
  if (existsSync(manifest)) {
236
286
  try {
237
- const parsed = JSON.parse(readFileSync(manifest, 'utf8'));
287
+ // A byte order mark at the start, which an editor on Windows may write, Electron reads past, as Node does.
288
+ const parsed = JSON.parse(readFileSync(manifest, 'utf8').replace(/^\uFEFF/, ''));
238
289
  if (typeof parsed === 'object' && parsed !== null && 'main' in parsed && typeof parsed.main === 'string' && parsed.main !== '')
239
290
  main = parsed.main;
240
291
  }
@@ -0,0 +1,30 @@
1
+ /**
2
+ * `expect(electron)` and `electron.waitForURL`: conditions of the active
3
+ * window polled against the assertion timeout, as `expect(browser)` polls a
4
+ * tab's on the web. Each failure reports the last read.
5
+ */
6
+ import { type EngineFixtureContext, type FixtureOperations } from '@e2e-dev/core/engine';
7
+ import type { ElectronExpectation } from './fixtures.ts';
8
+ import type { ElectronSurface } from './surface.ts';
9
+ export declare class WindowConditions {
10
+ private readonly surface;
11
+ private readonly context;
12
+ constructor(surface: ElectronSurface, context: EngineFixtureContext);
13
+ /** Polls `read` until it matches, or fails with the last read once the assertion timeout (or `timeout`) is over. */
14
+ private poll;
15
+ /**
16
+ * Whether a failed read is one a wait goes on through: the document went
17
+ * away under it (a navigation), or the window is closed or not there yet
18
+ * while the app still runs. A read that hangs is the poll's own to judge.
19
+ */
20
+ private passing;
21
+ private url;
22
+ /** `electron.waitForURL()`: the poll `expect(electron).toHaveURL` runs. */
23
+ waitForURL(expected: string | RegExp, options: {
24
+ readonly timeout?: number;
25
+ } | undefined): Promise<void>;
26
+ /** The `expect(electron)` matchers, or their negations. */
27
+ expectation(negated?: boolean): ElectronExpectation;
28
+ }
29
+ /** How the harness records each matcher: an assertion that owns its deadline. */
30
+ export declare const EXPECTATION_OPERATIONS: FixtureOperations<ElectronExpectation>;