@ultimat3/testing 31.49.0 → 31.50.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.
@@ -0,0 +1,91 @@
1
+ // Single responsibility: a virtual WebAuthn authenticator on one tab (CDP's `WebAuthn` domain), so a
2
+ // passkey registration and sign-in run end to end in the e2e harness with no device: the page's own
3
+ // `navigator.credentials.create/get` is answered by it, user presence and verification included.
4
+
5
+ import type { E2eTab } from './cdp-e2e-page';
6
+ import { tabPortOf } from './cdp-ports';
7
+
8
+ /** What the authenticator is. The defaults are a platform passkey: resident key, user verified. */
9
+ export interface VirtualAuthenticatorOptions {
10
+ /** Default `'internal'` — a platform authenticator, as a laptop's or a phone's. */
11
+ readonly transport?: 'internal' | 'usb' | 'nfc' | 'ble' | undefined;
12
+ /** Default `true`: discoverable credentials, what a usernameless sign-in needs. */
13
+ readonly residentKey?: boolean | undefined;
14
+ /** Default `true`: the person passes the PIN or biometric. `false` answers every UV as failed. */
15
+ readonly userVerified?: boolean | undefined;
16
+ }
17
+
18
+ /** One credential the authenticator holds, as CDP reports it. */
19
+ export interface VirtualCredential {
20
+ /** base64 of the raw credential id. */
21
+ readonly credentialId: string;
22
+ readonly rpId: string;
23
+ readonly resident: boolean;
24
+ readonly signCount: number;
25
+ /** base64 of the user handle the relying party registered; absent for a non-resident one. */
26
+ readonly userHandle: string | undefined;
27
+ }
28
+
29
+ export interface VirtualAuthenticator {
30
+ readonly id: string;
31
+ /** Every credential registered on it, in the order the browser lists them. */
32
+ credentials(): Promise<readonly VirtualCredential[]>;
33
+ /** The person's verification from here on: `false` makes the next ceremony fail UV. */
34
+ setUserVerified(verified: boolean): Promise<void>;
35
+ /** Detaches this authenticator only: another added to the same tab keeps answering ceremonies. */
36
+ remove(): Promise<void>;
37
+ }
38
+
39
+ const field = (from: unknown, key: string): unknown =>
40
+ typeof from === 'object' && from !== null ? (from as Record<string, unknown>)[key] : undefined;
41
+
42
+ const toCredential = (raw: unknown): VirtualCredential => {
43
+ const handle = field(raw, 'userHandle');
44
+ return {
45
+ credentialId: String(field(raw, 'credentialId') ?? ''),
46
+ rpId: String(field(raw, 'rpId') ?? ''),
47
+ resident: field(raw, 'isResidentCredential') === true,
48
+ signCount: Number(field(raw, 'signCount') ?? 0),
49
+ userHandle: typeof handle === 'string' ? handle : undefined,
50
+ };
51
+ };
52
+
53
+ /**
54
+ * Adds a CTAP2 authenticator to `tab` with presence simulated, so a ceremony completes with no
55
+ * prompt. Per tab: another tab, or another context's, has none until it is given one.
56
+ */
57
+ export async function addVirtualAuthenticator(
58
+ tab: E2eTab,
59
+ options: VirtualAuthenticatorOptions = {},
60
+ ): Promise<VirtualAuthenticator> {
61
+ const { connection, sessionId } = tabPortOf(tab, 'addVirtualAuthenticator');
62
+ const send = (method: string, params: Record<string, unknown> = {}) =>
63
+ connection.send(method, params, sessionId);
64
+ await send('WebAuthn.enable', { enableUI: false });
65
+ const added = await send('WebAuthn.addVirtualAuthenticator', {
66
+ options: {
67
+ protocol: 'ctap2',
68
+ ctap2Version: 'ctap2_1',
69
+ transport: options.transport ?? 'internal',
70
+ hasResidentKey: options.residentKey ?? true,
71
+ hasUserVerification: true,
72
+ isUserVerified: options.userVerified ?? true,
73
+ automaticPresenceSimulation: true,
74
+ },
75
+ });
76
+ const id = String(field(added.result, 'authenticatorId') ?? '');
77
+ return {
78
+ id,
79
+ async credentials() {
80
+ const listed = await send('WebAuthn.getCredentials', { authenticatorId: id });
81
+ const raw = field(listed.result, 'credentials');
82
+ return Array.isArray(raw) ? raw.map(toCredential) : [];
83
+ },
84
+ async setUserVerified(verified) {
85
+ await send('WebAuthn.setUserVerified', { authenticatorId: id, isUserVerified: verified });
86
+ },
87
+ async remove() {
88
+ await send('WebAuthn.removeVirtualAuthenticator', { authenticatorId: id });
89
+ },
90
+ };
91
+ }
@@ -0,0 +1,108 @@
1
+ // One key press as `Input.dispatchKeyEvent` sends it: a chord (`Shift+Tab`, `Control+k`) parsed by
2
+ // `@ultimat3/scraping`'s one grammar, its key looked up, and the down and up events built — the
3
+ // modifiers as CDP's bitmask, the text a US keyboard would type, or none under Control/Meta/Alt.
4
+
5
+ import { type KeyModifier, parseKeyChord } from '@ultimat3/scraping';
6
+ import { CdpCallFailedError } from '@ultimat3/scraping/cdp';
7
+
8
+ /** Named keys `press()` knows, with the Windows virtual key code Chrome routes them by. */
9
+ export const PRESS_KEYS: Readonly<Record<string, number>> = {
10
+ Tab: 9,
11
+ Enter: 13,
12
+ Escape: 27,
13
+ ' ': 32,
14
+ PageUp: 33,
15
+ PageDown: 34,
16
+ End: 35,
17
+ Home: 36,
18
+ ArrowLeft: 37,
19
+ ArrowUp: 38,
20
+ ArrowRight: 39,
21
+ ArrowDown: 40,
22
+ Backspace: 8,
23
+ Delete: 46,
24
+ };
25
+
26
+ /** The key code of a printable character: its upper-case code point for a letter or digit. */
27
+ const charCode = (key: string): number | undefined =>
28
+ key.length === 1 && /[a-z0-9]/i.test(key) ? key.toUpperCase().charCodeAt(0) : undefined;
29
+
30
+ /**
31
+ * The text a key TYPES, as puppeteer's key table has it. A key with text goes down as `keyDown`
32
+ * carrying it, so Chrome raises the character event — what makes Enter submit a focused button's
33
+ * form. A key with none (Tab, the arrows) goes down as `rawKeyDown`.
34
+ */
35
+ const typedText = (key: string): string | undefined =>
36
+ key === 'Enter' ? '\r' : key.length === 1 ? key : undefined;
37
+
38
+ /** `KeyboardEvent.code`: `KeyA`, `Digit7`, `Space`; a named key is its own code. */
39
+ const keyCodeName = (key: string): string =>
40
+ key === ' '
41
+ ? 'Space'
42
+ : /^[a-z]$/i.test(key)
43
+ ? `Key${key.toUpperCase()}`
44
+ : /^[0-9]$/.test(key)
45
+ ? `Digit${key}`
46
+ : key;
47
+
48
+ /** CDP's `modifiers` bits (`Input.dispatchKeyEvent`). */
49
+ const MODIFIER_BITS: ReadonlyMap<KeyModifier, number> = new Map([
50
+ ['Alt', 1],
51
+ ['Control', 2],
52
+ ['Meta', 4],
53
+ ['Shift', 8],
54
+ ]);
55
+
56
+ /** What Shift turns a digit into on a US layout; its `code` and key code stay the digit's. */
57
+ const SHIFTED_DIGITS = ')!@#$%^&*(';
58
+
59
+ /** The key Shift makes of `base`: an upper-case letter, a digit's symbol, else `base` itself. */
60
+ const shifted = (base: string): string =>
61
+ /^[a-z]$/.test(base)
62
+ ? base.toUpperCase()
63
+ : /^[0-9]$/.test(base)
64
+ ? (SHIFTED_DIGITS[Number(base)] ?? base)
65
+ : base;
66
+
67
+ export interface KeyEvents {
68
+ readonly down: Record<string, unknown>;
69
+ readonly up: Record<string, unknown>;
70
+ }
71
+
72
+ /**
73
+ * The two events one press sends. A chord's grammar is refused as `X_SCRAPE_KEY_INVALID`; a key
74
+ * outside `PRESS_KEYS`, an ASCII letter or a digit as `X_CDP_CALL_FAILED`.
75
+ */
76
+ export function keyEvents(chord: string): KeyEvents {
77
+ const parsed = parseKeyChord(chord);
78
+ const base = parsed.key;
79
+ const code = (Object.hasOwn(PRESS_KEYS, base) ? PRESS_KEYS[base] : undefined) ?? charCode(base);
80
+ if (code === undefined) {
81
+ throw new CdpCallFailedError({
82
+ method: `press(${chord})`,
83
+ detail: `not a key press() knows: one of ${Object.keys(PRESS_KEYS).join(', ')}, or one ASCII letter or digit, optionally after Alt, Control, Meta or Shift joined by +`,
84
+ });
85
+ }
86
+ const modifiers = parsed.modifiers.reduce(
87
+ (bits, name) => bits | (MODIFIER_BITS.get(name) ?? 0),
88
+ 0,
89
+ );
90
+ const key = parsed.modifiers.includes('Shift') ? shifted(base) : base;
91
+ // Control, Meta and Alt make a shortcut, not a character: no text, so nothing is typed.
92
+ const typing = parsed.modifiers.every((name) => name === 'Shift');
93
+ const text = typing ? typedText(key) : undefined;
94
+ const common = {
95
+ key,
96
+ code: keyCodeName(base),
97
+ windowsVirtualKeyCode: code,
98
+ ...(modifiers === 0 ? {} : { modifiers }),
99
+ };
100
+ return {
101
+ down: {
102
+ type: text === undefined ? 'rawKeyDown' : 'keyDown',
103
+ ...common,
104
+ ...(text === undefined ? {} : { text }),
105
+ },
106
+ up: { type: 'keyUp', ...common },
107
+ };
108
+ }
@@ -0,0 +1,55 @@
1
+ // Single responsibility: the CDP behind a tab or a session the harness built, for the free
2
+ // functions that drive a domain neither port names (`WebAuthn`, `Target.createBrowserContext`).
3
+ // Kept beside the objects rather than on them: `E2eTab` and `E2eSession` are shapes an app may
4
+ // implement, and a member added to either would be a member every hand-rolled one lacks.
5
+
6
+ import type { CdpConnection } from '@ultimat3/scraping/cdp';
7
+ import type { E2eTab } from './cdp-e2e-page';
8
+ import type { E2eSession } from './cdp-e2e-session';
9
+ import { FixtureUnavailableError } from './errors';
10
+
11
+ export interface TabPort {
12
+ readonly connection: CdpConnection;
13
+ readonly sessionId: string;
14
+ }
15
+
16
+ export interface SessionPort {
17
+ readonly connection: CdpConnection;
18
+ /** A tab in `browserContextId`'s profile, attached and audited as `newTab()`'s is. */
19
+ openTab(browserContextId: string): Promise<E2eTab>;
20
+ }
21
+
22
+ const tabs = new WeakMap<object, TabPort>();
23
+ const sessions = new WeakMap<object, SessionPort>();
24
+
25
+ export const registerTabPort = (tab: E2eTab, port: TabPort): void => {
26
+ tabs.set(tab, port);
27
+ };
28
+
29
+ export const registerSessionPort = (session: E2eSession, port: SessionPort): void => {
30
+ sessions.set(session, port);
31
+ };
32
+
33
+ /** A tab `cdpE2eTab` built; a hand-rolled one is refused by name, never driven blind. */
34
+ export function tabPortOf(tab: E2eTab, what: string): TabPort {
35
+ const port = tabs.get(tab);
36
+ if (port === undefined) {
37
+ throw new FixtureUnavailableError({
38
+ name: what,
39
+ needs: 'a tab cdpE2eTab built — e2eBrowser().page or session.newTab()',
40
+ });
41
+ }
42
+ return port;
43
+ }
44
+
45
+ /** A session `cdpE2eSession` built — `e2eBrowser().session`. */
46
+ export function sessionPortOf(session: E2eSession, what: string): SessionPort {
47
+ const port = sessions.get(session);
48
+ if (port === undefined) {
49
+ throw new FixtureUnavailableError({
50
+ name: what,
51
+ needs: 'a session cdpE2eSession built — e2eBrowser().session',
52
+ });
53
+ }
54
+ return port;
55
+ }
@@ -110,6 +110,21 @@ async function waitReady(url: string, deadlineMs: number, alive: () => boolean):
110
110
  return false;
111
111
  }
112
112
 
113
+ /**
114
+ * Before migrate a role is never ready, so its bind is proven by its first `watch` line — or it
115
+ * exits. Until this wait, a role that lost its port to another process (an outgoing Postgres
116
+ * connection's ephemeral port) between hand-out and bind died unseen and read as a failed drill
117
+ * (`ROLE=sync exited 1`, EADDRINUSE, PR #1286); now it reaches `bindFreePorts`' retry.
118
+ */
119
+ async function waitWatching(
120
+ watched: () => number,
121
+ deadlineMs: number,
122
+ alive: () => boolean,
123
+ ): Promise<void> {
124
+ const until = performance.now() + deadlineMs;
125
+ while (performance.now() < until && alive() && watched() === 0) await Bun.sleep(100);
126
+ }
127
+
113
128
  /** The fleet, ready: database created and migrated, every proxy listening, every role answering. */
114
129
  export async function startDrillFleet(options: DrillFleetOptions): Promise<DrillFleet> {
115
130
  const database = await scratchDatabase(options.services.postgres);
@@ -216,6 +231,17 @@ export async function startDrillFleet(options: DrillFleetOptions): Promise<Drill
216
231
  await child.exited;
217
232
  throw refuse(`ROLE=${role} never answered ${readyz}`, output.log());
218
233
  }
234
+ } else {
235
+ await waitWatching(
236
+ output.watched,
237
+ options.readyTimeoutMs,
238
+ () => child.exitCode === null,
239
+ );
240
+ if (child.exitCode !== null && isPortClash(output.log())) {
241
+ clashed = true;
242
+ children.delete(child);
243
+ throw refuse(`ROLE=${role} lost its port before migrate`, output.log());
244
+ }
219
245
  }
220
246
  // The sync node listens on PORT + 1 (`syncPortFor`): held too, so no other role is handed it.
221
247
  taken.push(port, metricsPort, ...(role === 'sync' ? [port + 1] : []));
@@ -0,0 +1,16 @@
1
+ // One console line an e2e page printed, as the port answers it: a `console.*` call or an uncaught
2
+ // exception. Its own file so the port (`e2e-page.ts`) and the CDP tab can share it.
3
+
4
+ /** `console.*`'s level as Chrome reports it (`console.warn` is `warning`). */
5
+ export type E2eConsoleLevel = 'debug' | 'log' | 'info' | 'warning' | 'error';
6
+
7
+ export interface E2eConsoleMessage {
8
+ readonly level: E2eConsoleLevel;
9
+ /**
10
+ * The call's raw arguments joined by one space: a primitive's value, an object's description. No
11
+ * format substitution — `console.log('n: %d', 2)` is `n: %d 2` — so assert on a fragment.
12
+ */
13
+ readonly text: string;
14
+ /** `console` for a `console.*` call; `exception` for a throw nothing caught (always `error`). */
15
+ readonly source: 'console' | 'exception';
16
+ }
package/src/e2e-driver.ts CHANGED
@@ -7,6 +7,7 @@ import type { A11yOptions, A11yRun } from './e2e-a11y-run';
7
7
  import { checkAllow, startA11yRun } from './e2e-a11y-run';
8
8
  import type { E2eBrowserPage, E2ePageOptions } from './e2e-page';
9
9
  import { e2ePage } from './e2e-page';
10
+ import { markConsoleStart } from './e2e-page-input';
10
11
  import { FixtureUnavailableError } from './errors';
11
12
  import { withFailureContext } from './failure-context';
12
13
  import { unavailableFixture } from './fixture-drivers';
@@ -99,6 +100,8 @@ export function e2eRunner(options: E2eDriverOptions): E2eRunner {
99
100
  try {
100
101
  const current = startA11yRun(options.page, checkAllow(a11y), reported);
101
102
  audit = current;
103
+ // The console a test reads begins with the test: a tab shared by the suite carries the last one's.
104
+ await markConsoleStart(page);
102
105
  await body(e2eFixtures(page, options.page, options.newBuild));
103
106
  await current.check();
104
107
  current.verdict();
@@ -132,7 +135,11 @@ export function installE2eDriver(options: E2eDriverOptions): () => void {
132
135
  const { page, run } = e2eRunner(options);
133
136
  const newBuild = options.newBuild;
134
137
  defineFixtures({
135
- page: () => page,
138
+ // Built once per test: the plain `{ page }` fixture's console begins with its test too.
139
+ page: async () => {
140
+ await markConsoleStart(page);
141
+ return page;
142
+ },
136
143
  ...(newBuild === undefined ? {} : { deploy: () => ({ newBuild }) }),
137
144
  });
138
145
  useE2eDriver((name, body: E2eBody, test) => {
@@ -1,4 +1,4 @@
1
- // The registry for the browser-backed e2e driver's codes: the seven `X_E2E_*` a page refuses with,
1
+ // The registry for the browser-backed e2e driver's codes: the eight `X_E2E_*` a page refuses with,
2
2
  // registered here (not in `errors.ts`, which sits at its ceiling). The four `X_CDP_*` its raw-CDP
3
3
  // browser refuses with are `@ultimat3/scraping/cdp`'s since 31.0.0 — listed here, registered there.
4
4
  import { registerErrorCodes } from '@ultimat3/core';
@@ -12,11 +12,12 @@ const OWN_E2E_CODES = [
12
12
  'X_E2E_LOCATOR_AMBIGUOUS',
13
13
  'X_E2E_SERVICE_WORKER_ABSENT',
14
14
  'X_E2E_APP_FAILED',
15
+ 'X_E2E_CONSOLE_ERRORS',
15
16
  ] as const;
16
17
 
17
18
  type OwnE2eCode = (typeof OWN_E2E_CODES)[number];
18
19
 
19
- /** Every code an e2e run can refuse with: this package's seven, then the browser's four. */
20
+ /** Every code an e2e run can refuse with: this package's eight, then the browser's four. */
20
21
  export const E2E_ERROR_CODES = [...OWN_E2E_CODES, ...CDP_ERROR_CODES] as const;
21
22
 
22
23
  export type E2eErrorCode = (typeof E2E_ERROR_CODES)[number];
@@ -29,6 +30,7 @@ const OWN_E2E_TITLES = Object.freeze<Record<OwnE2eCode, string>>({
29
30
  X_E2E_LOCATOR_AMBIGUOUS: 'an e2e locator matched more than one element and was asked to click',
30
31
  X_E2E_SERVICE_WORKER_ABSENT: 'no service worker took control of the page within the budget',
31
32
  X_E2E_APP_FAILED: 'the app an e2e run spawned did not come up',
33
+ X_E2E_CONSOLE_ERRORS: 'the page printed a console error or threw an uncaught exception',
32
34
  });
33
35
 
34
36
  export const E2E_ERROR_TITLES = Object.freeze<Record<E2eErrorCode, string>>({
package/src/e2e-errors.ts CHANGED
@@ -164,3 +164,18 @@ export class E2eAppFailedError extends UltimateError {
164
164
  this.inner = inner;
165
165
  }
166
166
  }
167
+
168
+ /**
169
+ * The page printed an error, or threw one nothing caught, while the test ran. Every such line is
170
+ * quoted back at once, so one run shows them all rather than one per fix.
171
+ */
172
+ export class E2eConsoleErrorsError extends UltimateError {
173
+ constructor(input: { readonly errors: readonly string[]; readonly url: string }) {
174
+ const listed = input.errors.map((text) => renderCauseValue(text)).join('; ');
175
+ super({
176
+ code: 'X_E2E_CONSOLE_ERRORS',
177
+ cause: `the page printed ${String(input.errors.length)} console error(s) during this test: ${listed}`,
178
+ fix: `x dev # then open ${renderFixLiteral(input.url, URL_PLACEHOLDER)} with the browser console open; each error is the page's to fix`,
179
+ });
180
+ }
181
+ }
@@ -0,0 +1,80 @@
1
+ // Key presses and the console, for the page an e2e test holds. Free functions over `PageLike`
2
+ // rather than members of it, so no implementation of that interface has to grow: each reaches the
3
+ // browser port `e2ePage()` was built over, and refuses by name when that port cannot.
4
+
5
+ import type { E2eConsoleMessage } from './e2e-console';
6
+ import { E2eConsoleErrorsError } from './e2e-errors';
7
+ import type { E2eBrowserPage } from './e2e-page';
8
+ import { FixtureUnavailableError } from './errors';
9
+ import type { PageLike } from './test-types';
10
+
11
+ /** A WeakMap, so a page nobody holds any more is not kept alive by having been bound. */
12
+ const bindings = new WeakMap<PageLike, E2eBrowserPage>();
13
+
14
+ const DRIVER_PAGE = "the page e2eTest or a test's `{ page }` fixture hands you";
15
+
16
+ /** Called by `e2ePage()`: the page it answers, and the port behind it. */
17
+ export function bindPagePort(page: PageLike, port: E2eBrowserPage): void {
18
+ bindings.set(page, port);
19
+ }
20
+
21
+ const portOf = (page: PageLike, call: string, member: string): E2eBrowserPage => {
22
+ const port = bindings.get(page);
23
+ if (port === undefined) throw new FixtureUnavailableError({ name: call, needs: DRIVER_PAGE });
24
+ if (port[member as keyof E2eBrowserPage] === undefined) {
25
+ throw new FixtureUnavailableError({
26
+ name: call,
27
+ needs: `a page whose driver implements ${member}() — cdpE2eTab does; a hand-rolled E2eBrowserPage may not`,
28
+ });
29
+ }
30
+ return port;
31
+ };
32
+
33
+ /**
34
+ * A REAL key press at whatever has focus, so its default action runs (Tab moves focus, Enter
35
+ * submits): a key name (`Tab`, `Enter`, `Escape`, the arrows …), one letter or digit, or a chord
36
+ * with modifiers held (`Shift+Tab`, `Control+k`, `Meta+Shift+Enter`).
37
+ */
38
+ export async function pressKey(page: PageLike, key: string): Promise<void> {
39
+ const port = portOf(page, 'pressKey', 'press');
40
+ await port.press?.(key);
41
+ }
42
+
43
+ /**
44
+ * Starts the running test's console: the e2e driver calls it as each test starts, on `e2eTest` and
45
+ * on the `{ page }` fixture alike. One round trip first, so a line the previous test printed that
46
+ * is still in flight lands before the clear, never in this test.
47
+ */
48
+ export async function markConsoleStart(page: PageLike): Promise<void> {
49
+ const port = bindings.get(page);
50
+ if (port?.clearConsole === undefined) return;
51
+ await port.evaluate('0');
52
+ port.clearConsole();
53
+ }
54
+
55
+ /**
56
+ * Every console line and uncaught exception since the running test began. One round trip to the
57
+ * page first: the browser sends each console event before the reply to a later call, so a line
58
+ * printed just before this call is in the answer.
59
+ */
60
+ export async function consoleMessages(page: PageLike): Promise<readonly E2eConsoleMessage[]> {
61
+ const port = portOf(page, 'consoleMessages', 'consoleMessages');
62
+ // Without a reset the log is the whole tab's, and a previous test's error would fail this one.
63
+ portOf(page, 'consoleMessages', 'clearConsole');
64
+ await port.evaluate('0');
65
+ return port.consoleMessages?.() ?? [];
66
+ }
67
+
68
+ /**
69
+ * Refuses with `X_E2E_CONSOLE_ERRORS`, quoting each, when the page printed `console.error` (or a
70
+ * failed `console.assert`) or threw an uncaught exception since the running test began. Warnings
71
+ * and logs pass; filter `consoleMessages(page)` for a stricter or looser rule.
72
+ */
73
+ export async function expectNoConsoleErrors(page: PageLike): Promise<void> {
74
+ const errors = (await consoleMessages(page)).filter((message) => message.level === 'error');
75
+ if (errors.length === 0) return;
76
+ throw new E2eConsoleErrorsError({
77
+ errors: errors.map((message) => message.text),
78
+ url: page.url(),
79
+ });
80
+ }
package/src/e2e-page.ts CHANGED
@@ -4,8 +4,10 @@
4
4
 
5
5
  import { finiteCount } from '@ultimat3/core';
6
6
  import type { AxTreeNode } from './ax-node';
7
+ import type { E2eConsoleMessage } from './e2e-console';
7
8
  import { evaluateClosure } from './e2e-evaluate';
8
9
  import { e2eLocator } from './e2e-locator';
10
+ import { bindPagePort } from './e2e-page-input';
9
11
  import type { E2eSelection } from './e2e-selection';
10
12
  import { callBudget, waitForServiceWorker } from './e2e-service-worker';
11
13
  import type { LocatorLike, PageLike } from './test-types';
@@ -40,6 +42,19 @@ export interface E2eBrowserPage {
40
42
  * (`e2e-a11y-run.ts`) rather than passing a page nothing audited.
41
43
  */
42
44
  accessibilityTree?(request: AxTreeRequest): Promise<readonly AxTreeNode[]>;
45
+ /**
46
+ * A real key press at the focused element, or a chord (`Shift+Tab`, `Control+k`): what
47
+ * `pressKey(page, key)` forwards to. OPTIONAL as `offline` is; absent, `pressKey` refuses by name.
48
+ */
49
+ press?(key: string): Promise<void>;
50
+ /**
51
+ * Every console line and uncaught exception the page has printed since `clearConsole()` (or since
52
+ * this port was built), in order: what `consoleMessages(page)` reads. OPTIONAL as `offline` is;
53
+ * absent, it refuses by name.
54
+ */
55
+ consoleMessages?(): readonly E2eConsoleMessage[];
56
+ /** Forget the console held so far: the e2e driver calls it as each test starts. */
57
+ clearConsole?(): void;
43
58
  }
44
59
 
45
60
  /** What the audit asks of one tree read: which nodes to describe, and the selectors to test. */
@@ -163,7 +178,7 @@ export function e2ePage(options: E2ePageOptions): PageLike {
163
178
  return answer;
164
179
  };
165
180
 
166
- return {
181
+ const adapted: PageLike = {
167
182
  url: () => page.url(),
168
183
  goto: (url) => settled(page.goto(absolute(url), { timeout })),
169
184
  // The page's OWN url, re-read at call time: a reload of the url the adapter was built with
@@ -198,4 +213,6 @@ export function e2ePage(options: E2ePageOptions): PageLike {
198
213
  }),
199
214
  getByText: (text) => locate({ kind: 'text', text, first: false }),
200
215
  };
216
+ bindPagePort(adapted, page);
217
+ return adapted;
201
218
  }
@@ -0,0 +1,134 @@
1
+ // Character references back to characters, for the visible text a render test compares with a
2
+ // catalog string: every numeric reference, and the named ones copy commonly carries.
3
+
4
+ /** A `Map`, so a lookup never reaches `Object.prototype` (`bun run proto-index`). */
5
+ const NAMED: ReadonlyMap<string, string> = new Map([
6
+ ['amp', '&'],
7
+ ['lt', '<'],
8
+ ['gt', '>'],
9
+ ['quot', '"'],
10
+ ['apos', "'"],
11
+ ['nbsp', ' '],
12
+ ['copy', '©'],
13
+ ['reg', '®'],
14
+ ['trade', '™'],
15
+ ['hellip', '…'],
16
+ ['ndash', '–'],
17
+ ['mdash', '—'],
18
+ ['lsquo', '‘'],
19
+ ['rsquo', '’'],
20
+ ['ldquo', '“'],
21
+ ['rdquo', '”'],
22
+ ['laquo', '«'],
23
+ ['raquo', '»'],
24
+ ['middot', '·'],
25
+ ['bull', '•'],
26
+ ['deg', '°'],
27
+ ['times', '×'],
28
+ ['euro', '€'],
29
+ ['pound', '£'],
30
+ ['yen', '¥'],
31
+ ['cent', '¢'],
32
+ ['sect', '§'],
33
+ ]);
34
+
35
+ /**
36
+ * The names the HTML standard also reads WITHOUT a semicolon in text (its legacy list), among
37
+ * those the table holds: `&amp` renders `&`, `&copy2026` renders `©2026`.
38
+ */
39
+ const LEGACY = [
40
+ 'amp',
41
+ 'lt',
42
+ 'gt',
43
+ 'quot',
44
+ 'nbsp',
45
+ 'copy',
46
+ 'reg',
47
+ 'laquo',
48
+ 'raquo',
49
+ 'middot',
50
+ 'deg',
51
+ 'times',
52
+ 'pound',
53
+ 'yen',
54
+ 'cent',
55
+ 'sect',
56
+ ] as const;
57
+
58
+ /** A numeric reference's semicolon is optional, as a browser reads it; a named one's is not. */
59
+ const REFERENCE = /&(?:#(\d+);?|#[xX]([0-9a-fA-F]+);?|([a-zA-Z][a-zA-Z0-9]*)(;?))/g;
60
+
61
+ /**
62
+ * `&#128;`–`&#159;` name the windows-1252 characters there, not C1 controls: the HTML standard's
63
+ * numeric reference table, which is what a browser renders (`&#128;` is `€`).
64
+ */
65
+ const WINDOWS_1252: ReadonlyMap<number, number> = new Map([
66
+ [0x80, 0x20ac],
67
+ [0x82, 0x201a],
68
+ [0x83, 0x0192],
69
+ [0x84, 0x201e],
70
+ [0x85, 0x2026],
71
+ [0x86, 0x2020],
72
+ [0x87, 0x2021],
73
+ [0x88, 0x02c6],
74
+ [0x89, 0x2030],
75
+ [0x8a, 0x0160],
76
+ [0x8b, 0x2039],
77
+ [0x8c, 0x0152],
78
+ [0x8e, 0x017d],
79
+ [0x91, 0x2018],
80
+ [0x92, 0x2019],
81
+ [0x93, 0x201c],
82
+ [0x94, 0x201d],
83
+ [0x95, 0x2022],
84
+ [0x96, 0x2013],
85
+ [0x97, 0x2014],
86
+ [0x98, 0x02dc],
87
+ [0x99, 0x2122],
88
+ [0x9a, 0x0161],
89
+ [0x9b, 0x203a],
90
+ [0x9c, 0x0153],
91
+ [0x9e, 0x017e],
92
+ [0x9f, 0x0178],
93
+ ]);
94
+
95
+ /** What the HTML standard reads in place of a null, a surrogate or a code point past Unicode. */
96
+ const REPLACEMENT = '�';
97
+
98
+ const fromCodePoint = (point: number): string =>
99
+ point === 0 || point > 0x10ffff || (point >= 0xd800 && point <= 0xdfff)
100
+ ? REPLACEMENT
101
+ : String.fromCodePoint(WINDOWS_1252.get(point) ?? point);
102
+
103
+ /** `&name` with no semicolon: the longest legacy name it starts with, the rest kept as text. */
104
+ function legacyPrefix(whole: string, name: string): string {
105
+ let longest = '';
106
+ for (const legacy of LEGACY) {
107
+ if (name.startsWith(legacy) && legacy.length > longest.length) longest = legacy;
108
+ }
109
+ if (longest === '') return whole;
110
+ return (NAMED.get(longest) ?? '') + name.slice(longest.length);
111
+ }
112
+
113
+ /**
114
+ * One pass, so a decoded `&` never starts another reference: the text `&amp;lt;` — an author's
115
+ * literal `&lt;` — reads `&lt;`, never `<`. A name outside the table stays as written, and so does
116
+ * a semicolon-less name outside the legacy list.
117
+ */
118
+ export function decodeHtmlEntities(text: string): string {
119
+ return text.replace(
120
+ REFERENCE,
121
+ (
122
+ whole,
123
+ decimal: string | undefined,
124
+ hex: string | undefined,
125
+ name: string | undefined,
126
+ semicolon: string | undefined,
127
+ ) => {
128
+ if (decimal !== undefined) return fromCodePoint(Number.parseInt(decimal, 10));
129
+ if (hex !== undefined) return fromCodePoint(Number.parseInt(hex, 16));
130
+ if (semicolon === '') return legacyPrefix(whole, name ?? '');
131
+ return NAMED.get(name ?? '') ?? whole;
132
+ },
133
+ );
134
+ }