@e2e-dev/electron 0.1.0 → 0.1.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.
package/dist/.build.json CHANGED
@@ -1 +1 @@
1
- {"version":"0.1.0"}
1
+ {"version":"0.1.1"}
package/dist/actions.js CHANGED
@@ -344,7 +344,8 @@ async function longPress(budget, window, at, durationMs = LONG_PRESS_MS) {
344
344
  /**
345
345
  * Presses at `from` and drags to the point `target` answers once the pointer
346
346
  * is down, through a move in between so drag handlers see motion before the
347
- * drop; paced over `durationMs` when given.
347
+ * drop, and a second move at the target so an HTML drag drops there; paced
348
+ * over `durationMs` when given.
348
349
  */
349
350
  async function drag(budget, window, from, target, durationMs) {
350
351
  const { mouse } = window.page;
@@ -358,6 +359,9 @@ async function drag(budget, window, from, target, durationMs) {
358
359
  if (durationMs !== undefined)
359
360
  await sleep(durationMs / steps, budget.operation.signal);
360
361
  }
362
+ // An HTML drag drops only once the target has seen a move after the one that entered it: a release right after the
363
+ // first move over the target ends the drag with no drop.
364
+ await budget.send(() => mouse.move(to.x, to.y));
361
365
  }
362
366
  finally {
363
367
  await mouse.up();
@@ -263,7 +263,7 @@ export class AppProcess {
263
263
  const page = new PageTarget(info.targetId, app.process.browser.session(sessionId), info.url, info.openerId === undefined ? undefined : app.pages.get(info.openerId));
264
264
  app.pages.set(info.targetId, page);
265
265
  // A window that has loaded nothing has no renderer and never answers: it becomes a window once it does.
266
- await this.follow(page, report);
266
+ await this.follow(page, report, app.process.browser);
267
267
  if (current() && !page.isClosed())
268
268
  this.windows.add(page);
269
269
  };
@@ -292,7 +292,7 @@ export class AppProcess {
292
292
  * answers its dialogs, and keeps its crashed and navigated states.
293
293
  * Resolves once the page answers, which a page with a renderer does.
294
294
  */
295
- async follow(page, report) {
295
+ async follow(page, report, browser) {
296
296
  const { session } = page;
297
297
  const { log } = report;
298
298
  let mainFrame;
@@ -332,16 +332,24 @@ export class AppProcess {
332
332
  page.markLoaded();
333
333
  });
334
334
  session.on('Page.frameNavigated', ({ frame }) => {
335
- if (frame.parentId !== undefined)
335
+ if (frame.parentId !== undefined) {
336
+ page.navigatedInChildFrame();
336
337
  return;
338
+ }
337
339
  mainFrame = frame.id;
338
340
  page.documentChanged();
339
341
  navigatedTo(frame.url + (frame.urlFragment ?? ''));
340
342
  });
341
343
  session.on('Page.navigatedWithinDocument', ({ frameId, url }) => {
342
- if (frameId === mainFrame)
343
- navigatedTo(url);
344
+ if (frameId !== mainFrame) {
345
+ if (mainFrame !== undefined)
346
+ page.navigatedInChildFrame();
347
+ return;
348
+ }
349
+ page.navigatedWithinDocument();
350
+ navigatedTo(url);
344
351
  });
352
+ followOtherRenderers(page, session, browser);
345
353
  const enabled = session.send('Page.enable');
346
354
  for (const start of [
347
355
  session.send('Page.getFrameTree').then(({ frameTree }) => {
@@ -477,7 +485,7 @@ async function quitGracefully(app, graceMs) {
477
485
  }
478
486
  return (await answerWithin(process.exited, graceMs)) !== undefined;
479
487
  }
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. */
488
+ /** The first of the app's open windows, in the order they were registered (see `Windows.open`), to have a parsed document: a window is read from then on. */
481
489
  async function loaded(pages, deadline, signal) {
482
490
  let first;
483
491
  await pollCondition({
@@ -675,3 +683,21 @@ const INHERITED_ENV = new Set([
675
683
  function levelOf(type) {
676
684
  return type === 'error' ? 'error' : type === 'warning' ? 'warning' : 'info';
677
685
  }
686
+ /**
687
+ * Counts the navigations of the page's frames that run in renderers of their
688
+ * own (a frame of another site), which the page's session never reports: each
689
+ * such frame is attached on a session of its own as it appears, and so are
690
+ * the frames of other sites inside it.
691
+ */
692
+ function followOtherRenderers(page, parent, browser) {
693
+ parent.on('Target.attachedToTarget', ({ sessionId, targetInfo }) => {
694
+ if (targetInfo.type !== 'iframe')
695
+ return;
696
+ const frame = browser.session(sessionId);
697
+ frame.on('Page.frameNavigated', () => page.navigatedInChildFrame());
698
+ frame.on('Page.navigatedWithinDocument', () => page.navigatedInChildFrame());
699
+ followOtherRenderers(page, frame, browser);
700
+ frame.send('Page.enable').catch(() => undefined);
701
+ });
702
+ parent.send('Target.setAutoAttach', { autoAttach: true, waitForDebuggerOnStart: false, flatten: true, filter: [{ type: 'iframe' }] }).catch(() => undefined);
703
+ }
@@ -9,6 +9,8 @@ import { DomSnapshot } from './snapshot.ts';
9
9
  export interface DocumentSnapshot {
10
10
  readonly dom: DomSnapshot;
11
11
  readonly title: string;
12
+ /** The URL the document resolves its relative links against: its <base href>, else its own. */
13
+ readonly baseUrl: string | undefined;
12
14
  }
13
15
  export declare class DevTools {
14
16
  /** Runs `work` in the window's isolated world with an object group of its own, released when the call ends. */
package/dist/devtools.js CHANGED
@@ -106,6 +106,6 @@ export class DevTools {
106
106
  async snapshot(page) {
107
107
  const { documents, strings } = await page.session.send('DOMSnapshot.captureSnapshot', { computedStyles: [...SNAPSHOT_STYLES] });
108
108
  const document = documents[0];
109
- return document === undefined ? undefined : { dom: new DomSnapshot(document, strings), title: strings[document.title] ?? '' };
109
+ return document === undefined ? undefined : { dom: new DomSnapshot(document, strings), title: strings[document.title] ?? '', baseUrl: strings[document.baseURL] };
110
110
  }
111
111
  }
package/dist/electron.js CHANGED
@@ -3,6 +3,7 @@
3
3
  * than of a control in a window. The harness records each call as an
4
4
  * `electron.<method>` step bounded by the action timeout.
5
5
  */
6
+ import { types } from 'node:util';
6
7
  import { ConfigurationError, isSecret, stepTimeout, TestError } from '@e2e-dev/core/engine';
7
8
  import { EXPECTATION_OPERATIONS, WindowConditions } from './expectation.js';
8
9
  import { typeKeys } from './actions.js';
@@ -115,18 +116,21 @@ export function createElectronFixture(surface, context) {
115
116
  windows: () => surface.openWindows().map(handle),
116
117
  async waitForWindow(trigger, options) {
117
118
  if (typeof trigger !== 'function')
118
- throw new ConfigurationError('INVALID_ARGUMENT', 'electron.waitForWindow() takes the function that opens the window');
119
+ throw new TestError('INVALID_ARGUMENT', 'electron.waitForWindow() takes the function that opens the window');
119
120
  return handle(await surface.waitForWindow(trigger, context.operation(stepTimeout(options?.timeout, 'electron.waitForWindow'))));
120
121
  },
121
122
  async window(which, options) {
122
123
  if (typeof which !== 'object' || which === null || (which.title === undefined && which.url === undefined)) {
123
- throw new ConfigurationError('INVALID_ARGUMENT', 'electron.window() takes { title } or { url }; electron.windows() lists every window');
124
+ throw new TestError('INVALID_ARGUMENT', 'electron.window() takes { title } or { url }; electron.windows() lists every window');
124
125
  }
126
+ // Anything else would read as an empty pattern and match every window.
127
+ if (!(which.title === undefined || isPattern(which.title)) || !(which.url === undefined || isPattern(which.url)))
128
+ throw new TestError('INVALID_ARGUMENT', 'electron.window() takes a string or a RegExp for title and url');
125
129
  return handle(await surface.findWindow(which, context.operation(stepTimeout(options?.timeout, 'electron.window'))));
126
130
  },
127
131
  async waitForDownload(trigger, options) {
128
132
  if (typeof trigger !== 'function')
129
- throw new ConfigurationError('INVALID_ARGUMENT', 'electron.waitForDownload() takes the function that starts the download');
133
+ throw new TestError('INVALID_ARGUMENT', 'electron.waitForDownload() takes the function that starts the download');
130
134
  const file = await surface.waitForDownload(trigger, context.operation(stepTimeout(options?.timeout, 'electron.waitForDownload')));
131
135
  context.attachArtifact('download', file.path);
132
136
  return file;
@@ -134,7 +138,7 @@ export function createElectronFixture(surface, context) {
134
138
  // Async so the harness records the registration as an `electron.onDialog` step.
135
139
  async onDialog(handler) {
136
140
  if (handler !== 'accept' && handler !== 'dismiss' && typeof handler !== 'function') {
137
- throw new ConfigurationError('INVALID_ARGUMENT', "electron.onDialog() takes 'accept', 'dismiss', or a function that answers the dialog");
141
+ throw new TestError('INVALID_ARGUMENT', "electron.onDialog() takes 'accept', 'dismiss', or a function that answers the dialog");
138
142
  }
139
143
  const off = surface.onDialog(handler);
140
144
  return () => {
@@ -144,7 +148,7 @@ export function createElectronFixture(surface, context) {
144
148
  },
145
149
  locator(selector) {
146
150
  if (typeof selector !== 'string' || selector.trim() === '')
147
- throw new ConfigurationError('INVALID_ARGUMENT', 'electron.locator() takes a CSS selector string');
151
+ throw new TestError('INVALID_ARGUMENT', 'electron.locator() takes a CSS selector string');
148
152
  return context.locator({ kind: 'selector', selector });
149
153
  },
150
154
  };
@@ -162,11 +166,23 @@ export function createElectronFixture(surface, context) {
162
166
  mouse: { move: input, down: input, up: input, wheel: input },
163
167
  evaluate: { kind: 'resource' },
164
168
  waitForWindow: { kind: 'resource', timeout: false },
165
- window: { kind: 'resource', timeout: (_which, options) => options?.timeout, label: (which) => JSON.stringify({ title: which.title?.toString(), url: which.url?.toString() }) },
169
+ window: { kind: 'resource', timeout: false, label: (which) => (typeof which === 'object' && which !== null ? JSON.stringify({ title: patternText(which.title), url: patternText(which.url) }) : '') },
166
170
  waitForDownload: { kind: 'resource', timeout: false },
167
171
  onDialog: { kind: 'resource' },
168
172
  });
169
173
  }
174
+ /**
175
+ * Whether a value is a window matcher's title or url pattern: a string, or a
176
+ * RegExp from any realm (`vm`, another frame), whose source and flags the
177
+ * lookup reads.
178
+ */
179
+ function isPattern(value) {
180
+ return typeof value === 'string' || types.isRegExp(value);
181
+ }
182
+ /** A pattern as a step's label shows it; nothing for a value that is none, which `electron.window()` then refuses. */
183
+ function patternText(value) {
184
+ return isPattern(value) ? String(value) : undefined;
185
+ }
170
186
  /** Whether a value is a secret handle or holds one in an array or a plain object, at any depth. */
171
187
  function holdsSecret(value, seen = new Set()) {
172
188
  if (isSecret(value))
package/dist/engine.d.ts CHANGED
@@ -15,7 +15,7 @@ import { type ElectronOptions } from './options.ts';
15
15
  * names this package: a project sees `@e2e-dev/core` only through its
16
16
  * dependencies, and TypeScript cannot write that path in a declaration.
17
17
  */
18
- export interface ElectronEngine extends EngineHandle<ElectronFixtures> {
18
+ export interface ElectronEngine extends EngineHandle<ElectronFixtures, 'electron', 'attempt'> {
19
19
  }
20
20
  /**
21
21
  * Creates one Electron engine. A test launches the app with `app.open()`, on
@@ -8,7 +8,11 @@ import type { Session } from './cdp/connection.ts';
8
8
  /** What a function run in the app threw: its own failure, not the engine's. */
9
9
  export declare class EvaluateError extends Error {
10
10
  }
11
- /** Refuses an argument that is not JSON, in the caller's name: it crosses the protocol as a value. */
11
+ /**
12
+ * Refuses an argument that is not plain JSON, in the caller's name: it crosses
13
+ * the protocol as a value, where a function or a non-finite number would be
14
+ * changed rather than refused.
15
+ */
12
16
  export declare function checkJsonArgument(arg: unknown, caller: string): void;
13
17
  /**
14
18
  * Calls the function `source` on the remote object `objectId` with `leading`
package/dist/evaluate.js CHANGED
@@ -3,18 +3,17 @@
3
3
  * the function sent as source text, its argument as a protocol value, and
4
4
  * what it returns brought back as plain data.
5
5
  */
6
- import { TestError } from '@e2e-dev/core/engine';
6
+ import { TestError, validateJsonValue } from '@e2e-dev/core/engine';
7
7
  /** What a function run in the app threw: its own failure, not the engine's. */
8
8
  export class EvaluateError extends Error {
9
9
  }
10
- /** Refuses an argument that is not JSON, in the caller's name: it crosses the protocol as a value. */
10
+ /**
11
+ * Refuses an argument that is not plain JSON, in the caller's name: it crosses
12
+ * the protocol as a value, where a function or a non-finite number would be
13
+ * changed rather than refused.
14
+ */
11
15
  export function checkJsonArgument(arg, caller) {
12
- try {
13
- JSON.stringify(arg);
14
- }
15
- catch (cause) {
16
- throw new TestError('INVALID_ARGUMENT', `${caller}: its argument is not JSON (${cause instanceof Error ? (cause.message.split('\n')[0] ?? '') : String(cause)}); pass plain data`, { cause });
17
- }
16
+ validateJsonValue(arg, `${caller} argument`);
18
17
  }
19
18
  /**
20
19
  * Calls the function `source` on the remote object `objectId` with `leading`
package/dist/fields.js CHANGED
@@ -187,9 +187,9 @@ function valueOf(node, facts, role, policy) {
187
187
  * path, a query and a fragment only as `?…` and `#…` (they routinely carry
188
188
  * tokens), and a scheme with no origin (`data:`, `javascript:`), whose path
189
189
  * is a whole file or script, as `scheme:…`. A relative link resolves against
190
- * the document's URL. The web engine's own copy is `originAndPath` in
191
- * `packages/web/src/in-page/read-semantics.ts`: a change to what either hides
192
- * belongs in both. They differ in one place on purpose: this one shows a
190
+ * the document's `<base href>`, else its URL. The web engine's own copy is
191
+ * `originAndPath` in `packages/web/src/in-page/read-semantics.ts`: a change to
192
+ * what either hides belongs in both. They differ in one place on purpose: this one shows a
193
193
  * `file:` path, since an Electron app's own pages are local files.
194
194
  */
195
195
  function originAndPath(value, base) {
@@ -143,7 +143,12 @@ export interface Electron extends Expectable<ElectronExpectation> {
143
143
  evaluate<R>(fn: (electron: ElectronMainModule) => R | Promise<R>): Promise<R>;
144
144
  /** Runs `fn` in the main process with `arg`, which a function that takes one must be given. */
145
145
  evaluate<R, A>(fn: (electron: ElectronMainModule, arg: A) => R | Promise<R>, arg: A): Promise<R>;
146
- /** The app's open windows, in the order they opened. */
146
+ /**
147
+ * The app's open windows, in the order the engine registered them: each once
148
+ * it has a renderer, after it started loading its first page. This is not
149
+ * strictly load-start order: two windows that start loading at about the
150
+ * same time can come in either order.
151
+ */
147
152
  windows(): readonly ElectronWindow[];
148
153
  /**
149
154
  * Runs a trigger and waits for the window it opens, then resolves with that
package/dist/locate.d.ts CHANGED
@@ -19,6 +19,8 @@ export interface RawRead {
19
19
  readonly generation: number;
20
20
  readonly title: string;
21
21
  readonly url: string;
22
+ /** What the document resolves its relative links against: its <base href>, else its URL. */
23
+ readonly baseUrl: string | undefined;
22
24
  }
23
25
  /** What a projection reads beside the window itself. */
24
26
  export interface ProjectionContext {
package/dist/locate.js CHANGED
@@ -13,8 +13,10 @@ export async function readWindow(devtools, window) {
13
13
  const { generation } = window.page;
14
14
  // Its three parts may come from either side of a navigation: only a read of one document is a read.
15
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;
16
+ // The visual viewport's sizes are exact; the layout viewport's are whole pixels, which under a page zoom such as 1.5
17
+ // give a scale a little off, and an error that grows down the document.
18
+ const css = metrics.cssVisualViewport;
19
+ const device = metrics.visualViewport;
18
20
  if (snapshot === undefined)
19
21
  throw stale('the window has no document yet');
20
22
  return {
@@ -30,6 +32,7 @@ export async function readWindow(devtools, window) {
30
32
  height: metrics.cssVisualViewport.clientHeight,
31
33
  },
32
34
  title: snapshot.title,
35
+ baseUrl: snapshot.baseUrl,
33
36
  url: window.page.url(),
34
37
  };
35
38
  }
@@ -62,7 +65,8 @@ export function projectRead(raw, mode, context, keep) {
62
65
  testIdAttribute: context.testIdAttribute,
63
66
  idOf: (backendNodeId) => nodeId(raw.window, raw.generation, backendNodeId),
64
67
  rootId: ROOT_ID,
65
- baseUrl: raw.url,
68
+ // A link reads as the page resolves it: against its <base href> when it has one.
69
+ baseUrl: raw.baseUrl ?? raw.url,
66
70
  ...(raw.title === '' ? {} : { title: raw.title }),
67
71
  });
68
72
  const active = context.open.indexOf(raw.window);
package/dist/page.d.ts CHANGED
@@ -27,6 +27,8 @@ export declare class PageTarget implements InputTarget {
27
27
  private closed;
28
28
  private isolated;
29
29
  private documents;
30
+ private withinDocument;
31
+ private inChildFrames;
30
32
  /** Whether the current document fired its load event. */
31
33
  private loaded;
32
34
  private gestures;
@@ -50,6 +52,16 @@ export declare class PageTarget implements InputTarget {
50
52
  * again, so a number alone could name another node in the next document.
51
53
  */
52
54
  get generation(): number;
55
+ /** How many times the page went to another history entry of the same document (a fragment, pushState, back to one). */
56
+ get sameDocumentNavigations(): number;
57
+ /** The page went to another entry of its document. */
58
+ navigatedWithinDocument(): void;
59
+ /** How many times a frame inside the page navigated, to another document or within its own. */
60
+ get childFrameNavigations(): number;
61
+ /** A frame inside the page navigated. */
62
+ navigatedInChildFrame(): void;
63
+ /** Whether the current document has fired its load event. */
64
+ get hasLoaded(): boolean;
53
65
  /** The current document fired its load event. */
54
66
  markLoaded(): void;
55
67
  /** The page has another document: the isolated world of the last one is dropped, and its nodes are no longer this page's. */
package/dist/page.js CHANGED
@@ -23,6 +23,8 @@ export class PageTarget {
23
23
  closed = false;
24
24
  isolated;
25
25
  documents = 0;
26
+ withinDocument = 0;
27
+ inChildFrames = 0;
26
28
  /** Whether the current document fired its load event. */
27
29
  loaded = false;
28
30
  gestures = Promise.resolve();
@@ -89,6 +91,26 @@ export class PageTarget {
89
91
  get generation() {
90
92
  return this.documents;
91
93
  }
94
+ /** How many times the page went to another history entry of the same document (a fragment, pushState, back to one). */
95
+ get sameDocumentNavigations() {
96
+ return this.withinDocument;
97
+ }
98
+ /** The page went to another entry of its document. */
99
+ navigatedWithinDocument() {
100
+ this.withinDocument += 1;
101
+ }
102
+ /** How many times a frame inside the page navigated, to another document or within its own. */
103
+ get childFrameNavigations() {
104
+ return this.inChildFrames;
105
+ }
106
+ /** A frame inside the page navigated. */
107
+ navigatedInChildFrame() {
108
+ this.inChildFrames += 1;
109
+ }
110
+ /** Whether the current document has fired its load event. */
111
+ get hasLoaded() {
112
+ return this.loaded;
113
+ }
92
114
  /** The current document fired its load event. */
93
115
  markLoaded() {
94
116
  this.loaded = true;
package/dist/surface.d.ts CHANGED
@@ -106,7 +106,7 @@ export declare class ElectronSurface {
106
106
  input(label: string, send: (window: AppWindow, budget: Budget) => Promise<void>, operation: OperationContext): Promise<void>;
107
107
  switchTab(index: number, operation: OperationContext): Promise<void>;
108
108
  closeTab(index: number, operation: OperationContext): Promise<void>;
109
- /** The app's open windows, in the order they opened. */
109
+ /** The app's open windows, in the order they were registered (see `Windows.open`). */
110
110
  openWindows(): readonly AppWindow[];
111
111
  /** `electron.activeWindow()`: the window `screen` reads. */
112
112
  shownWindow(): AppWindow;
package/dist/surface.js CHANGED
@@ -404,7 +404,7 @@ export class ElectronSurface {
404
404
  await withBudget(operation, 'close window', (budget) => budget.send(() => this.app.closeWindow(window.page)));
405
405
  }
406
406
  // --- what the fixture asks ---
407
- /** The app's open windows, in the order they opened. */
407
+ /** The app's open windows, in the order they were registered (see `Windows.open`). */
408
408
  openWindows() {
409
409
  return this.windowList.open();
410
410
  }
@@ -595,7 +595,30 @@ export class ElectronSurface {
595
595
  const previous = entries[currentIndex - 1];
596
596
  if (previous === undefined)
597
597
  throw notActionable('the window has no page to go back to');
598
+ const { page } = window;
599
+ const before = { document: page.generation, withinDocument: page.sameDocumentNavigations, inChildFrames: page.childFrameNavigations };
598
600
  await budget.send(() => session.send('Page.navigateToHistoryEntry', { entryId: previous.id }));
601
+ // The command answers as the navigation starts: the step ends once the window shows the entry, a document that
602
+ // loaded or, for an entry of the same document (a fragment, pushState, at the same URL too), the navigation to it,
603
+ // as web()'s back waits for load. An entry only a frame inside the page made moves no part of the page's own
604
+ // document, and is at the URL the window shows: a frame's navigation ends the step only while the window shows
605
+ // the entry's URL, so a frame of the page being left that navigates on its own does not end a back to another
606
+ // URL. The history's current entry cannot tell: it names the pending entry as soon as the command answers. Out of
607
+ // time, the window may already be on its way to the entry (a document that committed and is still loading): a
608
+ // timeout, which the budget reports as a back that may have happened, so the next step checks the window first.
609
+ await pollCondition({
610
+ deadline: budget.waits,
611
+ signal: operation.signal,
612
+ negated: false,
613
+ evaluate: () => {
614
+ if (page.generation !== before.document)
615
+ return Promise.resolve(page.hasLoaded);
616
+ if (page.sameDocumentNavigations !== before.withinDocument)
617
+ return Promise.resolve(true);
618
+ return Promise.resolve(page.childFrameNavigations !== before.inChildFrames && page.url() === previous.url);
619
+ },
620
+ onTimeout: () => new EngineError('OPERATION_TIMEOUT', 'the window did not show its previous page in time', { retryable: false }),
621
+ });
599
622
  });
600
623
  }
601
624
  // --- downloads ---
package/dist/tree.d.ts CHANGED
@@ -33,7 +33,7 @@ export interface ProjectionOptions {
33
33
  readonly idOf: (backendNodeId: number) => string;
34
34
  /** The root's id, stable for the surface. */
35
35
  readonly rootId: string;
36
- /** The document's URL, which a relative link resolves against. */
36
+ /** What a relative link resolves against: the document's <base href>, else its URL. */
37
37
  readonly baseUrl?: string;
38
38
  /** The document's title, the root's name. */
39
39
  readonly title?: string;
package/dist/tree.js CHANGED
@@ -140,23 +140,52 @@ class TreeProjector {
140
140
  placeAbsent(roots) {
141
141
  const wanted = new Set(this.options.keep ?? []);
142
142
  if (this.policy.hiddenTestIds) {
143
- // Content under aria-hidden or inert is out of the accessibility tree and on screen all the same: a text query
144
- // finds it, as on the web, on the element that holds the text, each one under the element that hides them. It
145
- // has no role, so a role query still does not.
143
+ // Content under aria-hidden or inert, or behind a modal dialog, is out of the accessibility tree and on screen
144
+ // all the same: a text query finds it, as on the web, on the element that holds the text, each one under the
145
+ // element that hides them. It has no role, so a role query still does not.
146
146
  const hides = (facts) => facts.attributes['aria-hidden']?.toLowerCase() === 'true' || facts.attributes['inert'] !== undefined;
147
147
  const hiding = new Set();
148
148
  for (const [backend, facts] of this.snapshot.elements())
149
149
  if (hides(facts))
150
150
  hiding.add(backend);
151
+ // A modal dialog showModal() opened holds the rest of the page inert with no attribute: Chromium's tree keeps
152
+ // only the document's root, ignored for the dialog, and the dialog under it, and leaves out what the dialog
153
+ // blocks. The dialog's own content and the elements that hold it are not blocked, so they are not placed.
154
+ const blocking = new Set();
155
+ const dialogs = [];
156
+ for (const node of this.nodes.values()) {
157
+ const backend = node.backendDOMNodeId;
158
+ if (backend === undefined)
159
+ continue;
160
+ if (node.ignored && node.ignoredReasons?.some((reason) => reason.name === 'activeModalDialog') === true)
161
+ blocking.add(backend);
162
+ const index = this.snapshot.element(backend)?.index;
163
+ if (!node.ignored && index !== undefined && node.properties?.some((entry) => entry.name === 'modal' && entry.value.value === true) === true)
164
+ dialogs.push(index);
165
+ }
166
+ // A dialog showModal() opened that Chromium does not call modal (`aria-modal="false"`, `role="menu"`) blocks the
167
+ // page all the same, but nothing says which elements hold it: blocking without one would place <body> with the
168
+ // script's source and the dialog's text, so nothing is placed for the dialog, as before.
169
+ if (dialogs.length === 0)
170
+ blocking.clear();
171
+ const holdsDialog = new Set(dialogs.flatMap((index) => [...this.snapshot.ancestors(index)]));
172
+ const inDialog = new Set(dialogs.flatMap((index) => [...this.snapshot.subtree(index)]));
151
173
  /** Whether the element hides itself or sits under one that does; a page that hides nothing is not walked. */
152
174
  const hidden = (backend, index) => {
153
- if (hiding.size === 0)
175
+ if (hiding.size === 0 && blocking.size === 0)
154
176
  return false;
155
177
  if (hiding.has(backend))
156
178
  return true;
157
179
  for (const ancestor of this.snapshot.ancestors(index))
158
180
  if (hiding.has(ancestor))
159
181
  return true;
182
+ if (blocking.size === 0 || holdsDialog.has(backend) || inDialog.has(index))
183
+ return false;
184
+ if (blocking.has(backend))
185
+ return true;
186
+ for (const ancestor of this.snapshot.ancestors(index))
187
+ if (blocking.has(ancestor))
188
+ return true;
160
189
  return false;
161
190
  };
162
191
  for (const [backend, facts] of this.snapshot.elements()) {
@@ -174,7 +203,7 @@ class TreeProjector {
174
203
  const draft = this.element(backend, undefined, facts, 'generic');
175
204
  const siblings = this.parentOf(facts.index)?.children ?? roots;
176
205
  if (!isSecure(facts) && !isTextField(facts))
177
- this.adoptText(draft, siblings);
206
+ this.adoptContent(draft, siblings);
178
207
  const at = siblings.findIndex((sibling) => sibling.order > draft.order);
179
208
  siblings.splice(at < 0 ? siblings.length : at, 0, draft);
180
209
  }
@@ -321,23 +350,27 @@ class TreeProjector {
321
350
  return this.snapshot.parentOf(run.order) !== draft.order;
322
351
  }
323
352
  /**
324
- * The text of an element the tree left out. The text runs the tree already
325
- * holds for it move under it, so its text is not read twice; with none
326
- * (nothing rendered), the text comes from the DOM.
353
+ * The content of an element the tree left out. The text runs and elements
354
+ * the tree already holds for it move under it, so its text is not read
355
+ * twice and a query scoped to it finds them. With no text run among them,
356
+ * the text comes from the DOM: the elements it adopted may hold only part
357
+ * of it, and hidden content placed under it later has its text there.
327
358
  */
328
- adoptText(draft, siblings) {
359
+ adoptContent(draft, siblings) {
329
360
  const inside = this.snapshot.subtree(draft.order);
330
- const runs = siblings.filter((sibling) => sibling.isText && inside.has(sibling.order));
331
- if (runs.length === 0) {
332
- const text = this.snapshot.textContent(draft.order);
333
- if (text !== '')
334
- draft.text = cut(text, this.policy.textLimit);
361
+ // Its text runs, and the elements in it the tree kept (a button in a display: contents wrapper), so a query scoped
362
+ // to it finds them.
363
+ const adopted = siblings.filter((sibling) => inside.has(sibling.order));
364
+ for (const child of adopted)
365
+ siblings.splice(siblings.indexOf(child), 1);
366
+ draft.children = adopted;
367
+ if (adopted.some((child) => child.isText)) {
368
+ this.foldText(draft);
335
369
  return;
336
370
  }
337
- for (const run of runs)
338
- siblings.splice(siblings.indexOf(run), 1);
339
- draft.children = runs;
340
- this.foldText(draft);
371
+ const text = this.snapshot.textContent(draft.order);
372
+ if (text !== '')
373
+ draft.text = cut(text, this.policy.textLimit);
341
374
  }
342
375
  /** The nearest DOM ancestor of the node at `index` that is an element in the tree; undefined when it sits under the root. */
343
376
  parentOf(index) {
package/dist/windows.d.ts CHANGED
@@ -53,7 +53,7 @@ export declare class Windows {
53
53
  has(page: PageTarget): boolean;
54
54
  /** Whether a page is the window `screen` and the agent read. */
55
55
  isShownPage(page: PageTarget): boolean;
56
- /** The open windows, in the order they opened. A `WebContentsView` is a page of its own and counts as a window. */
56
+ /** The open windows, in the order they were registered: each once it has a renderer, after it started loading its first page. A `WebContentsView` is a page of its own and counts as a window. */
57
57
  open(): AppWindow[];
58
58
  /**
59
59
  * The window `screen` and the agent read: the one chosen, else the first the
@@ -74,7 +74,11 @@ export declare class Windows {
74
74
  closable(index: number): AppWindow;
75
75
  /** Makes an open window the shown one. */
76
76
  activate(window: AppWindow): void;
77
- /** The open windows with what a matcher reads of each, so a window that closes while the titles are read cannot shift a match onto another. */
77
+ /**
78
+ * What a matcher reads of each window, read at once and answered in the
79
+ * windows' order, so a window that closes while the titles are read cannot
80
+ * shift a match onto another. Never rejects.
81
+ */
78
82
  private describe;
79
83
  /** The first open window `which` matches, waiting for it to open until a little before the operation's deadline. It is not shown: the caller activates it. */
80
84
  find(which: WindowMatcher, windowTitle: WindowTitle, operation: OperationContext): Promise<AppWindow>;
package/dist/windows.js CHANGED
@@ -7,6 +7,8 @@ import { invalidState, notActionable, stale } from './errors.js';
7
7
  import { answerWithin, Budget } from './budget.js';
8
8
  /** How long a window gets to say its document's title. */
9
9
  const TITLE_MS = 1_000;
10
+ /** The least a lookup gives each title read, within the operation's end: one near its deadline still names the windows its miss lists. */
11
+ const TITLE_FLOOR_MS = 100;
10
12
  /** The observation root's id: one surface, one root, whichever window it reads. */
11
13
  export const ROOT_ID = 'window';
12
14
  /**
@@ -94,7 +96,7 @@ export class Windows {
94
96
  isShownPage(page) {
95
97
  return this.shown?.page === page;
96
98
  }
97
- /** The open windows, in the order they opened. A `WebContentsView` is a page of its own and counts as a window. */
99
+ /** The open windows, in the order they were registered: each once it has a renderer, after it started loading its first page. A `WebContentsView` is a page of its own and counts as a window. */
98
100
  open() {
99
101
  return [...this.byPage.values()].filter(isOpen).toSorted((a, b) => a.serial - b.serial);
100
102
  }
@@ -154,13 +156,18 @@ export class Windows {
154
156
  throw new TestError('ACTION_FAILED', 'the window has closed');
155
157
  this.showWindow(window);
156
158
  }
157
- /** The open windows with what a matcher reads of each, so a window that closes while the titles are read cannot shift a match onto another. */
158
- async describe(windowTitle) {
159
- return await Promise.all(this.open().map(async (window) => {
160
- // A window whose renderer crashed, or is busy, never answers: it is listed without a title rather than not at all.
161
- const [title = '', own] = await Promise.all([answerWithin(window.page.title(), TITLE_MS), windowTitle(window.page)]);
159
+ /**
160
+ * What a matcher reads of each window, read at once and answered in the
161
+ * windows' order, so a window that closes while the titles are read cannot
162
+ * shift a match onto another. Never rejects.
163
+ */
164
+ describe(windowTitle, windows, withinMs) {
165
+ return windows.map(async (window) => {
166
+ // A window whose renderer crashed, or is busy, never answers: it is listed without a title rather than not at all,
167
+ // and by the lookup's own time, so a busy window before a match never holds the match past it.
168
+ const [title = '', own] = await Promise.all([answerWithin(window.page.title(), withinMs), answerWithin(windowTitle(window.page), withinMs)]);
162
169
  return { window, title, ...(own === undefined || own === title ? {} : { windowTitle: own }), url: window.page.url() };
163
- }));
170
+ });
164
171
  }
165
172
  /** The first open window `which` matches, waiting for it to open until a little before the operation's deadline. It is not shown: the caller activates it. */
166
173
  async find(which, windowTitle, operation) {
@@ -172,18 +179,45 @@ export class Windows {
172
179
  signal: operation.signal,
173
180
  negated: false,
174
181
  evaluate: async () => {
175
- described = await this.describe(windowTitle);
176
- // A match that closed while the titles were read is no match; the next read looks again.
177
- found = described.find((each) => matchesWindow(each, which) && this.open().includes(each.window))?.window;
182
+ // Titles are read only when the matcher names one, and only of the windows at a URL it takes: a busy renderer
183
+ // elsewhere answers late, and its title decides nothing.
184
+ const candidates = this.open().filter((window) => matches(which.url, window.page.url()));
185
+ const reads = which.title === undefined ? candidates.map((window) => Promise.resolve({ window, title: '', url: window.page.url() })) : this.describe(windowTitle, candidates, titleReadMs(budget));
186
+ const read = [];
187
+ found = undefined;
188
+ // In the windows' order: the first open window that matches wins, without waiting on a busy one after it.
189
+ for (const pending of reads) {
190
+ const each = await pending;
191
+ read.push(each);
192
+ // A match that closed while the titles were read is no match; the next read looks again.
193
+ if (matchesWindow(each, which) && this.open().includes(each.window)) {
194
+ found = each.window;
195
+ break;
196
+ }
197
+ }
198
+ described = read;
178
199
  return found !== undefined;
179
200
  },
180
- onTimeout: () => notActionable(`no window matches ${describeMatcher(which)}; open: ${described.map(({ title }) => JSON.stringify(title)).join(', ') || 'none'}`),
201
+ onTimeout: () => {
202
+ // The titles of the windows at a URL the matcher takes; with no title asked for, or no window at such a URL, the URLs say why.
203
+ const open = which.title === undefined || described.length === 0 ? this.open().map((window) => window.page.url()) : described.map(({ title }) => title);
204
+ return notActionable(`no window matches ${describeMatcher(which)}; open: ${open.map((each) => JSON.stringify(each)).join(', ') || 'none'}`);
205
+ },
181
206
  });
182
207
  if (found === undefined)
183
208
  throw notActionable(`no window matches ${describeMatcher(which)}`);
184
209
  return found;
185
210
  }
186
211
  }
212
+ /**
213
+ * How long one title read of a lookup gets: what is left of its wait, at
214
+ * least `TITLE_FLOOR_MS` so a read near the wait's end still names the
215
+ * windows, and never past the operation's own end, which the wait leaves a
216
+ * margin before.
217
+ */
218
+ function titleReadMs(budget) {
219
+ return Math.min(TITLE_MS, Math.max(TITLE_FLOOR_MS, budget.waits.remaining()), budget.deadline.remaining());
220
+ }
187
221
  function windowCount(count) {
188
222
  return `${count} window${count === 1 ? '' : 's'}`;
189
223
  }
@@ -191,9 +225,12 @@ function windowCount(count) {
191
225
  function isOpen(window) {
192
226
  return !window.page.isClosed() && !window.page.url().startsWith('devtools://');
193
227
  }
228
+ /** Whether a matcher's pattern takes a value: equal to a string, or matched by a pattern; no pattern takes any value. */
229
+ function matches(pattern, value) {
230
+ return pattern === undefined || (typeof pattern === 'string' ? value === pattern : new RegExp(pattern.source, pattern.flags).test(value));
231
+ }
194
232
  function matchesWindow(window, which) {
195
- const test = (pattern, value) => pattern === undefined || (typeof pattern === 'string' ? value === pattern : new RegExp(pattern.source, pattern.flags).test(value));
196
- return (test(which.title, window.title) || (window.windowTitle !== undefined && test(which.title, window.windowTitle))) && test(which.url, window.url);
233
+ return (matches(which.title, window.title) || (window.windowTitle !== undefined && matches(which.title, window.windowTitle))) && matches(which.url, window.url);
197
234
  }
198
235
  function describeMatcher(which) {
199
236
  return [which.title === undefined ? '' : `title ${String(which.title)}`, which.url === undefined ? '' : `url ${String(which.url)}`].filter(Boolean).join(' and ') || 'any window';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@e2e-dev/electron",
3
- "version": "0.1.0",
3
+ "version": "0.1.1",
4
4
  "description": "Electron engine for e2e agentic end-to-end testing: launches an Electron app and drives its windows through Chromium's accessibility tree",
5
5
  "keywords": [
6
6
  "e2e",
@@ -52,11 +52,11 @@
52
52
  }
53
53
  },
54
54
  "devDependencies": {
55
- "@e2e-dev/core": "0.26.0",
55
+ "@e2e-dev/core": "0.26.1",
56
56
  "@napi-rs/image": "1.16.0",
57
57
  "@types/node": "26.6.11",
58
- "devtools-protocol": "0.0.1756183",
59
- "e2e": "0.26.0",
58
+ "devtools-protocol": "0.0.1758431",
59
+ "e2e": "0.26.1",
60
60
  "electron": "45.5.0",
61
61
  "typescript": "7.0.2",
62
62
  "vitest": "5.1.2"