@ultimat3/testing 20.2.1 → 22.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.
@@ -0,0 +1,122 @@
1
+ // A document small enough to hold in a test and real enough to RUN the driver's own in-page
2
+ // expressions. Without it every claim about `getByRole` and `getByText` would be an assertion
3
+ // about a string, and a string that never executes cannot be wrong about a page.
4
+ //
5
+ // Its own file, the pattern `dev-roles-fixture.ts` and `policy-fixture.ts` already set here.
6
+
7
+ /** One element. `attrs` is data, so every read of it goes through `Object.hasOwn` below. */
8
+ export interface FakeE2eElement {
9
+ readonly tag: string;
10
+ readonly attrs: Readonly<Record<string, string>>;
11
+ readonly text?: string;
12
+ readonly children?: readonly FakeE2eElement[];
13
+ /** What `getComputedStyle` answers. Absent is the browser's own default — visible. */
14
+ readonly style?: { display?: string; visibility?: string; opacity?: string };
15
+ }
16
+
17
+ interface Node {
18
+ tagName: string;
19
+ textContent: string;
20
+ readonly attributes: Record<string, string>;
21
+ readonly descendants: Node[];
22
+ readonly style: { display: string; visibility: string; opacity: string };
23
+ getAttribute(name: string): string | null;
24
+ setAttribute(name: string, value: string): void;
25
+ removeAttribute(name: string): void;
26
+ contains(other: Node): boolean;
27
+ }
28
+
29
+ const textOf = (element: FakeE2eElement): string =>
30
+ [element.text ?? '', ...(element.children ?? []).map(textOf)]
31
+ .join(' ')
32
+ .replace(/\s+/g, ' ')
33
+ .trim();
34
+
35
+ function build(element: FakeE2eElement): Node {
36
+ const attributes: Record<string, string> = { ...element.attrs };
37
+ const children = (element.children ?? []).map(build);
38
+ const descendants = children.flatMap((child) => [child, ...child.descendants]);
39
+ const node: Node = {
40
+ tagName: element.tag.toUpperCase(),
41
+ textContent: textOf(element),
42
+ attributes,
43
+ descendants,
44
+ style: {
45
+ display: element.style?.display ?? 'block',
46
+ visibility: element.style?.visibility ?? 'visible',
47
+ opacity: element.style?.opacity ?? '1',
48
+ },
49
+ getAttribute: (name) => (Object.hasOwn(attributes, name) ? (attributes[name] as string) : null),
50
+ setAttribute: (name, value) => {
51
+ attributes[name] = value;
52
+ },
53
+ removeAttribute: (name) => {
54
+ delete attributes[name];
55
+ },
56
+ contains: (other) => descendants.includes(other),
57
+ };
58
+ return node;
59
+ }
60
+
61
+ /**
62
+ * `tag`, `*`, `[attr]`, `[attr="value"]`, a trailing `:not([attr])` and any combination — every
63
+ * shape this driver emits (`input:not([type])` is the textbox role's untyped input).
64
+ */
65
+ const SIMPLE = /^([a-zA-Z0-9*]*)((?:\[[^\]]*\])*)(?::not\(\[([^\]=]+)\]\))?$/;
66
+
67
+ function matchesSimple(node: Node, selector: string): boolean {
68
+ const parsed = SIMPLE.exec(selector.trim());
69
+ if (parsed === null) return false;
70
+ const tag = parsed[1] ?? '';
71
+ if (tag !== '' && tag !== '*' && tag.toUpperCase() !== node.tagName) return false;
72
+ const absent = parsed[3]?.trim();
73
+ if (absent !== undefined && node.getAttribute(absent) !== null) return false;
74
+ for (const clause of (parsed[2] ?? '').matchAll(/\[([^\]=]+)(?:=("[^"]*"|[^\]]*))?\]/g)) {
75
+ const name = (clause[1] ?? '').trim();
76
+ const held = node.getAttribute(name);
77
+ if (held === null) return false;
78
+ const raw = clause[2];
79
+ if (raw !== undefined && held !== raw.replace(/^"|"$/g, '')) return false;
80
+ }
81
+ return true;
82
+ }
83
+
84
+ const matches = (node: Node, selector: string): boolean =>
85
+ selector.split(',').some((part) => part.trim() !== '' && matchesSimple(node, part));
86
+
87
+ /**
88
+ * The globals a driver expression names, bound to one tree. `getComputedStyle` and `document` are
89
+ * handed in as arguments rather than assigned to `globalThis`: a test that installed a fake
90
+ * `document` on the process would leak it into every later file in the run.
91
+ */
92
+ export function fakeE2eDocument(root: FakeE2eElement): Readonly<Record<string, unknown>> {
93
+ const rootNode = build(root);
94
+ const all = [rootNode, ...rootNode.descendants];
95
+ return {
96
+ document: {
97
+ querySelectorAll: (selector: string): Node[] => all.filter((node) => matches(node, selector)),
98
+ querySelector: (selector: string): Node | null =>
99
+ all.find((node) => matches(node, selector)) ?? null,
100
+ getElementById: (id: string): Node | null =>
101
+ all.find((node) => node.getAttribute('id') === id) ?? null,
102
+ },
103
+ getComputedStyle: (node: Node) => node.style,
104
+ };
105
+ }
106
+
107
+ /**
108
+ * Run an expression the driver built, in THIS process, against a stubbed global scope.
109
+ *
110
+ * `new Function` and not `eval`: the body evaluates with no access to this module's scope, so a
111
+ * name the expression does not receive as a parameter is genuinely free — which is exactly the
112
+ * `ReferenceError` a captured closure produces in a real browser, and the thing the evaluate
113
+ * wrapper has to be proved against.
114
+ */
115
+ export async function runInFakePage(
116
+ expression: string,
117
+ globals: Readonly<Record<string, unknown>> = {},
118
+ ): Promise<unknown> {
119
+ const names = Object.keys(globals);
120
+ const body = new Function(...names, `return (${expression});`) as (...args: unknown[]) => unknown;
121
+ return await body(...names.map((name) => globals[name]));
122
+ }
@@ -0,0 +1,114 @@
1
+ // The registration. One call from an app's test preload turns the declared `page` fixture into a
2
+ // browser-backed one and gives `e2eTest` a driver — and nothing here runs unless that call is
3
+ // made, which is what keeps a CI box with no Chrome answering `hasE2eDriver() === false`.
4
+
5
+ import { test as bunTest } from 'bun:test';
6
+ import type { E2eBrowserPage, E2ePageOptions } from './e2e-page';
7
+ import { e2ePage } from './e2e-page';
8
+ import { FixtureUnavailableError } from './errors';
9
+ import { unavailableFixture } from './fixture-drivers';
10
+ import { defineFixtures } from './fixtures';
11
+ import type { E2eBody, E2eFixtures, PageLike } from './test-types';
12
+ import { resetE2eDriver, useE2eDriver } from './test-types';
13
+
14
+ export interface E2eDriverOptions extends E2ePageOptions {
15
+ /**
16
+ * Switch the running app to a new build — the SERVER half no page port can speak for. Given, it
17
+ * becomes the `deploy` fixture's `newBuild()` and `e2eTest`'s `update()`; absent, both refuse by
18
+ * name. The gate's e2e preload passes the spawned app's `restart({ BUILD_ID })`.
19
+ */
20
+ readonly newBuild?: (() => Promise<void>) | undefined;
21
+ }
22
+
23
+ /**
24
+ * A member this driver cannot build is a REFUSAL, never a no-op. A fixture that silently did
25
+ * nothing would make the assertion after it read as proof: `offline()` followed by "the fallback
26
+ * rendered" is the app's ONLINE page passing an offline test.
27
+ */
28
+ const refuse =
29
+ (name: string, needs: string): (() => Promise<void>) =>
30
+ () =>
31
+ Promise.reject(new FixtureUnavailableError({ name, needs }));
32
+
33
+ /**
34
+ * `offline()`/`online()` FORWARD, `As of 2026-08-27`. They refused until then on a reason the tree
35
+ * contradicted on the day it was written: this file said `CdpPageLike`
36
+ * (`packages/scraping/src/cdp-port.ts`) "declares twelve methods and none of them is
37
+ * `setOfflineMode`". It declares it at line 71 — optional, guarded, with a coded
38
+ * `X_NOT_IMPLEMENTED` in `cdp-target.ts` for a launcher that lacks it — and `page-over-target.ts`
39
+ * exposes it as `ScrapePage.offline()`. All of that landed in **the same commit as the comment**
40
+ * (#351), so the refusal was never true, and it is the reason issue #390 records a real browser
41
+ * check as out of reach.
42
+ *
43
+ * Optional on `E2eBrowserPage` rather than required, for the reason `CdpPageLike` gives about the
44
+ * same method: this port is the shape of somebody ELSE's object, and a six-line test double must
45
+ * still satisfy it. Absent, the refusal stands — and now it names the method the double is missing
46
+ * rather than a capability the framework does not have.
47
+ */
48
+ const networkFixtures = (browser: E2eBrowserPage): Pick<E2eFixtures, 'offline' | 'online'> => {
49
+ const setOffline = browser.offline?.bind(browser);
50
+ if (setOffline === undefined) {
51
+ const needs =
52
+ "a page whose driver implements offline(enabled) — @ultimat3/scraping's ScrapePage does; a hand-rolled E2eBrowserPage may not";
53
+ return { offline: refuse('offline', needs), online: refuse('online', needs) };
54
+ }
55
+ return { offline: () => setOffline(true), online: () => setOffline(false) };
56
+ };
57
+
58
+ /** What `e2eTest` hands its body: a real page, the network condition, and one honest refusal. */
59
+ export const e2eFixtures = (
60
+ page: PageLike,
61
+ browser: E2eBrowserPage,
62
+ newBuild?: () => Promise<void>,
63
+ ): E2eFixtures => ({
64
+ page,
65
+ ...networkFixtures(browser),
66
+ // A new build id is a fact about the SERVER, which no page port can speak for — so it is
67
+ // forwarded when whoever spawned the app can restart it, and refused by name otherwise.
68
+ update:
69
+ newBuild ??
70
+ refuse(
71
+ 'update',
72
+ 'a second build served under a new immutable build id, which is a server fact',
73
+ ),
74
+ });
75
+
76
+ /**
77
+ * Install the browser-backed driver for this process.
78
+ *
79
+ * Two seams, deliberately, because they are two questions. `defineFixtures({ page })` replaces the
80
+ * declaration `driverFixtures()` registered — the ordinary way a driver arrives, last registration
81
+ * wins — so every `test('…', async ({ page }) => …)` in the suite gets a browser. `useE2eDriver`
82
+ * is the other half: it is what makes `hasE2eDriver()` answer true and stops `e2eTest` becoming a
83
+ * `test.skip` — which the gate now reports as a SKIPPED step rather than the green check it
84
+ * printed until #434, and which a repo whose `x.verify.json` names `e2e` gets red for.
85
+ *
86
+ * `budget` and `signIn` are deliberately NOT registered here, and `deploy` only with `newBuild`. Each needs something a
87
+ * page cannot supply — byte counts off a built `dist/`, an app's own sign-in route, a second build
88
+ * — so each keeps refusing with `X_TEST_FIXTURE_UNAVAILABLE` naming what it waits for.
89
+ *
90
+ * Returns the undo. `bun test` is one process, so a driver installed and never removed reaches
91
+ * every later file in the run.
92
+ */
93
+ export function installE2eDriver(options: E2eDriverOptions): () => void {
94
+ const page = e2ePage(options);
95
+ const newBuild = options.newBuild;
96
+ defineFixtures({
97
+ page: () => page,
98
+ ...(newBuild === undefined ? {} : { deploy: () => ({ newBuild }) }),
99
+ });
100
+ useE2eDriver((name, body: E2eBody) => {
101
+ bunTest(name, () => body(e2eFixtures(page, options.page, newBuild)));
102
+ });
103
+ return () => {
104
+ // Both halves, because both were installed. Putting the DECLARATION back — rather than
105
+ // deleting the key — is what keeps a later file's `{ page }` failing as
106
+ // `X_TEST_FIXTURE_UNAVAILABLE` (a driver is missing) instead of `X_TEST_FIXTURE_UNKNOWN`
107
+ // (register it), which is the wrong instruction for a name the framework declares.
108
+ defineFixtures({
109
+ page: unavailableFixture('page'),
110
+ ...(newBuild === undefined ? {} : { deploy: unavailableFixture('deploy') }),
111
+ });
112
+ resetE2eDriver();
113
+ };
114
+ }
@@ -0,0 +1,42 @@
1
+ // The registry for the browser-backed e2e driver's codes: the seven `X_E2E_*` a page refuses with
2
+ // and the four `X_CDP_*` its raw-CDP browser refuses with. Registered here, not in `errors.ts`,
3
+ // because that catalogue sits at its ceiling; anchored by the barrel and by both constructor files.
4
+ import { registerErrorCodes } from '@ultimat3/core';
5
+
6
+ export const E2E_ERROR_CODES = [
7
+ 'X_E2E_EVALUATE_UNSUPPORTED',
8
+ 'X_E2E_EVALUATE_CAPTURED',
9
+ 'X_E2E_EVALUATE_THREW',
10
+ 'X_E2E_LOCATOR_EMPTY',
11
+ 'X_E2E_LOCATOR_AMBIGUOUS',
12
+ 'X_E2E_SERVICE_WORKER_ABSENT',
13
+ 'X_E2E_APP_FAILED',
14
+ // Four and not one, because the four repairs differ: install a browser, read the browser's own
15
+ // stderr, look at the page, raise a deadline.
16
+ 'X_CDP_BROWSER_MISSING',
17
+ 'X_CDP_LAUNCH_FAILED',
18
+ 'X_CDP_CALL_FAILED',
19
+ 'X_CDP_TIMEOUT',
20
+ ] as const;
21
+
22
+ export type E2eErrorCode = (typeof E2E_ERROR_CODES)[number];
23
+
24
+ export const E2E_ERROR_TITLES = Object.freeze<Record<E2eErrorCode, string>>({
25
+ X_E2E_EVALUATE_UNSUPPORTED: 'a page.evaluate() closure cannot be sent into the browser',
26
+ X_E2E_EVALUATE_CAPTURED: 'a page.evaluate() closure named a binding the page does not have',
27
+ X_E2E_EVALUATE_THREW: 'an expression an e2e page ran threw inside the browser',
28
+ X_E2E_LOCATOR_EMPTY: 'an e2e locator matched no element',
29
+ X_E2E_LOCATOR_AMBIGUOUS: 'an e2e locator matched more than one element and was asked to click',
30
+ X_E2E_SERVICE_WORKER_ABSENT: 'no service worker took control of the page within the budget',
31
+ X_E2E_APP_FAILED: 'the app an e2e run spawned did not come up',
32
+ X_CDP_BROWSER_MISSING: 'no Chrome or Chromium is installed for the e2e driver to launch',
33
+ X_CDP_LAUNCH_FAILED: 'the browser started and never announced a DevTools endpoint',
34
+ X_CDP_CALL_FAILED: 'the browser refused a DevTools call',
35
+ X_CDP_TIMEOUT: 'a DevTools call did not answer inside its deadline',
36
+ });
37
+
38
+ // Owned here and borrowed by nobody, so unconditional: a second package claiming one must fail as
39
+ // X_ERROR_CODE_DUPLICATE rather than quietly keep whichever title registered first.
40
+ registerErrorCodes(
41
+ Object.fromEntries(Object.entries(E2E_ERROR_TITLES).map(([code, title]) => [code, { title }])),
42
+ );
@@ -0,0 +1,126 @@
1
+ // One constructor per way the browser-backed e2e page refuses. Every cause below quotes a value
2
+ // that came out of a BROWSER or out of a test's own `toString()`, so every one of them is
3
+ // rendered rather than interpolated.
4
+
5
+ import { renderCauseValue, renderFixLiteral, UltimateError } from '@ultimat3/core';
6
+ import type { E2eSelection } from './e2e-selection';
7
+ import { selectionCall } from './e2e-selection';
8
+ // Bare: the titles these constructors' codes render with are registered there.
9
+ import './e2e-error-codes';
10
+
11
+ /** A page URL is uncontrolled text; a fix line has to parse after one lands inside it. */
12
+ const URL_PLACEHOLDER = '<the url the cause names>';
13
+
14
+ /**
15
+ * The closure never left the test process. `PageLike.evaluate` takes a function and CDP takes a
16
+ * string, so the only thing that can cross is `Function.prototype.toString()` — and a function
17
+ * with no readable source, or one expecting an argument nothing in the page will pass, has no
18
+ * honest string form at all.
19
+ */
20
+ export class E2eEvaluateUnsupportedError extends UltimateError {
21
+ constructor(input: { readonly reason: string; readonly source: string }) {
22
+ super({
23
+ code: 'X_E2E_EVALUATE_UNSUPPORTED',
24
+ cause: `page.evaluate() was given a function that ${input.reason}: ${renderCauseValue(input.source)}`,
25
+ fix: 'page.evaluate(() => document.title) # a zero-parameter arrow whose body names only page globals',
26
+ });
27
+ }
28
+ }
29
+
30
+ /**
31
+ * The closure crossed and then named something the page has never heard of. This is the failure
32
+ * the whole `evaluate` seam is built around: `const wanted = 3; page.evaluate(() => rows === wanted)`
33
+ * sends the source, so the page receives the NAME `wanted` and a `ReferenceError`. Reported with
34
+ * the binding's own name, because "it threw in the browser" sends the reader to the app.
35
+ */
36
+ export class E2eEvaluateCapturedError extends UltimateError {
37
+ constructor(input: { readonly binding: string; readonly source: string }) {
38
+ const binding = renderFixLiteral(input.binding, '<the binding the cause names>');
39
+ super({
40
+ code: 'X_E2E_EVALUATE_CAPTURED',
41
+ cause: `page.evaluate() ran ${renderCauseValue(input.source)} in the browser and ${renderCauseValue(input.binding)} is not defined there — a closure sends its source, never its scope`,
42
+ fix: `page.evaluate(() => document.querySelectorAll("script[src]").length) # write the value into the closure literally; the page has no binding named ${binding}`,
43
+ });
44
+ }
45
+ }
46
+
47
+ /**
48
+ * The expression ran and the PAGE threw — the app's own failure, not the driver's. Kept apart from
49
+ * the two above so the reader is sent to the app rather than to the test's closure.
50
+ */
51
+ export class E2eEvaluateThrewError extends UltimateError {
52
+ constructor(input: { readonly thrown: string; readonly url: string }) {
53
+ super({
54
+ code: 'X_E2E_EVALUATE_THREW',
55
+ cause: `the expression page.evaluate() ran threw inside the browser: ${renderCauseValue(input.thrown)}`,
56
+ fix: `x dev — then open ${renderFixLiteral(input.url, URL_PLACEHOLDER)} and run the same expression in the console; the throw is the page's`,
57
+ });
58
+ }
59
+ }
60
+
61
+ /**
62
+ * Nothing matched. The fix is the retrying assertion and not a longer sleep: `toBeVisible()` looks
63
+ * again to a budget, while `click()` resolves the selection once — so a test that raced the render
64
+ * is asserting in the wrong order rather than waiting for the wrong length of time.
65
+ */
66
+ export class E2eLocatorEmptyError extends UltimateError {
67
+ constructor(input: { readonly selection: E2eSelection; readonly url: string }) {
68
+ const call = selectionCall(input.selection);
69
+ super({
70
+ code: 'X_E2E_LOCATOR_EMPTY',
71
+ cause: `${call} matched no element on ${renderCauseValue(input.url)}`,
72
+ fix: `await expect(${call}).toBeVisible() before acting on it — that assertion retries to a budget, click() resolves once`,
73
+ });
74
+ }
75
+ }
76
+
77
+ /**
78
+ * More than one matched and the caller asked to ACT. Never raised by `count()` or `isVisible()`:
79
+ * an assertion handed an ambiguous locator has an answer, and refusing there would turn a question
80
+ * into a crash. A click has no such answer — one of them is about to be pressed.
81
+ */
82
+ export class E2eLocatorAmbiguousError extends UltimateError {
83
+ constructor(input: { readonly selection: E2eSelection; readonly count: number }) {
84
+ const call = selectionCall(input.selection);
85
+ super({
86
+ code: 'X_E2E_LOCATOR_AMBIGUOUS',
87
+ cause: `${call} matched ${String(input.count)} elements and click() presses exactly one`,
88
+ fix: `${call}.first().click() # or narrow the selection until it matches one element`,
89
+ });
90
+ }
91
+ }
92
+
93
+ /**
94
+ * `waitForServiceWorker()` gave up. Bounded IN THE PAGE rather than here: an unbounded wait is a
95
+ * test that hangs, and CI then reports a runner timeout with no assertion anywhere in it.
96
+ */
97
+ export class E2eServiceWorkerAbsentError extends UltimateError {
98
+ constructor(input: { readonly url: string; readonly timeoutMs: number }) {
99
+ super({
100
+ code: 'X_E2E_SERVICE_WORKER_ABSENT',
101
+ cause: `no service worker took control of ${renderCauseValue(input.url)} within ${String(input.timeoutMs)}ms`,
102
+ fix: `x build --target static — the worker is generated by the pwa build; then confirm the route at ${renderFixLiteral(input.url, URL_PLACEHOLDER)} registers it`,
103
+ });
104
+ }
105
+ }
106
+
107
+ /**
108
+ * The app an e2e run spawns (`e2e-app.ts`) did not come up: its reset, its seed, or its boot. The
109
+ * cause carries that process's own output, rendered, because it is the only place the reason is.
110
+ */
111
+ export class E2eAppFailedError extends UltimateError {
112
+ constructor(input: {
113
+ readonly step: string;
114
+ readonly output: string;
115
+ /** A literal, for the one step `x dev` cannot diagnose: there being no `x` to run. */
116
+ readonly fix?: string | undefined;
117
+ }) {
118
+ super({
119
+ code: 'X_E2E_APP_FAILED',
120
+ cause: `${renderCauseValue(input.step)} failed for the e2e app: ${renderCauseValue(input.output)}`,
121
+ fix:
122
+ input.fix ??
123
+ 'x dev --json # boot the same app by hand and read why it would not start; the e2e run used a throwaway ULTIMATE_STATE_DIR, so your own .x is untouched',
124
+ });
125
+ }
126
+ }
@@ -0,0 +1,157 @@
1
+ // The one crossing in this driver that cannot be lossless: `PageLike.evaluate` takes a CLOSURE and
2
+ // every browser port in the framework takes a STRING. What is supported is stated here, what is
3
+ // not is refused by name, and a page-side throw comes back as itself rather than as a driver fault.
4
+
5
+ import { renderCauseValue, stringField } from '@ultimat3/core';
6
+ import {
7
+ E2eEvaluateCapturedError,
8
+ E2eEvaluateThrewError,
9
+ E2eEvaluateUnsupportedError,
10
+ } from './e2e-errors';
11
+
12
+ /** Only what this driver needs from a page, so a test proves the crossing with two methods. */
13
+ export interface EvaluablePage {
14
+ evaluate(expression: string): Promise<unknown>;
15
+ url(): string;
16
+ }
17
+
18
+ /**
19
+ * A function with no source. `Function.prototype.toString` answers `[native code]` for a native
20
+ * function and for anything `.bind()` produced, so there is nothing to send and the page would be
21
+ * asked to evaluate a syntax error.
22
+ */
23
+ const NATIVE = /\{\s*\[native code\]\s*\}/;
24
+
25
+ /**
26
+ * The parameter list of an arrow or a function expression, as written. `PageLike.evaluate` declares
27
+ * `() => T`, so a declared parameter is a value the author meant to pass and cannot: nothing in
28
+ * the page will supply it, and it would silently arrive `undefined`.
29
+ */
30
+ const takesParameters = (source: string): boolean => {
31
+ const arrow = /^(?:async\s+)?\(([^)]*)\)\s*=>/.exec(source);
32
+ if (arrow !== null) return arrow[1]?.trim() !== '';
33
+ // `x => x * 2` — a single unparenthesised parameter, which is still a parameter.
34
+ if (/^(?:async\s+)?[A-Za-z_$][\w$]*\s*=>/.test(source)) return true;
35
+ // The name is OPTIONAL: an anonymous `function (rows)` read as taking nothing without it.
36
+ const fn = /^(?:async\s+)?function\s*\*?\s*(?:[A-Za-z_$][\w$]*)?\s*\(([^)]*)\)/.exec(source);
37
+ return fn !== null && fn[1]?.trim() !== '';
38
+ };
39
+
40
+ /**
41
+ * Is the source a standalone expression at all? A method shorthand — what `{ evaluate() {} }.evaluate`
42
+ * stringifies to — is `evaluate() { … }`, which is legal in an object literal and a syntax error
43
+ * anywhere else. `new Function` is the parser, and it PARSES only: nothing is called here, so no
44
+ * page code and no test code runs in this process.
45
+ */
46
+ const parses = (source: string): boolean => {
47
+ try {
48
+ new Function(`"use strict"; return (${source});`);
49
+ return true;
50
+ } catch {
51
+ return false;
52
+ }
53
+ };
54
+
55
+ /**
56
+ * The static half. Everything it refuses is refused before a byte reaches the browser, because the
57
+ * page's own answer for each of these would be a syntax error with the driver's wrapper in it.
58
+ */
59
+ export function closureSource(fn: (...args: never[]) => unknown): string {
60
+ const source = fn.toString();
61
+ if (NATIVE.test(source)) {
62
+ throw new E2eEvaluateUnsupportedError({
63
+ reason: 'is native or bound, so it has no source to send',
64
+ source,
65
+ });
66
+ }
67
+ if (takesParameters(source)) {
68
+ throw new E2eEvaluateUnsupportedError({
69
+ reason: 'declares a parameter, and nothing in the page will pass one',
70
+ source,
71
+ });
72
+ }
73
+ if (!parses(source)) {
74
+ throw new E2eEvaluateUnsupportedError({
75
+ reason: 'does not stringify to an expression the browser can parse',
76
+ source,
77
+ });
78
+ }
79
+ return source;
80
+ }
81
+
82
+ /**
83
+ * The wrapper. It CATCHES in the page and answers a value, rather than letting the throw cross the
84
+ * wire: `@ultimat3/scraping`'s `cdp-target.ts` wraps anything its `evaluate` rejects with as
85
+ * `X_SCRAPE_BROWSER_UNREACHABLE`, so an app error that travelled as a rejection would arrive
86
+ * labelled a dead socket.
87
+ *
88
+ * `Promise.resolve().then(…)` because the closure may be async and because a `ReferenceError` for
89
+ * a captured binding is raised when the body RUNS, not when the arrow is built.
90
+ */
91
+ export const evaluateExpression = (source: string): string =>
92
+ `(() => { const fn = (${source});
93
+ return Promise.resolve().then(() => fn()).then(
94
+ (value) => JSON.stringify({ ok: true, value: value }),
95
+ (error) => JSON.stringify({ ok: false, name: String(error && error.name || 'Error'), message: String(error && error.message || error) }),
96
+ );
97
+ })()`;
98
+
99
+ /**
100
+ * The envelope, read by hand rather than through a schema, and the reason is `value`: it is
101
+ * whatever the test's own closure returned, so no schema in this package can describe it and a
102
+ * `t.object` would strip the one field the caller came for. Everything the DRIVER reads — the
103
+ * discriminant, the error name, the message — is read defensively through core's `stringField`,
104
+ * which is total against a getter that throws.
105
+ *
106
+ * A malformed answer degrades into the failure branch instead of a branch of its own: the wrapper
107
+ * below is the only writer, so anything else is a page that shadowed `JSON.stringify`, and the
108
+ * reader needs to see what came back either way.
109
+ */
110
+ type Envelope =
111
+ | { readonly ok: true; readonly value: unknown }
112
+ | { readonly ok: false; readonly name: string; readonly message: string };
113
+
114
+ const decode = (raw: unknown): unknown => {
115
+ if (typeof raw !== 'string') return raw;
116
+ try {
117
+ return JSON.parse(raw) as unknown;
118
+ } catch {
119
+ return raw;
120
+ }
121
+ };
122
+
123
+ const readEnvelope = (raw: unknown): Envelope => {
124
+ const decoded = decode(raw);
125
+ if (typeof decoded === 'object' && decoded !== null) {
126
+ const held = decoded as { readonly ok?: unknown; readonly value?: unknown };
127
+ if (held.ok === true) return { ok: true, value: held.value };
128
+ return {
129
+ ok: false,
130
+ name: stringField(decoded, 'name') ?? 'Error',
131
+ message: stringField(decoded, 'message') ?? renderCauseValue(raw),
132
+ };
133
+ }
134
+ return { ok: false, name: 'Error', message: renderCauseValue(raw) };
135
+ };
136
+
137
+ /** V8's wording for a free identifier. The name is the whole value of the refusal it produces. */
138
+ const NOT_DEFINED = /^([A-Za-z_$][\w$]*) is not defined$/;
139
+
140
+ /**
141
+ * Run the closure in the page and hand back what it answered.
142
+ *
143
+ * The cast on the way out is the generic boundary and nothing more: `evaluate<T>` is the CALLER's
144
+ * claim about what its own closure returns, and no schema in this process can check a claim the
145
+ * browser was never told about. Everything the driver itself reads is read above.
146
+ */
147
+ export async function evaluateClosure<T>(page: EvaluablePage, fn: () => T): Promise<Awaited<T>> {
148
+ const source = closureSource(fn);
149
+ const envelope = readEnvelope(await page.evaluate(evaluateExpression(source)));
150
+ if (envelope.ok) return envelope.value as Awaited<T>;
151
+ const captured = envelope.name === 'ReferenceError' ? NOT_DEFINED.exec(envelope.message) : null;
152
+ if (captured !== null) throw new E2eEvaluateCapturedError({ binding: captured[1] ?? '', source });
153
+ throw new E2eEvaluateThrewError({
154
+ thrown: `${envelope.name}: ${envelope.message}`,
155
+ url: page.url(),
156
+ });
157
+ }
@@ -0,0 +1,86 @@
1
+ // `LocatorLike` over a browser page: a handle that holds a SELECTION and resolves nothing until
2
+ // something asks. One round trip per question, and no waiting of its own — `toBeVisible()` owns
3
+ // the only retry budget in the harness and drives this by looking again.
4
+
5
+ import { E2eLocatorAmbiguousError, E2eLocatorEmptyError } from './e2e-errors';
6
+ import type { E2eResolution, E2eSelection } from './e2e-selection';
7
+ import { markSelector, selectionExpression, unmarkExpression } from './e2e-selection';
8
+ import type { LocatorLike } from './test-types';
9
+
10
+ /**
11
+ * What a locator needs from the browser. Narrower than `ScrapePage` on purpose: three methods is
12
+ * what a test has to stand up to prove the mapping, and `click` is taken from the page rather than
13
+ * re-derived here so the actionability wait `@ultimat3/scraping` already performs is the one that
14
+ * runs.
15
+ */
16
+ export interface LocatablePage {
17
+ evaluate(expression: string): Promise<unknown>;
18
+ click(selector: string): Promise<void>;
19
+ url(): string;
20
+ }
21
+
22
+ const readResolution = (raw: unknown): E2eResolution => {
23
+ const decoded = typeof raw === 'string' ? (JSON.parse(raw) as unknown) : raw;
24
+ const held = decoded as { count?: unknown; visible?: unknown; marked?: unknown };
25
+ return {
26
+ count: typeof held?.count === 'number' ? held.count : 0,
27
+ visible: held?.visible === true,
28
+ marked: held?.marked === true,
29
+ };
30
+ };
31
+
32
+ /**
33
+ * One mark per click, never a constant: two locators marking the same page at once would each
34
+ * click whichever element the other had just tagged. Seeded from a counter and not from
35
+ * `Math.random()`, which `bun run flight-copies` refuses in shipped source and which would make
36
+ * two runs of one test address two different elements.
37
+ */
38
+ let marks = 0;
39
+ const nextMark = (): string => {
40
+ marks += 1;
41
+ return `m${String(marks)}`;
42
+ };
43
+
44
+ /** Test seam: the counter is process-global, so a test that asserts a mark resets it first. */
45
+ export const resetLocatorMarks = (): void => {
46
+ marks = 0;
47
+ };
48
+
49
+ /**
50
+ * Nothing is cached. A locator taken before a navigation must address the page that is there when
51
+ * it is USED — the same rule `ScrapeFrame` states for a frame handle — so every method below
52
+ * re-resolves, and a handle can never go stale behind the caller's back.
53
+ */
54
+ export function e2eLocator(page: LocatablePage, selection: E2eSelection): LocatorLike {
55
+ const resolve = async (mark?: string): Promise<E2eResolution> =>
56
+ readResolution(await page.evaluate(selectionExpression(selection, mark)));
57
+
58
+ return {
59
+ count: async () => (await resolve()).count,
60
+ /**
61
+ * A point-in-time look, and deliberately not an ambiguity check: an assertion handed a locator
62
+ * that matched three elements has an ANSWER — was the first one visible — and a refusal there
63
+ * would turn `expect(...).toBeVisible()` into a crash rather than a verdict. Only `click`
64
+ * refuses, because only `click` has to pick one.
65
+ */
66
+ isVisible: async () => (await resolve()).visible,
67
+ first: () => e2eLocator(page, { ...selection, first: true }),
68
+ click: async () => {
69
+ const mark = nextMark();
70
+ const resolution = await resolve(mark);
71
+ if (resolution.count === 0) {
72
+ throw new E2eLocatorEmptyError({ selection, url: page.url() });
73
+ }
74
+ if (resolution.count > 1 && !selection.first) {
75
+ throw new E2eLocatorAmbiguousError({ selection, count: resolution.count });
76
+ }
77
+ try {
78
+ await page.click(markSelector(mark));
79
+ } finally {
80
+ // Best effort, and never allowed to replace the click's own failure: a click that
81
+ // navigated took the whole document — attribute included — with it.
82
+ await page.evaluate(unmarkExpression(mark)).catch(() => undefined);
83
+ }
84
+ },
85
+ };
86
+ }