@e2e-dev/electron 0.0.0-stage → 0.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (75) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +5 -0
  3. package/README.md +91 -2
  4. package/dist/.build.json +1 -0
  5. package/dist/actionability.d.ts +41 -0
  6. package/dist/actionability.js +121 -0
  7. package/dist/actions.d.ts +52 -0
  8. package/dist/actions.js +418 -0
  9. package/dist/app-process.d.ts +114 -0
  10. package/dist/app-process.js +610 -0
  11. package/dist/budget.d.ts +33 -0
  12. package/dist/budget.js +64 -0
  13. package/dist/capture.d.ts +21 -0
  14. package/dist/capture.js +137 -0
  15. package/dist/cdp/connection.d.ts +68 -0
  16. package/dist/cdp/connection.js +232 -0
  17. package/dist/cdp/input.d.ts +67 -0
  18. package/dist/cdp/input.js +195 -0
  19. package/dist/cdp/keys.d.ts +21 -0
  20. package/dist/cdp/keys.js +114 -0
  21. package/dist/console-text.d.ts +4 -0
  22. package/dist/console-text.js +27 -0
  23. package/dist/devtools.d.ts +36 -0
  24. package/dist/devtools.js +111 -0
  25. package/dist/dialogs.d.ts +38 -0
  26. package/dist/dialogs.js +81 -0
  27. package/dist/electron.d.ts +9 -0
  28. package/dist/electron.js +174 -0
  29. package/dist/engine-entry.d.ts +13 -0
  30. package/dist/engine-entry.js +9 -0
  31. package/dist/engine.d.ts +27 -0
  32. package/dist/engine.js +98 -0
  33. package/dist/errors.d.ts +17 -0
  34. package/dist/errors.js +54 -0
  35. package/dist/evaluate.d.ts +40 -0
  36. package/dist/evaluate.js +115 -0
  37. package/dist/executable.d.ts +29 -0
  38. package/dist/executable.js +249 -0
  39. package/dist/ffmpeg.d.ts +12 -0
  40. package/dist/ffmpeg.js +100 -0
  41. package/dist/fields.d.ts +93 -0
  42. package/dist/fields.js +254 -0
  43. package/dist/file-bound.d.ts +31 -0
  44. package/dist/file-bound.js +104 -0
  45. package/dist/fixtures.d.ts +168 -0
  46. package/dist/fixtures.js +6 -0
  47. package/dist/in-page/masks.d.ts +25 -0
  48. package/dist/in-page/masks.js +140 -0
  49. package/dist/in-page/node-ops.d.ts +96 -0
  50. package/dist/in-page/node-ops.js +406 -0
  51. package/dist/index.d.ts +18 -0
  52. package/dist/index.js +18 -0
  53. package/dist/launcher.d.ts +45 -0
  54. package/dist/launcher.js +167 -0
  55. package/dist/locate.d.ts +46 -0
  56. package/dist/locate.js +103 -0
  57. package/dist/main-process.d.ts +25 -0
  58. package/dist/main-process.js +60 -0
  59. package/dist/options.d.ts +65 -0
  60. package/dist/options.js +120 -0
  61. package/dist/page.d.ts +100 -0
  62. package/dist/page.js +229 -0
  63. package/dist/runner-test.d.ts +15 -0
  64. package/dist/runner-test.js +45 -0
  65. package/dist/snapshot.d.ts +143 -0
  66. package/dist/snapshot.js +260 -0
  67. package/dist/surface.d.ts +158 -0
  68. package/dist/surface.js +602 -0
  69. package/dist/tree.d.ts +51 -0
  70. package/dist/tree.js +406 -0
  71. package/dist/video.d.ts +42 -0
  72. package/dist/video.js +253 -0
  73. package/dist/windows.d.ts +81 -0
  74. package/dist/windows.js +200 -0
  75. package/package.json +72 -3
package/dist/index.js ADDED
@@ -0,0 +1,18 @@
1
+ /**
2
+ * `@e2e-dev/electron` public surface: the `electron()` engine factory, the
3
+ * `electron` fixture types, and `test`, `describe`, and the hooks typed with
4
+ * that fixture. `expect`, `credentials`, and `secrets` still come from
5
+ * `e2e`. Without `e2e` installed, `electron()` still loads and `test` throws
6
+ * when used.
7
+ */
8
+ import { runnerTest } from './runner-test.js';
9
+ export * from './engine-entry.js';
10
+ /** The engine factory as the default export: what `e2e mcp` calls when `open_session` names this package as its `engine`. */
11
+ export { default } from './engine-entry.js';
12
+ /**
13
+ * `test` typed with this engine's contributed `electron` fixture. The same
14
+ * runtime `test` as `e2e`'s; only the fixture types differ.
15
+ */
16
+ export const test = runnerTest().extend();
17
+ /** `describe` and the hooks, the same functions as `test.describe` and `test.beforeEach`, typed with the `electron` fixture. */
18
+ export const { describe, beforeEach, afterEach, beforeAll, afterAll } = test;
@@ -0,0 +1,45 @@
1
+ /**
2
+ * Starts the Electron binary and holds its process: the DevTools pipe to its
3
+ * windows, the address of its main process's inspector once it prints one,
4
+ * what it wrote to stderr, and the kill that takes its whole process tree.
5
+ */
6
+ import { Connection } from './cdp/connection.ts';
7
+ export interface LaunchCommand {
8
+ readonly executable: string;
9
+ readonly args: readonly string[];
10
+ readonly cwd: string;
11
+ readonly env: Readonly<Record<string, string>>;
12
+ }
13
+ /** How the app's process ended. */
14
+ export interface ProcessExit {
15
+ readonly code: number | null;
16
+ readonly signal: NodeJS.Signals | null;
17
+ }
18
+ /** The switches the engine starts every app with, before the caller's own. */
19
+ export declare function engineArguments(args: readonly string[], platform?: NodeJS.Platform): string[];
20
+ export declare class ElectronProcess {
21
+ /** The DevTools protocol of the app's browser process, over the pipe. */
22
+ readonly browser: Connection;
23
+ /** Resolves when the process ends, however it does; a binary that cannot be started ends at once. */
24
+ readonly exited: Promise<ProcessExit>;
25
+ /** The address of the main process's inspector, once it printed one; never settles for an app that opens none. */
26
+ readonly inspector: Promise<string>;
27
+ /** Why the binary could not be started at all. */
28
+ spawnError: Error | undefined;
29
+ /** Whether the main process printed its inspector's address. */
30
+ inspectorSeen: boolean;
31
+ private exit;
32
+ private readonly stderr;
33
+ private readonly child;
34
+ private readonly waitingHandlers;
35
+ constructor(command: LaunchCommand);
36
+ /** How the process ended, or undefined while it runs. */
37
+ get ended(): ProcessExit | undefined;
38
+ /** The last lines the app wrote to stderr, each once, in order. */
39
+ stderrTail(count: number): string[];
40
+ /** Runs `handler` when the process is done and waits only for the inspector's client to let go. */
41
+ onWaitingForInspector(handler: () => void): void;
42
+ /** Kills the process and every process it started, without waiting for them. */
43
+ killNow(): void;
44
+ private killGroup;
45
+ }
@@ -0,0 +1,167 @@
1
+ /**
2
+ * Starts the Electron binary and holds its process: the DevTools pipe to its
3
+ * windows, the address of its main process's inspector once it prints one,
4
+ * what it wrote to stderr, and the kill that takes its whole process tree.
5
+ */
6
+ import { spawn, spawnSync } from 'node:child_process';
7
+ import { Connection, pipeTransport } from './cdp/connection.js';
8
+ /** How many of the app's last stderr lines a failed launch can quote. */
9
+ const STDERR_LINES = 50;
10
+ /** How long Windows' taskkill gets to end the process tree before the process alone is killed. */
11
+ const TASKKILL_MS = 5_000;
12
+ /** How long a process that exited gets to hand over the rest of its stderr. */
13
+ const STDERR_DRAIN_MS = 500;
14
+ const INSPECTOR_LISTENING = /^Debugger listening on (ws:\/\/\S+)/;
15
+ /** What the Node inspector prints about itself, which is not the app's output. */
16
+ const INSPECTOR_NOISE = /^(Debugger listening on |For help, see: https:\/\/nodejs\.org\/|Debugger attached\.|Waiting for the debugger to disconnect)/;
17
+ /** Printed when the process is done and only the inspector's client keeps it alive. */
18
+ const INSPECTOR_WAITING = /Waiting for the debugger to disconnect/;
19
+ /** The switches the engine starts every app with, before the caller's own. */
20
+ export function engineArguments(args, platform = process.platform) {
21
+ return [
22
+ // The main process's inspector, on a port of its own choosing, for electron.evaluate.
23
+ '--inspect=0',
24
+ // The windows' DevTools protocol on a pipe: no port, so no other process can connect.
25
+ '--remote-debugging-pipe',
26
+ // Captures in sRGB whatever the display: a wide-gamut screen would otherwise give other pixels for the same page.
27
+ ...(args.some((argument) => argument.startsWith('--force-color-profile')) ? [] : ['--force-color-profile=srgb']),
28
+ // A window another one covers, or the app keeps hidden, still draws and runs its timers: Chromium would
29
+ // otherwise stop both, and a capture of such a window never returns. Parallel workers cover each other's windows.
30
+ '--disable-backgrounding-occluded-windows',
31
+ '--disable-renderer-backgrounding',
32
+ '--disable-background-timer-throttling',
33
+ ...(args.some((argument) => argument.startsWith('--disable-features')) ? [] : ['--disable-features=CalculateNativeWinOcclusion']),
34
+ // Chromium's sandbox needs a setuid helper or user namespaces, which a CI container rarely has.
35
+ ...(platform === 'linux' && !args.includes('--no-sandbox') ? ['--no-sandbox'] : []),
36
+ ];
37
+ }
38
+ const running = new Set();
39
+ let exitHookInstalled = false;
40
+ /** An app the runner leaves behind when it exits would keep its windows open: every one still running is killed. */
41
+ function killAtExit() {
42
+ if (exitHookInstalled)
43
+ return;
44
+ exitHookInstalled = true;
45
+ process.once('exit', () => {
46
+ for (const launched of running)
47
+ launched.killNow();
48
+ });
49
+ }
50
+ export class ElectronProcess {
51
+ /** The DevTools protocol of the app's browser process, over the pipe. */
52
+ browser;
53
+ /** Resolves when the process ends, however it does; a binary that cannot be started ends at once. */
54
+ exited;
55
+ /** The address of the main process's inspector, once it printed one; never settles for an app that opens none. */
56
+ inspector;
57
+ /** Why the binary could not be started at all. */
58
+ spawnError;
59
+ /** Whether the main process printed its inspector's address. */
60
+ inspectorSeen = false;
61
+ exit;
62
+ stderr = [];
63
+ child;
64
+ waitingHandlers = [];
65
+ constructor(command) {
66
+ killAtExit();
67
+ this.child = spawn(command.executable, [...engineArguments(command.args), ...command.args], {
68
+ cwd: command.cwd,
69
+ env: command.env,
70
+ // fd 3 carries the engine's commands and fd 4 the browser's answers. stdout is not read: an unread pipe would stall the app.
71
+ stdio: ['ignore', 'ignore', 'pipe', 'pipe', 'pipe'],
72
+ // A process group of its own, so the kill reaches every helper process Chromium starts.
73
+ detached: process.platform !== 'win32',
74
+ });
75
+ running.add(this);
76
+ this.browser = new Connection(pipeTransport(this.child.stdio[3], this.child.stdio[4]));
77
+ this.exited = new Promise((resolve) => {
78
+ const done = (exit) => {
79
+ if (this.exit !== undefined)
80
+ return;
81
+ // A helper the app started can outlive it, holding the pipes open: the whole group goes, and the pipes with it.
82
+ this.killGroup();
83
+ this.exit = exit;
84
+ running.delete(this);
85
+ this.browser.close();
86
+ // What the app wrote last is still on its way: its stderr is read to the end, which the killed group cannot hold off.
87
+ const { stderr } = this.child;
88
+ const finish = () => {
89
+ stderr?.destroy();
90
+ resolve(exit);
91
+ };
92
+ if (stderr === null || stderr.readableEnded || stderr.destroyed)
93
+ return finish();
94
+ stderr.once('close', finish);
95
+ setTimeout(finish, STDERR_DRAIN_MS).unref();
96
+ };
97
+ this.child.once('exit', (code, signal) => done({ code, signal }));
98
+ this.child.once('error', (error) => {
99
+ this.spawnError = error;
100
+ done({ code: null, signal: null });
101
+ });
102
+ });
103
+ this.inspector = new Promise((resolve) => {
104
+ let partial = '';
105
+ this.child.stderr?.setEncoding('utf8');
106
+ const read = (chunk, last) => {
107
+ const lines = (partial + chunk).split('\n');
108
+ partial = last ? '' : (lines.pop() ?? '');
109
+ for (const line of lines) {
110
+ const address = INSPECTOR_LISTENING.exec(line)?.[1];
111
+ if (address !== undefined) {
112
+ this.inspectorSeen = true;
113
+ resolve(address);
114
+ }
115
+ if (INSPECTOR_WAITING.test(line))
116
+ for (const handler of this.waitingHandlers)
117
+ handler();
118
+ if (line.trim() === '' || INSPECTOR_NOISE.test(line))
119
+ continue;
120
+ this.stderr.push(line.trim());
121
+ if (this.stderr.length > STDERR_LINES)
122
+ this.stderr.shift();
123
+ }
124
+ };
125
+ this.child.stderr?.on('data', (chunk) => read(chunk, false));
126
+ // A last line with no newline after it is a line all the same.
127
+ this.child.stderr?.once('end', () => read('', true));
128
+ });
129
+ }
130
+ /** How the process ended, or undefined while it runs. */
131
+ get ended() {
132
+ return this.exit;
133
+ }
134
+ /** The last lines the app wrote to stderr, each once, in order. */
135
+ stderrTail(count) {
136
+ return [...new Set(this.stderr)].slice(-count);
137
+ }
138
+ /** Runs `handler` when the process is done and waits only for the inspector's client to let go. */
139
+ onWaitingForInspector(handler) {
140
+ this.waitingHandlers.push(handler);
141
+ }
142
+ /** Kills the process and every process it started, without waiting for them. */
143
+ killNow() {
144
+ if (this.exit === undefined)
145
+ this.killGroup();
146
+ }
147
+ killGroup() {
148
+ const { pid } = this.child;
149
+ if (pid === undefined)
150
+ return;
151
+ try {
152
+ if (process.platform === 'win32') {
153
+ const { status, error } = spawnSync('taskkill', ['/pid', String(pid), '/T', '/F'], { stdio: 'ignore', timeout: TASKKILL_MS });
154
+ if (error !== undefined || status !== 0)
155
+ throw error ?? new Error(`taskkill exited with ${status}`);
156
+ }
157
+ else {
158
+ process.kill(-pid, 'SIGKILL');
159
+ }
160
+ }
161
+ catch {
162
+ // The group is gone already, or was never the process's own: the process itself is still killed.
163
+ if (this.exit === undefined)
164
+ this.child.kill('SIGKILL');
165
+ }
166
+ }
167
+ }
@@ -0,0 +1,46 @@
1
+ /**
2
+ * Reading a window and finding nodes in it: one accessibility tree and one
3
+ * DOM snapshot of the same document, projected by `tree.ts`, and locator
4
+ * expressions resolved over the projection.
5
+ */
6
+ import { type EngineSnapshot, type LocatorExpression, type SemanticNode } from '@e2e-dev/core/engine';
7
+ import type { DevTools } from './devtools.ts';
8
+ import type { AXNode } from './fields.ts';
9
+ import type { DomSnapshot } from './snapshot.ts';
10
+ import { type ProjectionMode, type WindowGeometry } from './tree.ts';
11
+ import { type AppWindow } from './windows.ts';
12
+ /** One window's raw read: the accessibility tree, the DOM snapshot of the same document, and its geometry. */
13
+ export interface RawRead {
14
+ readonly window: AppWindow;
15
+ readonly ax: readonly AXNode[];
16
+ readonly dom: DomSnapshot;
17
+ readonly geometry: WindowGeometry;
18
+ /** Which of the page's documents was read. */
19
+ readonly generation: number;
20
+ readonly title: string;
21
+ readonly url: string;
22
+ }
23
+ /** What a projection reads beside the window itself. */
24
+ export interface ProjectionContext {
25
+ readonly testIdAttribute: string;
26
+ /** The app's open windows, for the snapshot's tabs. */
27
+ readonly open: readonly AppWindow[];
28
+ }
29
+ /** Reads the window: its accessibility tree and a DOM snapshot of the same document, with the geometry joining them. */
30
+ export declare function readWindow(devtools: DevTools, window: AppWindow): Promise<RawRead>;
31
+ /**
32
+ * Runs a read that belongs to one document of the window, the one of
33
+ * `generation`. A navigation under it makes the read stale whether it then
34
+ * answers, with parts of two documents, or fails, in whatever way the
35
+ * document going away made it fail: the caller reads again.
36
+ */
37
+ export declare function inDocument<T>(window: AppWindow, generation: number, read: () => Promise<T>): Promise<T>;
38
+ /** Projects a read into the snapshot the harness receives; `keep` holds elements a selector matched, kept where the tree leaves them out. */
39
+ export declare function projectRead(raw: RawRead, mode: ProjectionMode, context: ProjectionContext, keep?: ReadonlySet<number>): EngineSnapshot;
40
+ /**
41
+ * Resolves a locator expression in a read window. `resolveExpression` takes
42
+ * the selector answer synchronously, so every selector in the expression is
43
+ * queried first; the elements they match stay in the tree even where
44
+ * Chromium's tree leaves them out.
45
+ */
46
+ export declare function locateIn(devtools: DevTools, raw: RawRead, expression: LocatorExpression, context: ProjectionContext): Promise<readonly SemanticNode[]>;
package/dist/locate.js ADDED
@@ -0,0 +1,103 @@
1
+ /**
2
+ * Reading a window and finding nodes in it: one accessibility tree and one
3
+ * DOM snapshot of the same document, projected by `tree.ts`, and locator
4
+ * expressions resolved over the projection.
5
+ */
6
+ import { expressionSelectors, resolveExpression } from '@e2e-dev/core/engine';
7
+ import { stale } from './errors.js';
8
+ import { projectTree } from './tree.js';
9
+ import { nodeId, ROOT_ID } from './windows.js';
10
+ /** Reads the window: its accessibility tree and a DOM snapshot of the same document, with the geometry joining them. */
11
+ export async function readWindow(devtools, window) {
12
+ const { session } = window.page;
13
+ const { generation } = window.page;
14
+ // Its three parts may come from either side of a navigation: only a read of one document is a read.
15
+ const [{ nodes }, snapshot, metrics] = await inDocument(window, generation, () => Promise.all([session.send('Accessibility.getFullAXTree'), devtools.snapshot(window.page), session.send('Page.getLayoutMetrics')]));
16
+ const css = metrics.cssLayoutViewport;
17
+ const device = metrics.layoutViewport;
18
+ if (snapshot === undefined)
19
+ throw stale('the window has no document yet');
20
+ return {
21
+ window,
22
+ ax: nodes,
23
+ dom: snapshot.dom,
24
+ generation,
25
+ geometry: {
26
+ scale: css.clientWidth > 0 ? device.clientWidth / css.clientWidth : 1,
27
+ scrollX: metrics.cssVisualViewport.pageX,
28
+ scrollY: metrics.cssVisualViewport.pageY,
29
+ width: metrics.cssVisualViewport.clientWidth,
30
+ height: metrics.cssVisualViewport.clientHeight,
31
+ },
32
+ title: snapshot.title,
33
+ url: window.page.url(),
34
+ };
35
+ }
36
+ /**
37
+ * Runs a read that belongs to one document of the window, the one of
38
+ * `generation`. A navigation under it makes the read stale whether it then
39
+ * answers, with parts of two documents, or fails, in whatever way the
40
+ * document going away made it fail: the caller reads again.
41
+ */
42
+ export async function inDocument(window, generation, read) {
43
+ const moved = () => window.page.generation !== generation;
44
+ let result;
45
+ try {
46
+ result = await read();
47
+ }
48
+ catch (cause) {
49
+ if (moved())
50
+ throw stale('the window loaded another document while it was read', cause);
51
+ throw cause;
52
+ }
53
+ if (moved())
54
+ throw stale('the window loaded another document while it was read');
55
+ return result;
56
+ }
57
+ /** Projects a read into the snapshot the harness receives; `keep` holds elements a selector matched, kept where the tree leaves them out. */
58
+ export function projectRead(raw, mode, context, keep) {
59
+ const projection = projectTree(raw.ax, raw.dom, raw.geometry, {
60
+ mode,
61
+ ...(keep === undefined ? {} : { keep }),
62
+ testIdAttribute: context.testIdAttribute,
63
+ idOf: (backendNodeId) => nodeId(raw.window, raw.generation, backendNodeId),
64
+ rootId: ROOT_ID,
65
+ baseUrl: raw.url,
66
+ ...(raw.title === '' ? {} : { title: raw.title }),
67
+ });
68
+ const active = context.open.indexOf(raw.window);
69
+ return {
70
+ location: raw.url,
71
+ root: projection.root,
72
+ viewport: { width: raw.geometry.width, height: raw.geometry.height },
73
+ ...(projection.truncated ? { truncated: true } : {}),
74
+ ...(context.open.length > 1 && active >= 0 ? { tabs: { count: context.open.length, active } } : {}),
75
+ };
76
+ }
77
+ /**
78
+ * Resolves a locator expression in a read window. `resolveExpression` takes
79
+ * the selector answer synchronously, so every selector in the expression is
80
+ * queried first; the elements they match stay in the tree even where
81
+ * Chromium's tree leaves them out.
82
+ */
83
+ export async function locateIn(devtools, raw, expression, context) {
84
+ const { window } = raw;
85
+ const selected = new Map();
86
+ await inDocument(window, raw.generation, async () => {
87
+ for (const selector of expressionSelectors(expression))
88
+ selected.set(selector, await devtools.querySelectorAll(window.page, selector));
89
+ });
90
+ const keep = new Set([...selected.values()].flatMap((ids) => [...ids]));
91
+ const { root } = projectRead(raw, 'node', context, keep);
92
+ // The hook answers in document order, as `querySelectorAll` does; `aria-owns` can put the tree in another one.
93
+ const domOrder = new Map([...keep].map((backendNodeId) => [nodeId(window, raw.generation, backendNodeId), raw.dom.element(backendNodeId)?.index]));
94
+ const position = (node) => domOrder.get(node.ref.id) ?? Number.MAX_SAFE_INTEGER;
95
+ return resolveExpression(expression, [root], {
96
+ // The tree carries every element's text, so a text query reads it alone, as web() does.
97
+ textQuery: 'text',
98
+ selector: (selector, candidates) => {
99
+ const ids = new Set([...(selected.get(selector) ?? [])].map((backendNodeId) => nodeId(window, raw.generation, backendNodeId)));
100
+ return candidates.filter((node) => ids.has(node.ref.id)).toSorted((a, b) => position(a) - position(b));
101
+ },
102
+ });
103
+ }
@@ -0,0 +1,25 @@
1
+ /**
2
+ * The app's main process, reached over the Node inspector it opens with
3
+ * `--inspect`: where `electron.evaluate` runs, and where the main process's
4
+ * console is read. An app that opens no inspector has none of this.
5
+ */
6
+ import type { ElectronMainModule } from './fixtures.ts';
7
+ /** One line the main process wrote to its console. */
8
+ export type MainConsole = (type: string, text: string) => void;
9
+ export declare class MainProcess {
10
+ private readonly connection;
11
+ private module;
12
+ private constructor();
13
+ /** Connects to the inspector at `url` and starts reading the main process's console. */
14
+ static connect(url: string, timeoutMs: number, onConsole: MainConsole): Promise<MainProcess>;
15
+ /** The main process's `electron` module, held as a remote object for every call to receive. */
16
+ private electronModule;
17
+ /**
18
+ * Runs `fn` in the main process with its `electron` module and `arg`, and
19
+ * returns what it returns as plain data (`plainData`). `fn` is sent as
20
+ * source text, and `arg` as JSON.
21
+ */
22
+ evaluate<R, A>(fn: (electron: ElectronMainModule, arg: A) => R | Promise<R>, arg: A): Promise<R>;
23
+ /** Disconnects. Node waits for its inspector's clients before it exits, so a quitting app is let go of here. */
24
+ close(): void;
25
+ }
@@ -0,0 +1,60 @@
1
+ /**
2
+ * The app's main process, reached over the Node inspector it opens with
3
+ * `--inspect`: where `electron.evaluate` runs, and where the main process's
4
+ * console is read. An app that opens no inspector has none of this.
5
+ */
6
+ import { Connection, webSocketTransport } from './cdp/connection.js';
7
+ import { consoleText } from './console-text.js';
8
+ import { callForPlainData, checkJsonArgument, describeException, functionSource } from './evaluate.js';
9
+ export class MainProcess {
10
+ connection;
11
+ module;
12
+ constructor(connection) {
13
+ this.connection = connection;
14
+ }
15
+ /** Connects to the inspector at `url` and starts reading the main process's console. */
16
+ static async connect(url, timeoutMs, onConsole) {
17
+ const connection = new Connection(await webSocketTransport(url, timeoutMs));
18
+ const { root } = connection;
19
+ root.on('Runtime.consoleAPICalled', (event) => {
20
+ // Context 0 is the inspector's own; the app's console calls come from its default context.
21
+ if (event.executionContextId !== 0)
22
+ onConsole(event.type, consoleText(event.args));
23
+ });
24
+ await root.send('Runtime.enable');
25
+ return new MainProcess(connection);
26
+ }
27
+ /** The main process's `electron` module, held as a remote object for every call to receive. */
28
+ electronModule() {
29
+ if (this.module === undefined) {
30
+ const module = (async () => {
31
+ // `require` is in scope only with the command-line API, since Electron 28.
32
+ const { result, exceptionDetails } = await this.connection.root.send('Runtime.evaluate', { expression: "require('electron')", includeCommandLineAPI: true });
33
+ if (exceptionDetails !== undefined || result.objectId === undefined)
34
+ throw new Error(`the main process has no electron module: ${exceptionDetails === undefined ? result.type : describeException(exceptionDetails)}`);
35
+ return result.objectId;
36
+ })();
37
+ this.module = module;
38
+ module.catch(() => {
39
+ if (this.module === module)
40
+ this.module = undefined;
41
+ });
42
+ }
43
+ return this.module;
44
+ }
45
+ /**
46
+ * Runs `fn` in the main process with its `electron` module and `arg`, and
47
+ * returns what it returns as plain data (`plainData`). `fn` is sent as
48
+ * source text, and `arg` as JSON.
49
+ */
50
+ async evaluate(fn, arg) {
51
+ checkJsonArgument(arg, 'electron.evaluate');
52
+ const source = functionSource(fn, 'electron.evaluate');
53
+ const objectId = await this.electronModule();
54
+ return (await callForPlainData(this.connection.root, { objectId, source, leading: [{ objectId }], arg }));
55
+ }
56
+ /** Disconnects. Node waits for its inspector's clients before it exits, so a quitting app is let go of here. */
57
+ close() {
58
+ this.connection.close();
59
+ }
60
+ }
@@ -0,0 +1,65 @@
1
+ /**
2
+ * What the Electron engine is given: its options. The app under test is the
3
+ * target's `app` (`appPath`, `launchArguments`); these options only say how
4
+ * the engine starts Electron and reads its windows.
5
+ */
6
+ /** Variables no app is started with, whoever sets them, by their upper-case names. */
7
+ export declare const REFUSED_ENV: ReadonlySet<string>;
8
+ /**
9
+ * Options of the Electron engine. Every optional value also accepts
10
+ * `undefined`, so values read straight from `process.env` need no
11
+ * conditional spread.
12
+ */
13
+ export interface ElectronOptions {
14
+ /**
15
+ * The executable to start: a packaged app's binary, or an Electron binary
16
+ * of your own; relative to the project root. Default: the `electron`
17
+ * package installed in the project, which runs the target's `app.appPath`.
18
+ */
19
+ readonly executablePath?: string | undefined;
20
+ /**
21
+ * Variables added to the app's environment. The app does not get the run's
22
+ * environment, only what a process needs to start and draw (`PATH`,
23
+ * `HOME`, the locale, the display): pass anything else it reads here.
24
+ */
25
+ readonly env?: Readonly<Record<string, string>> | undefined;
26
+ /** The directory the app's process starts in: absolute, or relative to the project root. Default: the project root. */
27
+ readonly cwd?: string | undefined;
28
+ /** The attribute `getByTestId` reads. Default `data-testid`. */
29
+ readonly testIdAttribute?: string | undefined;
30
+ /**
31
+ * How long the engine waits after an action the agent took before the
32
+ * agent observes again, in milliseconds; `false` skips the wait. A test's
33
+ * own steps never wait: `expect` polls their outcome. Default 100.
34
+ */
35
+ readonly settle?: number | false | undefined;
36
+ }
37
+ /** The options with defaults applied, checked once at config load. */
38
+ export interface ResolvedElectronOptions {
39
+ readonly executablePath?: string;
40
+ readonly env: Readonly<Record<string, string>>;
41
+ readonly cwd?: string;
42
+ readonly testIdAttribute: string;
43
+ readonly settleMs: number;
44
+ }
45
+ /**
46
+ * Why the engine refuses a launch argument it owns, or undefined: Chromium's
47
+ * profile directory (every attempt gets an empty one), and the inspector and
48
+ * the DevTools transport the engine drives the app through (a fixed port
49
+ * would also collide between workers).
50
+ */
51
+ export declare function ownedArgument(argument: string): string | undefined;
52
+ /** Checks the target's `app.launchArguments`: the app's own switches and Chromium's, none of the engine's. */
53
+ export declare function checkLaunchArguments(launchArguments: readonly string[] | undefined): void;
54
+ /** Checks the option bag the way every config option is checked: unknown keys and wrong types fail the config load. */
55
+ export declare function resolveOptions(options: ElectronOptions | undefined): ResolvedElectronOptions;
56
+ type RefusalCode = 'INVALID_CONFIG' | 'INVALID_ARGUMENT';
57
+ /** Checks that `cwd` names a directory a process can start in, from the project root. */
58
+ export declare function checkCwd(label: string, projectRoot: string, cwd: string | undefined, code: RefusalCode): void;
59
+ /** What `electron.launch()` was given, checked: the arguments, variables, and directory one test adds to its launches. */
60
+ export declare function checkLaunchOptions(options: unknown, projectRoot: string): {
61
+ readonly args: readonly string[];
62
+ readonly env: Readonly<Record<string, string>>;
63
+ readonly cwd?: string;
64
+ };
65
+ export {};
@@ -0,0 +1,120 @@
1
+ /**
2
+ * What the Electron engine is given: its options. The app under test is the
3
+ * target's `app` (`appPath`, `launchArguments`); these options only say how
4
+ * the engine starts Electron and reads its windows.
5
+ */
6
+ import { statSync } from 'node:fs';
7
+ import path from 'node:path';
8
+ import { ConfigurationError, rejectUnknownKeys, TestError } from '@e2e-dev/core/engine';
9
+ /** Variables no app is started with, whoever sets them, by their upper-case names. */
10
+ export const REFUSED_ENV = new Set(['ELECTRON_RUN_AS_NODE', 'NODE_OPTIONS']);
11
+ const OPTION_KEYS = Object.keys({
12
+ executablePath: true,
13
+ env: true,
14
+ cwd: true,
15
+ testIdAttribute: true,
16
+ settle: true,
17
+ });
18
+ /**
19
+ * Why the engine refuses a launch argument it owns, or undefined: Chromium's
20
+ * profile directory (every attempt gets an empty one), and the inspector and
21
+ * the DevTools transport the engine drives the app through (a fixed port
22
+ * would also collide between workers).
23
+ */
24
+ export function ownedArgument(argument) {
25
+ if (/^--user-data-dir(=|$)/.test(argument))
26
+ return 'must not set --user-data-dir: the engine gives every attempt an empty one of its own';
27
+ const port = /^(--inspect(-brk)?|--remote-debugging-port|--remote-debugging-pipe)(=|$)/.exec(argument);
28
+ if (port !== null)
29
+ return `must not set ${port[1]}: the engine opens the inspector and the DevTools pipe it drives the app through itself`;
30
+ return undefined;
31
+ }
32
+ /** Checks the target's `app.launchArguments`: the app's own switches and Chromium's, none of the engine's. */
33
+ export function checkLaunchArguments(launchArguments) {
34
+ const owned = launchArguments?.map(ownedArgument).find((reason) => reason !== undefined);
35
+ if (owned !== undefined)
36
+ throw new ConfigurationError('INVALID_CONFIG', `app.launchArguments ${owned}`);
37
+ }
38
+ const DEFAULT_SETTLE_MS = 100;
39
+ /**
40
+ * An attribute name the document grammar accepts (XML `Name`, ASCII): a value
41
+ * outside it could never be on an element, so `getByTestId` would match
42
+ * nothing and every `testId` query would fail silently.
43
+ */
44
+ const ATTRIBUTE_NAME = /^[A-Za-z_:][A-Za-z0-9_:.-]*$/;
45
+ /** Checks the option bag the way every config option is checked: unknown keys and wrong types fail the config load. */
46
+ export function resolveOptions(options) {
47
+ // Only a missing bag defaults: a null one (from JSON an agent wrote for e2e mcp) is a config error, not the defaults.
48
+ const bag = options === undefined ? {} : options;
49
+ if (typeof bag !== 'object' || bag === null || Array.isArray(bag))
50
+ throw new ConfigurationError('INVALID_CONFIG', 'electron() options must be an object');
51
+ rejectUnknownKeys('electron() options', bag, OPTION_KEYS);
52
+ const { executablePath, env, cwd, testIdAttribute, settle } = bag;
53
+ if (executablePath !== undefined && (typeof executablePath !== 'string' || executablePath === '')) {
54
+ throw new ConfigurationError('INVALID_CONFIG', 'electron({ executablePath }) must be a path to an executable');
55
+ }
56
+ checkEnv('electron({ env })', env, 'INVALID_CONFIG');
57
+ checkCwdShape('electron({ cwd })', cwd, 'INVALID_CONFIG');
58
+ if (testIdAttribute !== undefined && (typeof testIdAttribute !== 'string' || !ATTRIBUTE_NAME.test(testIdAttribute))) {
59
+ throw new ConfigurationError('INVALID_CONFIG', `electron({ testIdAttribute }) must be an attribute name such as "data-testid", got ${JSON.stringify(testIdAttribute)}`);
60
+ }
61
+ if (settle !== undefined && settle !== false && (!Number.isInteger(settle) || settle < 0)) {
62
+ throw new ConfigurationError('INVALID_CONFIG', 'electron({ settle }) must be a whole number of milliseconds, or false');
63
+ }
64
+ return {
65
+ ...(executablePath === undefined ? {} : { executablePath }),
66
+ env: env ?? {},
67
+ ...(cwd === undefined ? {} : { cwd }),
68
+ testIdAttribute: testIdAttribute ?? 'data-testid',
69
+ settleMs: settle === false ? 0 : (settle ?? DEFAULT_SETTLE_MS),
70
+ };
71
+ }
72
+ /** A config's mistake is a configuration error; a test's call with the same mistake is the test's. */
73
+ function refusal(code, message) {
74
+ return code === 'INVALID_CONFIG' ? new ConfigurationError(code, message) : new TestError(code, message);
75
+ }
76
+ /** Checks variables for the app's environment: names to strings, none of the ones no app is started with. */
77
+ function checkEnv(label, env, code) {
78
+ if (env === undefined)
79
+ return;
80
+ if (typeof env !== 'object' || env === null || Array.isArray(env) || Object.values(env).some((value) => typeof value !== 'string')) {
81
+ throw refusal(code, `${label} must be an object of variable name to string value`);
82
+ }
83
+ // Windows reads a variable's name in any case.
84
+ const refused = Object.keys(env).find((name) => REFUSED_ENV.has(name.toUpperCase()));
85
+ if (refused !== undefined) {
86
+ throw refusal(code, `${label} must not set ${refused}: ${refused.toUpperCase() === 'NODE_OPTIONS' ? 'the engine starts the app with its own Node.js switches' : 'it starts the binary as plain Node.js, which opens no window'}`);
87
+ }
88
+ }
89
+ function checkCwdShape(label, cwd, code) {
90
+ if (cwd !== undefined && (typeof cwd !== 'string' || cwd === ''))
91
+ throw refusal(code, `${label} must be a path to a directory`);
92
+ }
93
+ /** Checks that `cwd` names a directory a process can start in, from the project root. */
94
+ export function checkCwd(label, projectRoot, cwd, code) {
95
+ if (cwd === undefined)
96
+ return;
97
+ const resolved = path.resolve(projectRoot, cwd);
98
+ if (statSync(resolved, { throwIfNoEntry: false })?.isDirectory() !== true)
99
+ throw refusal(code, `${label} names ${resolved}, which is not a directory`);
100
+ }
101
+ const LAUNCH_KEYS = ['args', 'env', 'cwd', 'timeout'];
102
+ /** What `electron.launch()` was given, checked: the arguments, variables, and directory one test adds to its launches. */
103
+ export function checkLaunchOptions(options, projectRoot) {
104
+ const label = 'electron.launch()';
105
+ if (options === undefined)
106
+ return { args: [], env: {} };
107
+ if (typeof options !== 'object' || options === null || Array.isArray(options))
108
+ throw refusal('INVALID_ARGUMENT', `${label} takes an object of options`);
109
+ rejectUnknownKeys(`${label} options`, options, LAUNCH_KEYS, 'INVALID_ARGUMENT');
110
+ const { args = [], env, cwd } = options;
111
+ if (!Array.isArray(args) || args.some((argument) => typeof argument !== 'string'))
112
+ throw refusal('INVALID_ARGUMENT', 'electron.launch({ args }) must be a list of strings');
113
+ const owned = args.map(ownedArgument).find((reason) => reason !== undefined);
114
+ if (owned !== undefined)
115
+ throw refusal('INVALID_ARGUMENT', `electron.launch({ args }) ${owned}`);
116
+ checkEnv('electron.launch({ env })', env, 'INVALID_ARGUMENT');
117
+ checkCwdShape('electron.launch({ cwd })', cwd, 'INVALID_ARGUMENT');
118
+ checkCwd('electron.launch({ cwd })', projectRoot, cwd, 'INVALID_ARGUMENT');
119
+ return { args: [...args], env: { ...env }, ...(cwd === undefined ? {} : { cwd }) };
120
+ }