@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.
package/README.md CHANGED
@@ -76,6 +76,7 @@ unitTest('the clock moves only when the test moves it', ({ clock }) => {
76
76
  | `matchers.ts` | `toBeUltimateError` `toDenyPolicy` `toEmitSteps` `toMatchOpenApi` `toBeWithinBudget` `toRejectInput` `toAcceptInput` `toEqualRow` `toBeVisible` |
77
77
  | `matchers-steps.ts` | `recordSteps` — behind `toEmitSteps`: the job's real arguments (a worker `ctx`, ambient too, `attempt` 1, `progress`, `runId`), a never-aborted signal per step body; `waitForEvent` is a recorded step that times out (`undefined`, or `X_JOB_TIMEOUT` when `required`); `sleep` returns at once and is no step |
78
78
  | `matcher-row.ts` | `toEqualRow` — equality over every OWN property, so a `.sealed()` column (not enumerable on a repository row) is compared; a server-only difference is named, never printed |
79
+ | `app-assets.ts` | the app's site asset table installed into `asset()` (Sass `asset()` included) when the run's root is an app, again at every file boundary — installed by the preload, exported from nowhere |
79
80
  | `test-seal-key.ts` | the throwaway master key a test process seals under when the app has none — installed by the preload, handed to the app `startE2eApp` spawns, exported from nowhere |
80
81
  | `local-tx.ts` | `memoryLocalTx()` — the client store a mutator's `local()` half writes into under test, with the record store's own rules |
81
82
  | `render-view.ts` | `renderView()` / `renderRoute()` — what the server renders, for a unit test: one component, or a whole route module with its `load`, `meta` and islands |
@@ -367,7 +368,11 @@ fixture that silently no-opped would make the assertion after it read as proof.
367
368
  **Real input, `As of 2026-11`.** A raw-CDP tab (`cdpE2eTab`, the `E2eTab` the framework implements)
368
369
  sends trusted input the page cannot forge: `tab.touchDrag(from, to, steps)` is a finger
369
370
  (`Input.dispatchTouchEvent`, touch emulation on once per tab) and `tab.press(key)` a key
370
- (`Input.dispatchKeyEvent`, so Tab really moves focus) — a key from `PRESS_KEYS`, a letter or a digit.
371
+ (`Input.dispatchKeyEvent`, so Tab really moves focus) — a key from `PRESS_KEYS`, a letter or a digit,
372
+ optionally a chord with `Alt`, `Control`, `Meta` or `Shift` held (`Shift+Tab`, `Control+k`). The tab
373
+ also keeps its console (`tab.consoleMessages()`, `tab.clearConsole()`: every `console.*` call and uncaught exception, cross-site iframes included; 1,000 lines of 2,000 characters at most, oldest non-error dropped first).
374
+ An app's e2e test reaches both through its `page`: `pressKey(page, key)`, `consoleMessages(page)`
375
+ (since the running test began) and `expectNoConsoleErrors(page)` (`X_E2E_CONSOLE_ERRORS`).
371
376
  A touch `PointerEvent` dispatched from page script is refused by `setPointerCapture`, so a drag
372
377
  proven that way proves nothing; `TouchPoint` is the `{ x, y }` both ends take.
373
378
 
@@ -789,11 +794,11 @@ unitTest('the shell keeps the page in <main>', async () => {
789
794
 
790
795
  | | |
791
796
  |---|---|
792
- | **`renderRoute(module, { url?, params?, actor? })`** | the route module passed WHOLE (`import * as page`), so the page is found by the router's own rule (`pageComponentOf`). `load` runs once; `meta` and the page are handed that one object; islands are collected under the route's own `hydrate` |
797
+ | **`renderRoute(module, { url?, params?, actor? })`** | the route module passed WHOLE (`import * as page`), so the page is found by the router's own rule (`pageComponentOf`). `load` runs once; `meta` and the page are handed that one object; islands are collected under the route's own `hydrate`. A `url` whose first segment is a routed locale (`/es/…`) renders in that locale, as the router reads the prefix |
793
798
  | **`renderView(Component, props)`** | one component. `props` is the component's own type — a renamed prop is a compile error in the test. A component that renders an `island()` is refused here: its timing is a route's |
794
799
  | **`view.html`** | the markup as the document carries it |
795
- | **`view.text`** | what a reader sees: tags, `<script>` and `<style>` bodies removed, entities decoded, whitespace collapsed. Compare with `t('<key>')` — markup escapes what the catalog does not |
796
- | **`actor`** | `load` and the page run inside `runWithContext(ctxOf({ actor }))`. Without one they run outside any request context, as a static page does |
800
+ | **`view.text`** | what a reader sees: tags, `<script>` and `<style>` bodies removed, character references decoded (every numeric one, and the common named ones: `&quot;`, `&apos;`, `&nbsp;`, typographic quotes and dashes, `&hellip;` …) as a browser reads them (`&#39` and `&amp` with no semicolon, `&#128;` as `€`), whitespace collapsed but a no-break space kept. Compare with `t('<key>')` — markup escapes what the catalog does not |
801
+ | **`actor`** | `load` and the page run inside `runWithContext(ctxOf({ actor }))`. With neither an actor nor a routed locale prefix in `url`, they run outside any request context, as a static page does; a `/es/…` prefix alone opens one holding that locale |
797
802
  | **the file stays `.test.ts`** | no JSX in a test: the registry-leak guard's loader covers `.test.ts` only, and children that need markup are a string |
798
803
 
799
804
  `@ultimat3/render` is imported inside the two functions, so the barrel still loads no renderer.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ultimat3/testing",
3
- "version": "31.49.0",
3
+ "version": "31.50.0",
4
4
  "description": "Test harness: cloned template DBs per worker, frozen clock, sealed network, 6 test types",
5
5
  "keywords": [
6
6
  "ultimate",
@@ -47,27 +47,27 @@
47
47
  "test": "bun test"
48
48
  },
49
49
  "dependencies": {
50
- "@ultimat3/action": "31.49.0",
51
- "@ultimat3/ai": "31.49.0",
52
- "@ultimat3/auth": "31.49.0",
53
- "@ultimat3/cache": "31.49.0",
54
- "@ultimat3/core": "31.49.0",
55
- "@ultimat3/db": "31.49.0",
56
- "@ultimat3/entity": "31.49.0",
57
- "@ultimat3/http": "31.49.0",
58
- "@ultimat3/i18n": "31.49.0",
59
- "@ultimat3/jobs": "31.49.0",
60
- "@ultimat3/mail": "31.49.0",
61
- "@ultimat3/notify": "31.49.0",
62
- "@ultimat3/policy": "31.49.0",
63
- "@ultimat3/pwa": "31.49.0",
64
- "@ultimat3/query": "31.49.0",
65
- "@ultimat3/realtime": "31.49.0",
66
- "@ultimat3/render": "31.49.0",
67
- "@ultimat3/schema": "31.49.0",
68
- "@ultimat3/scraping": "31.49.0",
69
- "@ultimat3/seo": "31.49.0",
70
- "@ultimat3/time": "31.49.0"
50
+ "@ultimat3/action": "31.50.0",
51
+ "@ultimat3/ai": "31.50.0",
52
+ "@ultimat3/auth": "31.50.0",
53
+ "@ultimat3/cache": "31.50.0",
54
+ "@ultimat3/core": "31.50.0",
55
+ "@ultimat3/db": "31.50.0",
56
+ "@ultimat3/entity": "31.50.0",
57
+ "@ultimat3/http": "31.50.0",
58
+ "@ultimat3/i18n": "31.50.0",
59
+ "@ultimat3/jobs": "31.50.0",
60
+ "@ultimat3/mail": "31.50.0",
61
+ "@ultimat3/notify": "31.50.0",
62
+ "@ultimat3/policy": "31.50.0",
63
+ "@ultimat3/pwa": "31.50.0",
64
+ "@ultimat3/query": "31.50.0",
65
+ "@ultimat3/realtime": "31.50.0",
66
+ "@ultimat3/render": "31.50.0",
67
+ "@ultimat3/schema": "31.50.0",
68
+ "@ultimat3/scraping": "31.50.0",
69
+ "@ultimat3/seo": "31.50.0",
70
+ "@ultimat3/time": "31.50.0"
71
71
  },
72
72
  "peerDependencies": {
73
73
  "solid-js": "^1.9.18"
@@ -0,0 +1,20 @@
1
+ // The app's site asset table, installed into `asset()` in a test process the way the app's boot
2
+ // installs it: a page, a component or a stylesheet whose Sass calls `asset()` resolves to the same
3
+ // hashed URL in a unit test as in `x dev`, and a file the app does not hold is still refused.
4
+
5
+ import { setAssetResolver } from '@ultimat3/render';
6
+ import { siteAssetTable } from '@ultimat3/render/server';
7
+ import { isAppRoot } from './app-root';
8
+
9
+ /**
10
+ * Installs `root`'s table and answers `true`, or answers `false` and installs nothing where `root`
11
+ * is not an app (the framework's own suites). The preload calls it once and again at every file
12
+ * boundary, so a test that installed its own resolver and handed the slot back with
13
+ * `setAssetResolver(undefined)` leaves the next file the app's table, not none.
14
+ */
15
+ export function installAppAssets(root: string = process.cwd()): boolean {
16
+ if (!isAppRoot(root)) return false;
17
+ const table = siteAssetTable(root);
18
+ setAssetResolver((path) => table.resolve(path).url);
19
+ return true;
20
+ }
@@ -1,6 +1,7 @@
1
1
  // `PasskeyStore`, for `authAdapterConformance`: a credential id is globally unique, the counter
2
2
  // advances by compare-and-set (two racing assertions must not both move it — the cloned-
3
- // authenticator signal), a delete is the owner's, and a challenge is single-use for its ceremony.
3
+ // authenticator signal), a delete and a rename are the owner's, and a challenge is single-use for
4
+ // its ceremony.
4
5
 
5
6
  import { expect } from 'bun:test';
6
7
  import type { PasskeyChallengeRecord, PasskeyCredential, PasskeyEvidence } from '@ultimat3/auth';
@@ -97,6 +98,28 @@ export const AUTH_ADAPTER_PASSKEY_CHECKS: readonly AuthAdapterCheck[] = [
97
98
  expect(await adapter.findPasskey(row.id)).toBeNull();
98
99
  },
99
100
  },
101
+ {
102
+ // `renamePasskey` and the label are optional on the seam: an adapter written before them is
103
+ // refused per call (`X_PASSKEY_RENAME_UNSUPPORTED`), so nothing here is asked of it at all.
104
+ name: 'a label round-trips, and a passkey is renamed only by its owner, its use kept',
105
+ async run({ adapter }) {
106
+ if (adapter.renamePasskey === undefined) return;
107
+ const [ada, grace] = [await seedUser(adapter), await seedUser(adapter)];
108
+ const seeded = { ...credential(ada, 3), label: 'Work laptop' };
109
+ await adapter.putPasskey(seeded);
110
+ expect(await adapter.findPasskey(seeded.id)).toEqual(seeded);
111
+ // A use recorded first, so a rename that rewrote the counter or the last use shows.
112
+ expect(await adapter.advancePasskeyCounter(seeded.id, 3, 4, later(5))).toBe(true);
113
+ const row = { ...seeded, signCount: 4, lastUsedAt: later(5) };
114
+ expect(await adapter.renamePasskey(grace, row.id, 'Mine')).toBeNull();
115
+ expect(await adapter.findPasskey(row.id)).toEqual(row);
116
+ expect(await adapter.renamePasskey(ada, row.id, 'Phone')).toEqual({ ...row, label: 'Phone' });
117
+ expect(await adapter.findPasskey(row.id)).toEqual({ ...row, label: 'Phone' });
118
+ const { label: _cleared, ...unnamed } = row;
119
+ expect(await adapter.renamePasskey(ada, row.id, null)).toEqual(unnamed);
120
+ expect(await adapter.findPasskey(row.id)).toEqual(unnamed);
121
+ },
122
+ },
100
123
  {
101
124
  name: 'a challenge is taken once, and only for its own ceremony',
102
125
  async run({ adapter }) {
@@ -130,6 +130,77 @@ export const AUTH_SERVER_STORE_CHECKS: readonly AuthServerStoreCheck[] = [
130
130
  expect((await store.getGrant(g1))?.revokedAt?.getTime()).toBe(at(1).getTime());
131
131
  },
132
132
  },
133
+ {
134
+ // Optional on the port: a store without it counts a per-grant revoke on its read.
135
+ name: 'revokeLiveGrant answers true only for the write that ended a live grant',
136
+ async run(store) {
137
+ if (store.revokeLiveGrant === undefined) return;
138
+ const subject = idOf('subject');
139
+ const [live, gone, sibling] = [idOf('live'), idOf('gone'), idOf('sibling')];
140
+ await store.putGrant(grantRecord(live, subject));
141
+ // The subject's other grant: ending one by id must leave it live.
142
+ await store.putGrant(grantRecord(sibling, subject));
143
+ const ended = [
144
+ await store.revokeLiveGrant(live, at(1)),
145
+ await store.revokeLiveGrant(live, at(5)),
146
+ ];
147
+ expect(ended).toEqual([true, false]);
148
+ expect((await store.getGrant(live))?.revokedAt?.getTime()).toBe(at(1).getTime());
149
+ expect(await store.revokeLiveGrant(gone, at(6))).toBe(false);
150
+ // Overlapping calls: one conditional write wins, so exactly one answers true.
151
+ const raced = idOf('raced');
152
+ await store.putGrant(grantRecord(raced, subject));
153
+ const both = await Promise.all([
154
+ store.revokeLiveGrant(raced, at(7)),
155
+ store.revokeLiveGrant(raced, at(8)),
156
+ ]);
157
+ expect(both.filter(Boolean)).toHaveLength(1);
158
+ // The losing call writes nothing: the stored time is the winner's.
159
+ const winner = both[0] ? at(7) : at(8);
160
+ expect((await store.getGrant(raced))?.revokedAt?.getTime()).toBe(winner.getTime());
161
+ expect((await store.getGrant(sibling))?.revokedAt).toBeNull();
162
+ },
163
+ },
164
+ {
165
+ // Optional on the port: a store without `liveGrants` answers `grants()` with a refusal of its
166
+ // own, so there is nothing here to hold it to.
167
+ name: "liveGrants lists a subject's grants holding a usable token, oldest first, one client or all",
168
+ async run(store) {
169
+ if (store.liveGrants === undefined) return;
170
+ const subject = idOf('subject');
171
+ const [older, newer, other, bare, revoked, spent] = [
172
+ idOf('older'),
173
+ idOf('newer'),
174
+ idOf('other'),
175
+ idOf('bare'),
176
+ idOf('revoked'),
177
+ idOf('spent'),
178
+ ];
179
+ await store.putGrant({ ...grantRecord(newer, subject), createdAt: at(5) });
180
+ await store.putGrant(grantRecord(older, subject));
181
+ await store.putGrant({ ...grantRecord(other, subject, 'c2'), createdAt: at(7) });
182
+ await store.putGrant(grantRecord(bare, subject));
183
+ await store.putGrant(grantRecord(revoked, subject));
184
+ await store.putGrant(grantRecord(spent, subject));
185
+ for (const grant of [older, newer, other, revoked]) {
186
+ await store.putToken(tokenRecord(idOf('token'), grant));
187
+ }
188
+ const retired = idOf('retired');
189
+ await store.putToken(tokenRecord(retired, spent));
190
+ await store.rotateRefresh(
191
+ retired,
192
+ { ...tokenRecord(idOf('next'), spent), expiresAt: at(1) },
193
+ at(1),
194
+ );
195
+ await store.revokeGrant(revoked, at(1));
196
+ const ids = async (clientId?: string) =>
197
+ (await store.liveGrants?.({ subject, clientId }, at(10)))?.map((grant) => grant.id);
198
+ expect(await ids()).toEqual([older, newer, other]);
199
+ expect(await ids('c2')).toEqual([other]);
200
+ expect(await store.liveGrants({ subject: idOf('nobody') }, at(10))).toEqual([]);
201
+ expect(await store.liveGrants({ subject }, at(3600))).toEqual([]);
202
+ },
203
+ },
133
204
  {
134
205
  name: 'touchGrant restarts the idle window',
135
206
  async run(store) {
@@ -0,0 +1,112 @@
1
+ // One tab's console over a raw CDP session: every `Runtime.consoleAPICalled` and
2
+ // `Runtime.exceptionThrown` its session, or a cross-site frame attached under it, sends — kept
3
+ // since the last `clear()`, bounded in lines and in characters per line, until the tab closes.
4
+
5
+ import type { CdpConnection } from '@ultimat3/scraping/cdp';
6
+ import type { E2eConsoleLevel, E2eConsoleMessage } from './e2e-console';
7
+
8
+ /** The most lines one capture holds: a tab nobody clears logs for a whole suite. */
9
+ export const CONSOLE_KEEP = 1_000;
10
+
11
+ /** The most characters one line keeps, so the bound above is a bound on memory too. */
12
+ export const CONSOLE_LINE_CHARS = 2_000;
13
+
14
+ const clipped = (text: string): string =>
15
+ text.length > CONSOLE_LINE_CHARS ? `${text.slice(0, CONSOLE_LINE_CHARS)}…` : text;
16
+
17
+ export interface ConsoleCapture {
18
+ messages(): readonly E2eConsoleMessage[];
19
+ /** Forget everything held so far. Constant time. */
20
+ clear(): void;
21
+ stop(): void;
22
+ }
23
+
24
+ const record = (value: unknown): Record<string, unknown> | undefined =>
25
+ typeof value === 'object' && value !== null ? (value as Record<string, unknown>) : undefined;
26
+
27
+ /**
28
+ * A `Runtime.RemoteObject` as its raw argument: a primitive's value, else its description. No
29
+ * format substitution — `console.log('n: %d', 2)` is `n: %d 2`, not what DevTools prints.
30
+ */
31
+ const shown = (arg: unknown): string | undefined => {
32
+ const remote = record(arg);
33
+ const value = remote?.['value'];
34
+ if (typeof value === 'string') return value;
35
+ if (value !== undefined) return JSON.stringify(value);
36
+ const described = remote?.['description'] ?? remote?.['unserializableValue'] ?? remote?.['type'];
37
+ return typeof described === 'string' ? described : undefined;
38
+ };
39
+
40
+ /** Chrome's `consoleAPICalled.type` folded onto the five levels a console filter shows. */
41
+ const levelOf = (type: unknown): E2eConsoleLevel => {
42
+ if (type === 'error' || type === 'assert') return 'error';
43
+ if (type === 'warning') return 'warning';
44
+ if (type === 'info') return 'info';
45
+ if (type === 'debug') return 'debug';
46
+ return 'log';
47
+ };
48
+
49
+ export function captureConsole(connection: CdpConnection, sessionId: string): ConsoleCapture {
50
+ let messages: E2eConsoleMessage[] = [];
51
+ // The tab's own session and the out-of-process frames attached under it: a cross-site iframe
52
+ // reports its console on its own session, and its errors are this page's errors.
53
+ const sessions = new Set([sessionId]);
54
+ // Past the bound the oldest NON-error goes first, so an error is never what makes room while
55
+ // anything else is held: `expectNoConsoleErrors` keeps its verdict on a noisy page.
56
+ const keep = (message: E2eConsoleMessage): void => {
57
+ messages.push({ ...message, text: clipped(message.text) });
58
+ if (messages.length <= CONSOLE_KEEP) return;
59
+ const quieter = messages.findIndex((held) => held.level !== 'error');
60
+ messages.splice(quieter === -1 ? 0 : quieter, 1);
61
+ };
62
+ const offs = [
63
+ connection.on('Target.attachedToTarget', (params, on) => {
64
+ const child = params['sessionId'];
65
+ const type = record(params['targetInfo'])?.['type'];
66
+ if (on !== undefined && sessions.has(on) && type === 'iframe' && typeof child === 'string') {
67
+ sessions.add(child);
68
+ }
69
+ }),
70
+ connection.on('Target.detachedFromTarget', (params, on) => {
71
+ const child = params['sessionId'];
72
+ if (
73
+ on !== undefined &&
74
+ sessions.has(on) &&
75
+ child !== sessionId &&
76
+ typeof child === 'string'
77
+ ) {
78
+ sessions.delete(child);
79
+ }
80
+ }),
81
+ connection.on('Runtime.consoleAPICalled', (params, on) => {
82
+ if (on === undefined || !sessions.has(on)) return;
83
+ const args = Array.isArray(params['args']) ? params['args'] : [];
84
+ keep({
85
+ level: levelOf(params['type']),
86
+ text: args.map((arg) => shown(arg) ?? '').join(' '),
87
+ source: 'console',
88
+ });
89
+ }),
90
+ connection.on('Runtime.exceptionThrown', (params, on) => {
91
+ if (on === undefined || !sessions.has(on)) return;
92
+ const details = record(params['exceptionDetails']);
93
+ // `throw 'broken'` carries its payload as the exception's value, with no description.
94
+ const thrown = shown(details?.['exception']);
95
+ const label = details?.['text'];
96
+ keep({
97
+ level: 'error',
98
+ text: thrown ?? (typeof label === 'string' ? label : 'an uncaught exception'),
99
+ source: 'exception',
100
+ });
101
+ }),
102
+ ];
103
+ return {
104
+ messages: () => [...messages],
105
+ clear: () => {
106
+ messages = [];
107
+ },
108
+ stop: () => {
109
+ for (const off of offs) off();
110
+ },
111
+ };
112
+ }
@@ -0,0 +1,33 @@
1
+ // Single responsibility: a second browser context on the harness's one browser
2
+ // (`Target.createBrowserContext`) — a profile with its own cookies, storage and service workers,
3
+ // so two people are signed in at once in one run: an inviter and the invited, an owner and a
4
+ // member. Its tabs are the session's own kind: attached, configured and audited as `newTab()`'s.
5
+
6
+ import type { E2eTab } from './cdp-e2e-page';
7
+ import type { E2eSession } from './cdp-e2e-session';
8
+ import { sessionPortOf } from './cdp-ports';
9
+
10
+ export interface E2eContext {
11
+ readonly id: string;
12
+ /** A tab in this context: none of the first profile's cookies or storage. */
13
+ newTab(): Promise<E2eTab>;
14
+ /** Disposes the context and every tab in it. */
15
+ close(): Promise<void>;
16
+ }
17
+
18
+ /** A fresh, isolated profile beside the session's first one. */
19
+ export async function newBrowserContext(session: E2eSession): Promise<E2eContext> {
20
+ const port = sessionPortOf(session, 'newBrowserContext');
21
+ const created = await port.connection.send('Target.createBrowserContext', {
22
+ disposeOnDetach: true,
23
+ });
24
+ const raw = created.result?.['browserContextId'];
25
+ const id = typeof raw === 'string' ? raw : '';
26
+ return {
27
+ id,
28
+ newTab: () => port.openTab(id),
29
+ async close() {
30
+ await port.connection.send('Target.disposeBrowserContext', { browserContextId: id });
31
+ },
32
+ };
33
+ }
@@ -11,6 +11,9 @@ import type { CdpConnection } from '@ultimat3/scraping/cdp';
11
11
  import { CdpCallFailedError, CdpTimeoutError } from '@ultimat3/scraping/cdp';
12
12
  import type { AxTreeNode } from './ax-node';
13
13
  import { axRecord, toAxTreeNodes } from './ax-node';
14
+ import { captureConsole } from './cdp-console-capture';
15
+ import { keyEvents } from './cdp-key-press';
16
+ import { registerTabPort } from './cdp-ports';
14
17
  import type { AxTreeRequest, E2eBrowserPage } from './e2e-page';
15
18
 
16
19
  /** What the page threw, when `Runtime.evaluate` answered with an exception rather than a value. */
@@ -80,7 +83,9 @@ export interface E2eTab extends E2eBrowserPage {
80
83
  /**
81
84
  * A REAL key press (`Input.dispatchKeyEvent`, down then up) at whatever has focus, so its default
82
85
  * action runs: Tab moves focus, which a dispatched `KeyboardEvent` never does. A name in
83
- * `PRESS_KEYS` or one printable character.
86
+ * `PRESS_KEYS` or one ASCII letter or digit, optionally after modifiers held for it:
87
+ * `Shift+Tab`, `Control+k`, `Meta+Shift+Enter` (`Alt`, `Control`, `Meta`, `Shift`). Shift makes
88
+ * the key a US keyboard would (`Shift+a` is `A`, `Shift+1` is `!`).
84
89
  */
85
90
  press(key: string): Promise<void>;
86
91
  /** Required on a tab: the audit of every `e2eTest` reads it (`e2e-a11y-run.ts`). */
@@ -100,45 +105,7 @@ export interface TouchPoint {
100
105
  readonly y: number;
101
106
  }
102
107
 
103
- /** Named keys `press()` knows, with the Windows virtual key code Chrome routes them by. */
104
- export const PRESS_KEYS: Readonly<Record<string, number>> = {
105
- Tab: 9,
106
- Enter: 13,
107
- Escape: 27,
108
- ' ': 32,
109
- PageUp: 33,
110
- PageDown: 34,
111
- End: 35,
112
- Home: 36,
113
- ArrowLeft: 37,
114
- ArrowUp: 38,
115
- ArrowRight: 39,
116
- ArrowDown: 40,
117
- Backspace: 8,
118
- Delete: 46,
119
- };
120
-
121
- /** The key code of a printable character: its upper-case code point for a letter or digit. */
122
- const charCode = (key: string): number | undefined =>
123
- key.length === 1 && /[a-z0-9]/i.test(key) ? key.toUpperCase().charCodeAt(0) : undefined;
124
-
125
- /**
126
- * The text a key TYPES, as puppeteer's key table has it. A key with text goes down as `keyDown`
127
- * carrying it, so Chrome raises the character event — what makes Enter submit a focused button's
128
- * form. A key with none (Tab, the arrows) goes down as `rawKeyDown`.
129
- */
130
- const typedText = (key: string): string | undefined =>
131
- key === 'Enter' ? '\r' : key.length === 1 ? key : undefined;
132
-
133
- /** `KeyboardEvent.code`: `KeyA`, `Digit7`, `Space`; a named key is its own code. */
134
- const keyCodeName = (key: string): string =>
135
- key === ' '
136
- ? 'Space'
137
- : /^[a-z]$/i.test(key)
138
- ? `Key${key.toUpperCase()}`
139
- : /^[0-9]$/.test(key)
140
- ? `Digit${key}`
141
- : key;
108
+ export { PRESS_KEYS } from './cdp-key-press';
142
109
 
143
110
  export interface CdpE2eTabOptions {
144
111
  readonly connection: CdpConnection;
@@ -196,6 +163,8 @@ export function cdpE2eTab(options: CdpE2eTabOptions): E2eTab {
196
163
  let current = 'about:blank';
197
164
  // Touch emulation is per tab and stays on: switched on by the first `touchDrag`, once.
198
165
  let touchOn = false;
166
+ // Heard from construction: the session enabled `Runtime` before handing the tab out.
167
+ const consoleCapture = captureConsole(options.connection, sessionId);
199
168
 
200
169
  const evaluateRaw = (expression: string) =>
201
170
  send('Runtime.evaluate', { expression, returnByValue: true, awaitPromise: true }, sessionId);
@@ -393,27 +362,13 @@ export function cdpE2eTab(options: CdpE2eTabOptions): E2eTab {
393
362
  }
394
363
  await touch('touchEnd', []);
395
364
  },
396
- async press(key: string): Promise<void> {
397
- const code = (Object.hasOwn(PRESS_KEYS, key) ? PRESS_KEYS[key] : undefined) ?? charCode(key);
398
- if (code === undefined) {
399
- throw new CdpCallFailedError({
400
- method: `press(${key})`,
401
- detail: `not a key press() knows: one of ${Object.keys(PRESS_KEYS).join(', ')}, or one letter or digit`,
402
- });
403
- }
404
- const text = typedText(key);
405
- const common = { key, code: keyCodeName(key), windowsVirtualKeyCode: code };
406
- await send(
407
- 'Input.dispatchKeyEvent',
408
- {
409
- type: text === undefined ? 'rawKeyDown' : 'keyDown',
410
- ...common,
411
- ...(text === undefined ? {} : { text }),
412
- },
413
- sessionId,
414
- );
415
- await send('Input.dispatchKeyEvent', { type: 'keyUp', ...common }, sessionId);
365
+ async press(chord: string): Promise<void> {
366
+ const { down, up } = keyEvents(chord);
367
+ await send('Input.dispatchKeyEvent', down, sessionId);
368
+ await send('Input.dispatchKeyEvent', up, sessionId);
416
369
  },
370
+ consoleMessages: () => consoleCapture.messages(),
371
+ clearConsole: () => consoleCapture.clear(),
417
372
  offline: (enabled: boolean) => options.offline(enabled),
418
373
  async accessibilityTree(request: AxTreeRequest): Promise<readonly AxTreeNode[]> {
419
374
  const nodes = toAxTreeNodes((await send(FULL_AX_TREE, {}, sessionId)).result);
@@ -445,9 +400,12 @@ export function cdpE2eTab(options: CdpE2eTabOptions): E2eTab {
445
400
  : [];
446
401
  },
447
402
  async close(): Promise<void> {
403
+ consoleCapture.stop();
448
404
  await send('Target.closeTarget', { targetId: options.targetId });
449
405
  options.audit?.closed();
450
406
  },
451
407
  };
408
+ // What `addVirtualAuthenticator(tab)` drives: this tab's own session, never a member on the port.
409
+ registerTabPort(tab, { connection: options.connection, sessionId });
452
410
  return tab;
453
411
  }
@@ -9,6 +9,7 @@ import type { E2eTab } from './cdp-e2e-page';
9
9
  import { cdpE2eTab } from './cdp-e2e-page';
10
10
  import { isNetworkProbe, networkAgrees } from './cdp-network-probe';
11
11
  import { offlineScripts } from './cdp-offline-script';
12
+ import { registerSessionPort } from './cdp-ports';
12
13
  import type { AuditedTab } from './e2e-a11y-tabs';
13
14
  import { auditTab } from './e2e-a11y-tabs';
14
15
 
@@ -127,6 +128,9 @@ export async function cdpE2eSession(options: CdpE2eSessionOptions): Promise<E2eS
127
128
  );
128
129
  }
129
130
  if (cut) configured.push(condition(session));
131
+ // A cross-site frame runs in its own process and reports its console on its own session:
132
+ // `Runtime` on, so its tab's console capture hears it (`cdp-console-capture.ts`).
133
+ if (type === 'iframe') configured.push(send('Runtime.enable', {}, session));
130
134
  if (type === 'page') {
131
135
  configured.push(send('Page.enable', {}, session), send('Runtime.enable', {}, session));
132
136
  pageSessions.add(session);
@@ -302,40 +306,46 @@ export async function cdpE2eSession(options: CdpE2eSessionOptions): Promise<E2eS
302
306
  });
303
307
  };
304
308
 
305
- return {
306
- async newTab(): Promise<E2eTab> {
307
- const created = await send('Target.createTarget', { url: 'about:blank' });
308
- const targetId = field(created.result, 'targetId');
309
- if (targetId === undefined) {
310
- throw new CdpCallFailedError({
311
- method: 'Target.createTarget',
312
- detail: 'the browser created a tab and answered no targetId',
313
- });
314
- }
315
- const sessionId = await attached(targetId);
316
- // Every tab is audited: built here, so no suite can hold one the audit does not see. The
317
- // tab is alive while the browser still knows its target — a closed one has no page to read.
318
- let audit: AuditedTab | undefined;
319
- const tab = cdpE2eTab({
320
- connection,
321
- sessionId,
322
- targetId,
323
- loadTimeoutMs: options.loadTimeoutMs,
324
- offline,
325
- audit: {
326
- navigated: () => audit?.navigated() ?? Promise.resolve(),
327
- used: () => audit?.used(),
328
- closed: () => audit?.closed(),
329
- },
309
+ /** A tab in the first profile, or in `browserContextId`'s (`newBrowserContext`). */
310
+ const openTab = async (browserContextId?: string): Promise<E2eTab> => {
311
+ const created = await send('Target.createTarget', {
312
+ url: 'about:blank',
313
+ ...(browserContextId === undefined ? {} : { browserContextId }),
314
+ });
315
+ const targetId = field(created.result, 'targetId');
316
+ if (targetId === undefined) {
317
+ throw new CdpCallFailedError({
318
+ method: 'Target.createTarget',
319
+ detail: 'the browser created a tab and answered no targetId',
330
320
  });
331
- audit = auditTab(tab, () =>
332
- send('Target.getTargetInfo', { targetId }).then(
333
- () => true,
334
- () => false,
335
- ),
336
- );
337
- return tab;
338
- },
321
+ }
322
+ const sessionId = await attached(targetId);
323
+ // Every tab is audited: built here, so no suite can hold one the audit does not see. The
324
+ // tab is alive while the browser still knows its target — a closed one has no page to read.
325
+ let audit: AuditedTab | undefined;
326
+ const tab = cdpE2eTab({
327
+ connection,
328
+ sessionId,
329
+ targetId,
330
+ loadTimeoutMs: options.loadTimeoutMs,
331
+ offline,
332
+ audit: {
333
+ navigated: () => audit?.navigated() ?? Promise.resolve(),
334
+ used: () => audit?.used(),
335
+ closed: () => audit?.closed(),
336
+ },
337
+ });
338
+ audit = auditTab(tab, () =>
339
+ send('Target.getTargetInfo', { targetId }).then(
340
+ () => true,
341
+ () => false,
342
+ ),
343
+ );
344
+ return tab;
345
+ };
346
+
347
+ const handle: E2eSession = {
348
+ newTab: () => openTab(),
339
349
  async addInitScript(source: string): Promise<void> {
340
350
  scripts.push(source);
341
351
  // A closed tab refuses every call; it is dropped rather than taking the open tabs down with
@@ -355,4 +365,10 @@ export async function cdpE2eSession(options: CdpE2eSessionOptions): Promise<E2eS
355
365
  sockets: () => [...sockets],
356
366
  requests: () => [...requests],
357
367
  };
368
+ // What `newBrowserContext(session)` drives: a tab opened into another profile, attached as these.
369
+ registerSessionPort(handle, {
370
+ connection,
371
+ openTab: (browserContextId) => openTab(browserContextId),
372
+ });
373
+ return handle;
358
374
  }