@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.
- package/LICENSE +202 -0
- package/NOTICE +5 -0
- package/README.md +91 -2
- package/dist/.build.json +1 -0
- package/dist/actionability.d.ts +41 -0
- package/dist/actionability.js +121 -0
- package/dist/actions.d.ts +52 -0
- package/dist/actions.js +418 -0
- package/dist/app-process.d.ts +114 -0
- package/dist/app-process.js +610 -0
- package/dist/budget.d.ts +33 -0
- package/dist/budget.js +64 -0
- package/dist/capture.d.ts +21 -0
- package/dist/capture.js +137 -0
- package/dist/cdp/connection.d.ts +68 -0
- package/dist/cdp/connection.js +232 -0
- package/dist/cdp/input.d.ts +67 -0
- package/dist/cdp/input.js +195 -0
- package/dist/cdp/keys.d.ts +21 -0
- package/dist/cdp/keys.js +114 -0
- package/dist/console-text.d.ts +4 -0
- package/dist/console-text.js +27 -0
- package/dist/devtools.d.ts +36 -0
- package/dist/devtools.js +111 -0
- package/dist/dialogs.d.ts +38 -0
- package/dist/dialogs.js +81 -0
- package/dist/electron.d.ts +9 -0
- package/dist/electron.js +174 -0
- package/dist/engine-entry.d.ts +13 -0
- package/dist/engine-entry.js +9 -0
- package/dist/engine.d.ts +27 -0
- package/dist/engine.js +98 -0
- package/dist/errors.d.ts +17 -0
- package/dist/errors.js +54 -0
- package/dist/evaluate.d.ts +40 -0
- package/dist/evaluate.js +115 -0
- package/dist/executable.d.ts +29 -0
- package/dist/executable.js +249 -0
- package/dist/ffmpeg.d.ts +12 -0
- package/dist/ffmpeg.js +100 -0
- package/dist/fields.d.ts +93 -0
- package/dist/fields.js +254 -0
- package/dist/file-bound.d.ts +31 -0
- package/dist/file-bound.js +104 -0
- package/dist/fixtures.d.ts +168 -0
- package/dist/fixtures.js +6 -0
- package/dist/in-page/masks.d.ts +25 -0
- package/dist/in-page/masks.js +140 -0
- package/dist/in-page/node-ops.d.ts +96 -0
- package/dist/in-page/node-ops.js +406 -0
- package/dist/index.d.ts +18 -0
- package/dist/index.js +18 -0
- package/dist/launcher.d.ts +45 -0
- package/dist/launcher.js +167 -0
- package/dist/locate.d.ts +46 -0
- package/dist/locate.js +103 -0
- package/dist/main-process.d.ts +25 -0
- package/dist/main-process.js +60 -0
- package/dist/options.d.ts +65 -0
- package/dist/options.js +120 -0
- package/dist/page.d.ts +100 -0
- package/dist/page.js +229 -0
- package/dist/runner-test.d.ts +15 -0
- package/dist/runner-test.js +45 -0
- package/dist/snapshot.d.ts +143 -0
- package/dist/snapshot.js +260 -0
- package/dist/surface.d.ts +158 -0
- package/dist/surface.js +602 -0
- package/dist/tree.d.ts +51 -0
- package/dist/tree.js +406 -0
- package/dist/video.d.ts +42 -0
- package/dist/video.js +253 -0
- package/dist/windows.d.ts +81 -0
- package/dist/windows.js +200 -0
- package/package.json +72 -3
package/dist/budget.js
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* One operation's budget: its deadline, the check every input passes, and
|
|
3
|
+
* whether any input went out, which decides how a failure is reported.
|
|
4
|
+
*/
|
|
5
|
+
import { Deadline, EngineError, raceAbort, withTimeout } from '@e2e-dev/core/engine';
|
|
6
|
+
import { translate } from './errors.js';
|
|
7
|
+
/** How long before the operation's end a wait inside it gives up, at most. */
|
|
8
|
+
const WAIT_MARGIN_MS = 250;
|
|
9
|
+
export class Budget {
|
|
10
|
+
operation;
|
|
11
|
+
label;
|
|
12
|
+
/** The operation's end. */
|
|
13
|
+
deadline;
|
|
14
|
+
/**
|
|
15
|
+
* The deadline a wait inside the operation gives up at: a little before
|
|
16
|
+
* the operation's own, so the wait reports what it waited for rather than a
|
|
17
|
+
* bare timeout.
|
|
18
|
+
*/
|
|
19
|
+
waits;
|
|
20
|
+
sent = false;
|
|
21
|
+
constructor(operation, label) {
|
|
22
|
+
this.operation = operation;
|
|
23
|
+
this.label = label;
|
|
24
|
+
this.deadline = new Deadline(operation.timeoutMs);
|
|
25
|
+
this.waits = new Deadline(Math.max(0, operation.timeoutMs - Math.min(WAIT_MARGIN_MS, operation.timeoutMs / 10)));
|
|
26
|
+
}
|
|
27
|
+
/** Throws once the operation ended: its caller stopped waiting, and nothing more may reach the app. */
|
|
28
|
+
check() {
|
|
29
|
+
if (this.operation.signal.aborted)
|
|
30
|
+
throw new EngineError('CANCELLED', `${this.label} was cancelled`, { retryable: false });
|
|
31
|
+
if (this.deadline.expired())
|
|
32
|
+
throw this.timedOut();
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* Sends one input, through the check. From here on a timeout or a vanished
|
|
36
|
+
* node is `ACTION_MAY_HAVE_COMMITTED`, which the harness never retries.
|
|
37
|
+
*/
|
|
38
|
+
send(input) {
|
|
39
|
+
this.check();
|
|
40
|
+
this.sent = true;
|
|
41
|
+
return input();
|
|
42
|
+
}
|
|
43
|
+
/** Runs `work` within the budget and the operation's signal, its failures translated into engine errors. */
|
|
44
|
+
async run(work) {
|
|
45
|
+
try {
|
|
46
|
+
return await raceAbort(() => withTimeout(work(), Math.max(1, this.deadline.remaining()), () => this.timedOut()), this.operation.signal, this.label);
|
|
47
|
+
}
|
|
48
|
+
catch (cause) {
|
|
49
|
+
throw translate(cause, this.label, this.sent);
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
timedOut() {
|
|
53
|
+
return new EngineError('OPERATION_TIMEOUT', `${this.label} timed out after ${this.operation.timeoutMs}ms`, { retryable: false });
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
/** Runs `work` on a budget of the operation's own. */
|
|
57
|
+
export function withBudget(operation, label, work) {
|
|
58
|
+
const budget = new Budget(operation, label);
|
|
59
|
+
return budget.run(() => work(budget));
|
|
60
|
+
}
|
|
61
|
+
/** A promise's answer, or undefined when it fails or takes longer than `ms`: for a question the caller can do without. */
|
|
62
|
+
export function answerWithin(pending, ms) {
|
|
63
|
+
return withTimeout(pending, Math.max(1, ms), () => new Error('no answer in time')).catch(() => undefined);
|
|
64
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Pixels: screenshots with every password field and nested document painted
|
|
3
|
+
* over, withheld when the window holds one no mask reaches.
|
|
4
|
+
*/
|
|
5
|
+
import { type EngineSnapshot } from '@e2e-dev/core/engine';
|
|
6
|
+
import type { DevTools } from './devtools.ts';
|
|
7
|
+
import { type RawRead } from './locate.ts';
|
|
8
|
+
import type { AppWindow } from './windows.ts';
|
|
9
|
+
/** Adds the pixels to an observation of a read window, or leaves them out when they are withheld. */
|
|
10
|
+
export declare function withPixels(devtools: DevTools, raw: RawRead, snapshot: EngineSnapshot): Promise<EngineSnapshot>;
|
|
11
|
+
/**
|
|
12
|
+
* `app.screenshot(label)`: the window with its masks painted over, written
|
|
13
|
+
* under the attempt's artifacts as `screenshots/<n>-<label>.png`. Refused
|
|
14
|
+
* with `POLICY_DENIED` when the capture is withheld, when `refused` says why
|
|
15
|
+
* the window is not one to capture, or when the window loaded another
|
|
16
|
+
* document while the capture waited its turn: the pixels are of the document
|
|
17
|
+
* `refused` approved, or none are kept.
|
|
18
|
+
*/
|
|
19
|
+
export declare function screenshotFile(devtools: DevTools, window: AppWindow, artifactsDir: string, name: string, refused: () => string | undefined): Promise<string>;
|
|
20
|
+
/** A screenshot's file name: its number in the attempt and a label that cannot turn into a path (letters, digits, dashes). */
|
|
21
|
+
export declare function screenshotName(counter: number, label: string | undefined): string;
|
package/dist/capture.js
ADDED
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Pixels: screenshots with every password field and nested document painted
|
|
3
|
+
* over, withheld when the window holds one no mask reaches.
|
|
4
|
+
*/
|
|
5
|
+
import { mkdirSync, writeFileSync } from 'node:fs';
|
|
6
|
+
import path from 'node:path';
|
|
7
|
+
import { ConfigurationError, readPngSize } from '@e2e-dev/core/engine';
|
|
8
|
+
import { pixelRatio, placeMasks, removeMasks } from './in-page/masks.js';
|
|
9
|
+
import { viewportSize } from './in-page/node-ops.js';
|
|
10
|
+
import { inDocument } from './locate.js';
|
|
11
|
+
import { MASKED_TAGS } from './snapshot.js';
|
|
12
|
+
/** Everything that can hold a secure value or show another document in a screenshot: masked, or the capture is not taken. */
|
|
13
|
+
const MASKED_SELECTOR = ['input[type=password i]', ...MASKED_TAGS.map((tag) => tag.toLowerCase())].join(', ');
|
|
14
|
+
/**
|
|
15
|
+
* How many password fields and nested documents in the window's document no
|
|
16
|
+
* selector mask reaches; see `DomSnapshot.unmaskableCount`. Undefined when the
|
|
17
|
+
* document could not be read: nothing is then known to be masked.
|
|
18
|
+
*/
|
|
19
|
+
async function unmaskable(devtools, window) {
|
|
20
|
+
return (await devtools.snapshot(window.page))?.dom.unmaskableCount();
|
|
21
|
+
}
|
|
22
|
+
const UNREAD = 'the window\'s document could not be read to check what its masks cover, so the screenshot is withheld';
|
|
23
|
+
function outOfReach(count) {
|
|
24
|
+
const plural = count === 1 ? '' : 's';
|
|
25
|
+
return `the window shows ${count} password field${plural} or nested document${plural} inside a closed shadow root, which no mask reaches, so the screenshot is withheld`;
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* The one way pixels leave a window: every password field and nested document
|
|
29
|
+
* painted over, and nothing returned when one sits in a closed shadow root,
|
|
30
|
+
* out of every selector's reach. `unmaskableBefore` is that count from a read
|
|
31
|
+
* the caller already has. The app may render such an element while the
|
|
32
|
+
* capture runs, inside a closed shadow root or beside the masks already
|
|
33
|
+
* placed, so the document is read again before the pixels go out.
|
|
34
|
+
*/
|
|
35
|
+
function maskedCapture(devtools, window, unmaskableBefore, scale) {
|
|
36
|
+
// One capture of a page at a time: the masks are the page's, and a second capture would take the first one's away.
|
|
37
|
+
const turn = (captures.get(window.page) ?? Promise.resolve()).then(() => captureUnderMasks(devtools, window, unmaskableBefore, scale));
|
|
38
|
+
captures.set(window.page, turn.catch(() => undefined));
|
|
39
|
+
return turn;
|
|
40
|
+
}
|
|
41
|
+
const captures = new WeakMap();
|
|
42
|
+
async function captureUnderMasks(devtools, window, unmaskableBefore, scale) {
|
|
43
|
+
const { page } = window;
|
|
44
|
+
if (unmaskableBefore === undefined)
|
|
45
|
+
return { masked: (await page.evaluate(removeMasks, MASKED_SELECTOR)).count, withheld: UNREAD };
|
|
46
|
+
if (unmaskableBefore > 0)
|
|
47
|
+
return { masked: (await page.evaluate(removeMasks, MASKED_SELECTOR)).count, withheld: outOfReach(unmaskableBefore) };
|
|
48
|
+
const placed = await page.evaluate(placeMasks, MASKED_SELECTOR);
|
|
49
|
+
const { count: masked } = placed;
|
|
50
|
+
let image;
|
|
51
|
+
let after;
|
|
52
|
+
try {
|
|
53
|
+
image = await captureViewport(window, scale);
|
|
54
|
+
}
|
|
55
|
+
finally {
|
|
56
|
+
// The masks never outlive the capture, whatever became of it.
|
|
57
|
+
after = await page.evaluate(removeMasks, MASKED_SELECTOR).catch(() => undefined);
|
|
58
|
+
}
|
|
59
|
+
// A document that navigated or reloaded under the capture took its masks with it: the image may show the new one bare.
|
|
60
|
+
if (!placed.placed)
|
|
61
|
+
return { masked, withheld: 'a mask did not cover the password field or nested document it was placed over, so the screenshot is withheld' };
|
|
62
|
+
if (after?.placed !== true)
|
|
63
|
+
return { masked, withheld: 'the masks did not last through the screenshot (the window loaded another document, or the page removed them), so the screenshot is withheld' };
|
|
64
|
+
const unmaskableAfter = await unmaskable(devtools, window);
|
|
65
|
+
if (unmaskableAfter === undefined)
|
|
66
|
+
return { masked, withheld: UNREAD };
|
|
67
|
+
if (unmaskableAfter > 0)
|
|
68
|
+
return { masked, withheld: outOfReach(unmaskableAfter) };
|
|
69
|
+
if (after.count > masked) {
|
|
70
|
+
return { masked, withheld: 'a password field or nested document appeared while the screenshot was taken, after its masks were placed, so the screenshot is withheld' };
|
|
71
|
+
}
|
|
72
|
+
// A mask is painted where its element was measured: one a script moved since may show beside its mask.
|
|
73
|
+
if (after.boxes !== placed.boxes) {
|
|
74
|
+
return { masked, withheld: 'a password field or nested document moved while the screenshot was taken, out from under its mask, so the screenshot is withheld' };
|
|
75
|
+
}
|
|
76
|
+
return { masked, image };
|
|
77
|
+
}
|
|
78
|
+
/** The window's viewport as a PNG: one image pixel per CSS pixel, or per device pixel. */
|
|
79
|
+
async function captureViewport(window, scale) {
|
|
80
|
+
const { page } = window;
|
|
81
|
+
let clip;
|
|
82
|
+
if (scale === 'css') {
|
|
83
|
+
const [{ cssVisualViewport: scrolled }, { width, height }, ratio] = await Promise.all([page.session.send('Page.getLayoutMetrics'), page.evaluate(viewportSize), page.evaluate(pixelRatio)]);
|
|
84
|
+
// A clip is in the document's coordinates, so the window's is where the document is scrolled to. It is the window's
|
|
85
|
+
// whole inner size, scrollbars included, as a capture with no clip is.
|
|
86
|
+
if (ratio !== 1)
|
|
87
|
+
clip = { x: scrolled.pageX, y: scrolled.pageY, width, height, scale: 1 / ratio };
|
|
88
|
+
}
|
|
89
|
+
const { data } = await page.captured(() => page.session.send('Page.captureScreenshot', { format: 'png', ...(clip === undefined ? {} : { clip }) }));
|
|
90
|
+
return Buffer.from(data, 'base64');
|
|
91
|
+
}
|
|
92
|
+
/** Adds the pixels to an observation of a read window, or leaves them out when they are withheld. */
|
|
93
|
+
export async function withPixels(devtools, raw, snapshot) {
|
|
94
|
+
// The pixels are of the document the snapshot describes, or the observation is taken again.
|
|
95
|
+
const capture = await inDocument(raw.window, raw.generation, () => maskedCapture(devtools, raw.window, raw.dom.unmaskableCount(), 'css'));
|
|
96
|
+
if ('withheld' in capture)
|
|
97
|
+
return { ...snapshot, maskedRegionCount: capture.masked };
|
|
98
|
+
const data = new Uint8Array(capture.image);
|
|
99
|
+
const { width: css } = await raw.window.page.evaluate(viewportSize);
|
|
100
|
+
const size = readPngSize(data);
|
|
101
|
+
if (size === undefined)
|
|
102
|
+
throw new Error('the window capture is not a PNG');
|
|
103
|
+
const pixels = { data, mediaType: 'image/png', width: size.width, height: size.height, scale: css > 0 ? size.width / css : 1 };
|
|
104
|
+
return { ...snapshot, pixels, maskedRegionCount: capture.masked };
|
|
105
|
+
}
|
|
106
|
+
/**
|
|
107
|
+
* `app.screenshot(label)`: the window with its masks painted over, written
|
|
108
|
+
* under the attempt's artifacts as `screenshots/<n>-<label>.png`. Refused
|
|
109
|
+
* with `POLICY_DENIED` when the capture is withheld, when `refused` says why
|
|
110
|
+
* the window is not one to capture, or when the window loaded another
|
|
111
|
+
* document while the capture waited its turn: the pixels are of the document
|
|
112
|
+
* `refused` approved, or none are kept.
|
|
113
|
+
*/
|
|
114
|
+
export async function screenshotFile(devtools, window, artifactsDir, name, refused) {
|
|
115
|
+
const before = refused();
|
|
116
|
+
if (before !== undefined)
|
|
117
|
+
throw new ConfigurationError('POLICY_DENIED', before);
|
|
118
|
+
const generation = window.page.generation;
|
|
119
|
+
const capture = await maskedCapture(devtools, window, await unmaskable(devtools, window), 'device');
|
|
120
|
+
if ('withheld' in capture)
|
|
121
|
+
throw new ConfigurationError('POLICY_DENIED', capture.withheld);
|
|
122
|
+
if (window.page.generation !== generation)
|
|
123
|
+
throw new ConfigurationError('POLICY_DENIED', 'the window loaded another document while the screenshot was taken, so the screenshot is withheld');
|
|
124
|
+
const after = refused();
|
|
125
|
+
if (after !== undefined)
|
|
126
|
+
throw new ConfigurationError('POLICY_DENIED', after);
|
|
127
|
+
const relative = path.posix.join('screenshots', name);
|
|
128
|
+
const absolute = path.join(artifactsDir, relative);
|
|
129
|
+
mkdirSync(path.dirname(absolute), { recursive: true });
|
|
130
|
+
writeFileSync(absolute, capture.image);
|
|
131
|
+
return relative;
|
|
132
|
+
}
|
|
133
|
+
/** A screenshot's file name: its number in the attempt and a label that cannot turn into a path (letters, digits, dashes). */
|
|
134
|
+
export function screenshotName(counter, label) {
|
|
135
|
+
const safe = label === undefined ? '' : label.replace(/[^A-Za-z0-9._-]+/g, '-').replace(/^[-.]+|[-.]+$/g, '').slice(0, 60);
|
|
136
|
+
return `${String(counter).padStart(3, '0')}${safe === '' ? '' : `-${safe}`}.png`;
|
|
137
|
+
}
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The DevTools protocol on the wire: one connection to a browser or a Node
|
|
3
|
+
* inspector, and the flat sessions of the targets attached over it. Commands
|
|
4
|
+
* and events are typed by `devtools-protocol`.
|
|
5
|
+
*/
|
|
6
|
+
import type { Readable, Writable } from 'node:stream';
|
|
7
|
+
import type { ProtocolMapping } from 'devtools-protocol/types/protocol-mapping.js';
|
|
8
|
+
type Commands = ProtocolMapping.Commands;
|
|
9
|
+
type Events = ProtocolMapping.Events;
|
|
10
|
+
/** A protocol command's failure: the method that failed and the protocol's own error code. */
|
|
11
|
+
export declare class ProtocolError extends Error {
|
|
12
|
+
readonly method: string;
|
|
13
|
+
readonly code: number | undefined;
|
|
14
|
+
constructor(method: string, message: string, code?: number);
|
|
15
|
+
}
|
|
16
|
+
/** Carries whole protocol messages in both directions. */
|
|
17
|
+
export interface Transport {
|
|
18
|
+
send(message: string): void;
|
|
19
|
+
onMessage(handler: (message: string) => void): void;
|
|
20
|
+
onClose(handler: () => void): void;
|
|
21
|
+
close(): void;
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* The pipe a browser started with `--remote-debugging-pipe` reads commands
|
|
25
|
+
* from (its fd 3) and writes to (its fd 4): JSON messages, each ended by a
|
|
26
|
+
* NUL byte. No port is opened, so no other process can connect.
|
|
27
|
+
*/
|
|
28
|
+
export declare function pipeTransport(write: Writable, read: Readable): Transport;
|
|
29
|
+
/** A WebSocket endpoint, such as the one a Node inspector listens on; rejects when it cannot be reached within `timeoutMs`. */
|
|
30
|
+
export declare function webSocketTransport(url: string, timeoutMs: number): Promise<Transport>;
|
|
31
|
+
/**
|
|
32
|
+
* One connection. Sessions are flat (`Target.attachToTarget` with
|
|
33
|
+
* `flatten: true`): every target's traffic shares the transport and is
|
|
34
|
+
* routed by its session id.
|
|
35
|
+
*/
|
|
36
|
+
export declare class Connection {
|
|
37
|
+
private readonly transport;
|
|
38
|
+
/** The session of the endpoint itself: the browser, or a Node process. */
|
|
39
|
+
readonly root: Session;
|
|
40
|
+
private nextId;
|
|
41
|
+
private readonly pending;
|
|
42
|
+
private readonly sessions;
|
|
43
|
+
private closed;
|
|
44
|
+
constructor(transport: Transport);
|
|
45
|
+
/** The session of an attached target, by the id `Target.attachToTarget` answered with. */
|
|
46
|
+
session(sessionId: string): Session;
|
|
47
|
+
send(method: string, params: unknown, sessionId: string): Promise<unknown>;
|
|
48
|
+
/** Closes the transport; every pending command fails. */
|
|
49
|
+
close(): void;
|
|
50
|
+
private dispatch;
|
|
51
|
+
/** Drops a detached session. The browser never answers its pending commands, so they fail here rather than hang. */
|
|
52
|
+
private forget;
|
|
53
|
+
private handleClose;
|
|
54
|
+
}
|
|
55
|
+
/** One flat protocol session: the endpoint itself (an empty id) or an attached target. */
|
|
56
|
+
export declare class Session {
|
|
57
|
+
private readonly connection;
|
|
58
|
+
readonly id: string;
|
|
59
|
+
private detached;
|
|
60
|
+
private readonly listeners;
|
|
61
|
+
constructor(connection: Connection, id: string);
|
|
62
|
+
send<M extends keyof Commands>(method: M, ...params: Commands[M]['paramsType']): Promise<Commands[M]['returnType']>;
|
|
63
|
+
/** Listens for a protocol event of this session; returns the unsubscribe. */
|
|
64
|
+
on<E extends keyof Events>(event: E, handler: (params: Events[E][0]) => void): () => void;
|
|
65
|
+
emit(event: string, params: unknown): void;
|
|
66
|
+
markDetached(): void;
|
|
67
|
+
}
|
|
68
|
+
export {};
|
|
@@ -0,0 +1,232 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The DevTools protocol on the wire: one connection to a browser or a Node
|
|
3
|
+
* inspector, and the flat sessions of the targets attached over it. Commands
|
|
4
|
+
* and events are typed by `devtools-protocol`.
|
|
5
|
+
*/
|
|
6
|
+
/** A protocol command's failure: the method that failed and the protocol's own error code. */
|
|
7
|
+
export class ProtocolError extends Error {
|
|
8
|
+
method;
|
|
9
|
+
code;
|
|
10
|
+
constructor(method, message, code) {
|
|
11
|
+
super(`${method}: ${message}`);
|
|
12
|
+
this.name = 'ProtocolError';
|
|
13
|
+
this.method = method;
|
|
14
|
+
this.code = code;
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
/** One message off the wire, or undefined for one that is not a protocol message. */
|
|
18
|
+
function readMessage(raw) {
|
|
19
|
+
const parsed = JSON.parse(raw);
|
|
20
|
+
if (typeof parsed !== 'object' || parsed === null)
|
|
21
|
+
return undefined;
|
|
22
|
+
const { id, method, params, result, error, sessionId } = parsed;
|
|
23
|
+
const failure = typeof error === 'object' && error !== null ? error : undefined;
|
|
24
|
+
return {
|
|
25
|
+
...(typeof id === 'number' ? { id } : {}),
|
|
26
|
+
...(typeof method === 'string' ? { method } : {}),
|
|
27
|
+
...(typeof sessionId === 'string' ? { sessionId } : {}),
|
|
28
|
+
params,
|
|
29
|
+
result,
|
|
30
|
+
...(failure === undefined ? {} : { error: { message: String(failure['message']), ...(typeof failure['code'] === 'number' ? { code: failure['code'] } : {}) } }),
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* The pipe a browser started with `--remote-debugging-pipe` reads commands
|
|
35
|
+
* from (its fd 3) and writes to (its fd 4): JSON messages, each ended by a
|
|
36
|
+
* NUL byte. No port is opened, so no other process can connect.
|
|
37
|
+
*/
|
|
38
|
+
export function pipeTransport(write, read) {
|
|
39
|
+
const messageHandlers = [];
|
|
40
|
+
const closeHandlers = [];
|
|
41
|
+
let buffered = [];
|
|
42
|
+
read.on('data', (chunk) => {
|
|
43
|
+
let start = 0;
|
|
44
|
+
let end = chunk.indexOf(0);
|
|
45
|
+
while (end !== -1) {
|
|
46
|
+
buffered.push(chunk.subarray(start, end));
|
|
47
|
+
const message = Buffer.concat(buffered).toString('utf8');
|
|
48
|
+
buffered = [];
|
|
49
|
+
for (const handler of messageHandlers)
|
|
50
|
+
handler(message);
|
|
51
|
+
start = end + 1;
|
|
52
|
+
end = chunk.indexOf(0, start);
|
|
53
|
+
}
|
|
54
|
+
if (start < chunk.length)
|
|
55
|
+
buffered.push(chunk.subarray(start));
|
|
56
|
+
});
|
|
57
|
+
// Either half ending or failing ends the connection: a command the browser can no longer read has no answer coming.
|
|
58
|
+
const closed = () => {
|
|
59
|
+
for (const handler of closeHandlers)
|
|
60
|
+
handler();
|
|
61
|
+
};
|
|
62
|
+
read.on('close', closed);
|
|
63
|
+
read.on('error', closed);
|
|
64
|
+
write.on('close', closed);
|
|
65
|
+
write.on('error', closed);
|
|
66
|
+
return {
|
|
67
|
+
send: (message) => {
|
|
68
|
+
write.write(`${message}\0`);
|
|
69
|
+
},
|
|
70
|
+
onMessage: (handler) => void messageHandlers.push(handler),
|
|
71
|
+
onClose: (handler) => void closeHandlers.push(handler),
|
|
72
|
+
close: () => {
|
|
73
|
+
write.end();
|
|
74
|
+
read.destroy();
|
|
75
|
+
},
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
/** A WebSocket endpoint, such as the one a Node inspector listens on; rejects when it cannot be reached within `timeoutMs`. */
|
|
79
|
+
export async function webSocketTransport(url, timeoutMs) {
|
|
80
|
+
const socket = new WebSocket(url);
|
|
81
|
+
await new Promise((resolve, reject) => {
|
|
82
|
+
const timer = setTimeout(() => {
|
|
83
|
+
socket.close();
|
|
84
|
+
reject(new Error(`no answer from ${url} within ${timeoutMs}ms`));
|
|
85
|
+
}, timeoutMs);
|
|
86
|
+
socket.addEventListener('open', () => {
|
|
87
|
+
clearTimeout(timer);
|
|
88
|
+
resolve();
|
|
89
|
+
}, { once: true });
|
|
90
|
+
socket.addEventListener('error', () => {
|
|
91
|
+
clearTimeout(timer);
|
|
92
|
+
reject(new Error(`cannot connect to ${url}`));
|
|
93
|
+
}, { once: true });
|
|
94
|
+
});
|
|
95
|
+
return {
|
|
96
|
+
send: (message) => socket.send(message),
|
|
97
|
+
onMessage: (handler) => socket.addEventListener('message', (event) => handler(String(event.data))),
|
|
98
|
+
onClose: (handler) => socket.addEventListener('close', () => handler()),
|
|
99
|
+
close: () => socket.close(),
|
|
100
|
+
};
|
|
101
|
+
}
|
|
102
|
+
/**
|
|
103
|
+
* One connection. Sessions are flat (`Target.attachToTarget` with
|
|
104
|
+
* `flatten: true`): every target's traffic shares the transport and is
|
|
105
|
+
* routed by its session id.
|
|
106
|
+
*/
|
|
107
|
+
export class Connection {
|
|
108
|
+
transport;
|
|
109
|
+
/** The session of the endpoint itself: the browser, or a Node process. */
|
|
110
|
+
root;
|
|
111
|
+
nextId = 1;
|
|
112
|
+
pending = new Map();
|
|
113
|
+
sessions = new Map();
|
|
114
|
+
closed = false;
|
|
115
|
+
constructor(transport) {
|
|
116
|
+
this.transport = transport;
|
|
117
|
+
this.root = new Session(this, '');
|
|
118
|
+
transport.onMessage((raw) => {
|
|
119
|
+
let message;
|
|
120
|
+
try {
|
|
121
|
+
message = readMessage(raw);
|
|
122
|
+
}
|
|
123
|
+
catch {
|
|
124
|
+
// A frame that is not JSON means the stream is out of step, and no later answer can be trusted.
|
|
125
|
+
this.close();
|
|
126
|
+
return;
|
|
127
|
+
}
|
|
128
|
+
if (message !== undefined)
|
|
129
|
+
this.dispatch(message);
|
|
130
|
+
});
|
|
131
|
+
transport.onClose(() => this.handleClose());
|
|
132
|
+
}
|
|
133
|
+
/** The session of an attached target, by the id `Target.attachToTarget` answered with. */
|
|
134
|
+
session(sessionId) {
|
|
135
|
+
let session = this.sessions.get(sessionId);
|
|
136
|
+
if (session === undefined) {
|
|
137
|
+
session = new Session(this, sessionId);
|
|
138
|
+
this.sessions.set(sessionId, session);
|
|
139
|
+
}
|
|
140
|
+
return session;
|
|
141
|
+
}
|
|
142
|
+
send(method, params, sessionId) {
|
|
143
|
+
if (this.closed)
|
|
144
|
+
return Promise.reject(new ProtocolError(method, 'connection closed'));
|
|
145
|
+
const id = this.nextId++;
|
|
146
|
+
this.transport.send(JSON.stringify({ id, method, params: params ?? {}, ...(sessionId === '' ? {} : { sessionId }) }));
|
|
147
|
+
return new Promise((resolve, reject) => {
|
|
148
|
+
this.pending.set(id, { resolve, reject, method, sessionId });
|
|
149
|
+
});
|
|
150
|
+
}
|
|
151
|
+
/** Closes the transport; every pending command fails. */
|
|
152
|
+
close() {
|
|
153
|
+
this.transport.close();
|
|
154
|
+
this.handleClose();
|
|
155
|
+
}
|
|
156
|
+
dispatch(message) {
|
|
157
|
+
if (message.id !== undefined) {
|
|
158
|
+
const pending = this.pending.get(message.id);
|
|
159
|
+
if (pending === undefined)
|
|
160
|
+
return;
|
|
161
|
+
this.pending.delete(message.id);
|
|
162
|
+
if (message.error !== undefined)
|
|
163
|
+
pending.reject(new ProtocolError(pending.method, message.error.message, message.error.code));
|
|
164
|
+
else
|
|
165
|
+
pending.resolve(message.result ?? {});
|
|
166
|
+
return;
|
|
167
|
+
}
|
|
168
|
+
if (message.method === undefined)
|
|
169
|
+
return;
|
|
170
|
+
const session = message.sessionId === undefined ? this.root : this.sessions.get(message.sessionId);
|
|
171
|
+
if (message.method === 'Target.detachedFromTarget')
|
|
172
|
+
this.forget(message.params.sessionId);
|
|
173
|
+
session?.emit(message.method, message.params ?? {});
|
|
174
|
+
}
|
|
175
|
+
/** Drops a detached session. The browser never answers its pending commands, so they fail here rather than hang. */
|
|
176
|
+
forget(sessionId) {
|
|
177
|
+
const session = this.sessions.get(sessionId);
|
|
178
|
+
this.sessions.delete(sessionId);
|
|
179
|
+
for (const [id, pending] of this.pending) {
|
|
180
|
+
if (pending.sessionId !== sessionId)
|
|
181
|
+
continue;
|
|
182
|
+
this.pending.delete(id);
|
|
183
|
+
pending.reject(new ProtocolError(pending.method, 'session detached'));
|
|
184
|
+
}
|
|
185
|
+
session?.markDetached();
|
|
186
|
+
}
|
|
187
|
+
handleClose() {
|
|
188
|
+
if (this.closed)
|
|
189
|
+
return;
|
|
190
|
+
this.closed = true;
|
|
191
|
+
for (const pending of this.pending.values())
|
|
192
|
+
pending.reject(new ProtocolError(pending.method, 'connection closed'));
|
|
193
|
+
this.pending.clear();
|
|
194
|
+
for (const session of this.sessions.values())
|
|
195
|
+
session.markDetached();
|
|
196
|
+
this.sessions.clear();
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
/** One flat protocol session: the endpoint itself (an empty id) or an attached target. */
|
|
200
|
+
export class Session {
|
|
201
|
+
connection;
|
|
202
|
+
id;
|
|
203
|
+
detached = false;
|
|
204
|
+
listeners = new Map();
|
|
205
|
+
constructor(connection, id) {
|
|
206
|
+
this.connection = connection;
|
|
207
|
+
this.id = id;
|
|
208
|
+
}
|
|
209
|
+
send(method, ...params) {
|
|
210
|
+
if (this.detached)
|
|
211
|
+
return Promise.reject(new ProtocolError(method, 'session detached'));
|
|
212
|
+
return this.connection.send(method, params[0], this.id);
|
|
213
|
+
}
|
|
214
|
+
/** Listens for a protocol event of this session; returns the unsubscribe. */
|
|
215
|
+
on(event, handler) {
|
|
216
|
+
let handlers = this.listeners.get(event);
|
|
217
|
+
if (handlers === undefined) {
|
|
218
|
+
handlers = new Set();
|
|
219
|
+
this.listeners.set(event, handlers);
|
|
220
|
+
}
|
|
221
|
+
handlers.add(handler);
|
|
222
|
+
return () => void handlers.delete(handler);
|
|
223
|
+
}
|
|
224
|
+
emit(event, params) {
|
|
225
|
+
for (const handler of this.listeners.get(event) ?? [])
|
|
226
|
+
handler(params);
|
|
227
|
+
}
|
|
228
|
+
markDetached() {
|
|
229
|
+
this.detached = true;
|
|
230
|
+
this.listeners.clear();
|
|
231
|
+
}
|
|
232
|
+
}
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Trusted input over `Input.*`: a keyboard and a mouse for one page, each
|
|
3
|
+
* tracking what is held so modifiers apply to the keys and clicks after
|
|
4
|
+
* them.
|
|
5
|
+
*/
|
|
6
|
+
import type { Session } from './connection.ts';
|
|
7
|
+
type Modifier = 'Alt' | 'Control' | 'Meta' | 'Shift';
|
|
8
|
+
export type MouseButton = 'left' | 'right' | 'middle';
|
|
9
|
+
/** The page input is sent to. */
|
|
10
|
+
export interface InputTarget {
|
|
11
|
+
/** The session of the page's target. */
|
|
12
|
+
readonly session: Session;
|
|
13
|
+
}
|
|
14
|
+
/** Whether the keyboard has a key by this name: a key code (`Enter`, `Space`) or a character of the US layout. */
|
|
15
|
+
export declare function hasKey(key: string): boolean;
|
|
16
|
+
export declare class Keyboard {
|
|
17
|
+
private readonly target;
|
|
18
|
+
private readonly heldModifiers;
|
|
19
|
+
private readonly heldKeys;
|
|
20
|
+
constructor(target: InputTarget);
|
|
21
|
+
/** The modifiers held now. */
|
|
22
|
+
modifiers(): ReadonlySet<Modifier>;
|
|
23
|
+
/** Whether a modifier is held now, by any name it is pressed by (`ControlOrMeta` too). */
|
|
24
|
+
holds(modifier: string): boolean;
|
|
25
|
+
/** Forgets what is held: the renderer that held it is gone. */
|
|
26
|
+
reset(): void;
|
|
27
|
+
/** Presses a key down and leaves it held; a held modifier applies to the keys and mouse events after it. */
|
|
28
|
+
down(key: string): Promise<void>;
|
|
29
|
+
/** Releases a key `down` pressed. */
|
|
30
|
+
up(key: string): Promise<void>;
|
|
31
|
+
/** Presses a key down and releases it, under whatever modifiers are held. */
|
|
32
|
+
press(key: string): Promise<void>;
|
|
33
|
+
/** Types one character: its key when the layout has one, else the character inserted as text. */
|
|
34
|
+
type(character: string): Promise<void>;
|
|
35
|
+
/** Inserts text as an input method's commit would: input events and no key events. */
|
|
36
|
+
insertText(text: string): Promise<void>;
|
|
37
|
+
private describe;
|
|
38
|
+
/** The editing commands macOS runs for this key with the held modifiers; text insertion is left to the event's `text`. */
|
|
39
|
+
private editingCommands;
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* The page's mouse, in viewport CSS pixels. A press that moves over a
|
|
43
|
+
* draggable element starts an HTML drag, which Chromium carries through from
|
|
44
|
+
* these events alone: the moves after it are its `dragover`, and the release
|
|
45
|
+
* its `drop`.
|
|
46
|
+
*/
|
|
47
|
+
export declare class Mouse {
|
|
48
|
+
private readonly target;
|
|
49
|
+
private readonly keyboard;
|
|
50
|
+
private x;
|
|
51
|
+
private y;
|
|
52
|
+
private lastButton;
|
|
53
|
+
private readonly buttons;
|
|
54
|
+
constructor(target: InputTarget, keyboard: Keyboard);
|
|
55
|
+
/** Forgets the buttons held: the renderer that held them is gone. */
|
|
56
|
+
reset(): void;
|
|
57
|
+
move(x: number, y: number): Promise<void>;
|
|
58
|
+
/** Presses a button where the pointer is. */
|
|
59
|
+
down(button?: MouseButton, clickCount?: number): Promise<void>;
|
|
60
|
+
/** Releases a button where the pointer is. */
|
|
61
|
+
up(button?: MouseButton, clickCount?: number): Promise<void>;
|
|
62
|
+
/** Moves to a point and clicks `clickCount` times, the events sent back to back as one gesture. */
|
|
63
|
+
click(x: number, y: number, button?: MouseButton, clickCount?: number): Promise<void>;
|
|
64
|
+
/** A wheel event where the pointer is. */
|
|
65
|
+
wheel(deltaX: number, deltaY: number): Promise<void>;
|
|
66
|
+
}
|
|
67
|
+
export {};
|