Files
e2e/docs/reference/web.mdx
T
Oskar Kwaśniewski 3dc4ec9614 feat!: browser fixture, getByRole name arg, toMatchSchema, top-level hooks, separate credential namespace (#704)
* feat!: browser fixture, getByRole name arg, toMatchSchema, top-level hooks, separate credential namespace

API review feedback before launch:

- web fixture renamed browser (Web -> Browser, WebExpectation ->
  BrowserExpectation); requires: ['browser']; destructuring web hints the
  new name. web() factory and other Web* types unchanged.
- getByRole(role, name, options?) beside the object form; MCP locate
  writes the short form.
- expect(value).toMatchSchema(standardSchema): sync, returns the typed
  output; poll resolves to it, soft returns undefined after a kept failure.
- describe, beforeEach, afterEach, beforeAll, afterAll exported from e2e;
  web and mobile export typed beforeEach/afterEach.
- credentials and secrets are separate namespaces: a password handle is
  <name>.password, secrets.get() never returns it. Committed recordings
  migrated offline (old key hash verified, then recomputed).
- runtime test.skip keeps Playwright semantics; docs say it throws.

* docs(web): browser acts on one active tab; cookies, routes, dialogs cover the whole browser

* fix(secrets): judge a fill's purpose by the config, not the handle; no old-name hints

A config-time secrets.get() handle reads its purpose from the run's
registry again, and authorizeSecretFill checks the registered purpose, so a
handle claiming generic-secret cannot put a password into a plain field.
Drop the web fixture migration hint. Changesets name the on-screen marker
change for replay entries.

* docs(skill): browser fixture, getByRole name arg, toMatchSchema, top-level hooks, credential namespace on the rewritten skill

* fix(expect): negated toMatchSchema returns nothing, as its type says

* fix(expect,docs): soft double negation stays soft, null ~standard is INVALID_ARGUMENT, Playwright samples keep Playwright's getByRole

Also documents SoftExpectCall, SoftValueExpectation, and NegatedPollExpectation
on the expect reference, requires: ['browser'] in the skill's options table,
and tightens the poll and secret-purpose tests.

* docs(babysit): triage pattern for scripted renames that rewrite another library's code

* docs: engine options take a secrets entry, web package hook exports, vault example imports

* refactor(secrets)!: credentials hold their password, allSecrets feeds fills; engines export describe and every hook; BrowserRoute, BrowserResponse

From the maintainability review:
- ResolvedConfig.secrets is the config.secrets entries only; a credential
  carries its password; allSecrets is the one map fills, the ledger, and
  redaction read. The per-consumer purpose filters and the .password
  suffix parsing are gone, and e2e mcp builds handles from config.
- The config load and a running test name the credential a missing
  secrets.get() most likely meant.
- @e2e-dev/web and @e2e-dev/mobile export describe and all four hooks
  beside test, so a test file registers from one import.
- WebRoute and WebResponse are BrowserRoute and BrowserResponse.
- getByRole normalizes its arguments once; isTextMatch is the one
  string-or-RegExp check; poll reuses ValueMatcherName.

* revert(web): keep WebRoute and WebResponse; Browser names the fixture, Web the network and option types
2026-09-30 20:58:52 +02:00

612 lines
26 KiB
Plaintext

---
title: Browser
description: The browser engine, its options, and the browser fixture it contributes.
---
`@e2e-dev/web` drives Chromium, Firefox, and WebKit through Playwright.
A web target names it as its engine, and it contributes the `browser` fixture for
browser-only work. Import `test` from the package to have `browser` typed.
The package declares `playwright` as a peer dependency (`>=1.63.0 <2`) and
does not install it. An app that already depends on Playwright keeps its
version; `e2e init` adds `playwright` only to a project that has none.
```ts title="e2e.config.ts"
import type { E2EConfig } from 'e2e';
import { web } from '@e2e-dev/web';
export default {
targets: [{ engine: web(), app: { url: 'http://localhost:3000' } }],
} satisfies E2EConfig;
```
## Options
```ts
/**
* Options of the browser engine: how it drives the app. The app itself
* (its `url`, `environment`, `identity`, and the command that starts it) is
* the target's `app`.
*/
export interface WebOptions {
/**
* Browser to launch, `chromium` by default. A `BrowserProvider` leases
* hosted browsers instead: one per worker slot at `prepare`, or one per
* attempt, each attached to over CDP and released when its scope ends. A
* provider implies chromium and excludes `connect`.
*/
readonly browser?: BrowserName | BrowserProvider;
/**
* Initial viewport of every attempt's page; default 1280 by 720. `null`
* emulates no size: the page fills the browser window, whatever size the
* window has (a hosted browser's live view, a headed run), and
* `browser.setViewport` still fixes one for the rest of the attempt.
*/
readonly viewport?: ViewportSize | null;
/**
* How the engine's own screencast records an attempt that records video.
* A browser provider that records (`BrowserProvider.record`) records in
* its place, and ignores these. Which attempts record is the config's
* `video`, not an engine option.
*/
readonly screencast?: WebScreencastOptions;
/**
* Attach to a remote browser over CDP instead of launching locally. Requires
* the chromium browser (the default). Wired by a hosted-browser engine.
*/
readonly connect?: WebConnectOptions;
/**
* Headers added to requests within the app's site, including subdomains.
* Useful for preview-protection tokens. Other sites never receive them.
* Names are case-insensitive and replace existing headers of the same name.
* This enables request routing, disables the browser's HTTP cache, and
* blocks service workers. Playwright traces record request headers.
*/
readonly headers?: Readonly<Record<string, string>>;
/**
* HTTP basic authentication. The browser answers a `401` challenge with
* these credentials on any origin, matching Playwright's `httpCredentials`.
*/
readonly basicAuth?: WebBasicAuth;
/**
* The attribute that carries an element's test id: what the `testId` query
* (`screen.getByTestId`) resolves and what `SemanticNode.testId` reports.
* Defaults to `data-testid`.
*/
readonly testIdAttribute?: string;
/**
* The `User-Agent` every attempt's context sends and `navigator.userAgent`
* reports, for an app that switches into a test mode on a marker in the
* agent string. Defaults to the browser's own. A `user-agent` entry in
* `headers` beside it is `INVALID_CONFIG`, and so is a persistent context
* (`connect.reconnectEndpoint`, or a provider with `scope: 'attempt'`).
*/
readonly userAgent?: string;
}
/** The engine's screencast of the page: the frame size and the JPEG quality of the frames it encodes. */
export interface WebScreencastOptions {
/** Frame size in pixels; default the viewport's, or the window's under `viewport: null`. A smaller size makes a smaller file. */
readonly size?: ViewportSize;
/** JPEG quality of each captured frame, 0 through 100; Playwright's default when unset. */
readonly quality?: number;
}
```
The app a web target opens is the target's `app`, not an engine option:
`targets: [{ engine: web(), app: { url } }]`, documented under
[the app under test](/reference/config#the-app-under-test). A `web()` target
needs `app.url` and refuses the device keys (`bundleId`, `appPath`,
`launchArguments`, `permissions`); `web({ url })` or any other app key on
`web()` is an unknown key, `INVALID_CONFIG`.
A target with `app.url` is a `browser` target, so `requires: ['browser']`
selects web targets.
`connect` needs chromium; `cdpEndpoint(signal)` is called once per worker and
again at an attempt start after a disconnect. A `browser` provider object leases hosted
browsers and releases them when the run or the attempt ends; see
[Hosted browsers](/browser#hosted-browsers) for the `BrowserProvider`
contract and an example provider. `browser: provider` together with
`connect` is `INVALID_CONFIG`, and so is an option `web()` does not take, or
an unknown key inside `connect` or `basicAuth`, naming the nearest known key
when it is a likely typo (`viewprt` is `viewport`) and every key otherwise. `:` is not allowed in the `basicAuth` user name.
The `basicAuth` password is a string or `secrets.get(name)`: a secret the
engine resolves when each attempt starts, redacted like any configured one,
and so is the base64 credential of the `Authorization` header it becomes.
That protection is text only: unlike a fill, it withholds no screenshot or
model pixels, so a page that renders the password on screen is not masked in
them ([Security](/security#secrets)).
`headers` and `basicAuth` are how a test reaches a [protected preview](/starting-your-app#protected-previews).
`screencast` shapes the recording, not which attempts record: that is the
config's [`video`](/reference/config#video) mode. `size` takes whole pixels,
each side at least 1, and `quality` an integer from 0 through 100; anything
else, or another key, is `INVALID_CONFIG` at config load. The old
`web({ video })` spelling is `INVALID_CONFIG` naming `screencast`.
### Recovering a CDP transport
`connect.reconnectEndpoint(signal)` opts into recovery of the same remote
browser after its CDP transport disconnects. This mode uses the browser's
persistent default context because Chrome deletes ordinary Playwright contexts
when their transport detaches.
```ts
interface WebConnectOptions {
cdpEndpoint(signal: AbortSignal): string | Promise<string>;
reconnectEndpoint?(signal: AbortSignal): string | Promise<string>;
}
```
In this mode, `cdpEndpoint` provisions a fresh, dedicated browser at every
attempt start, including retries. The engine rejects a browser reused by a
previous attempt. The remote must have only its default context, and the host
must delete the browser when the attempt ends. Engine cleanup detaches its
connection; it does not terminate the host's browser.
After a disconnect, the next operation calls `reconnectEndpoint` once, bounded
by that operation's timeout and abort signal. This resolver must return the
existing browser's endpoint. The engine verifies the persistent default context
ID and the original page's target ID. It refuses browsers that do not expose
the default context ID. A missing page or a different context fails the attempt.
A URL match is insufficient to select a replacement tab.
The engine installs secure-field masking before publishing each CDP binding;
an incompatible Playwright version fails the connection instead of exposing pixels.
Recovery also requires the original page's frames to retain their closed shadow
DOM tracking hooks. If a document loaded without that hook while disconnected,
recovery fails with `ENGINE_FAILURE`: existing closed roots cannot be recovered
without reloading the application. Mask queries reject any untracked document.
Endpoint resolution, CDP attachment, setup, and dispatch share one timeout.
Exhausting it raises `OPERATION_TIMEOUT`; caller or attempt cancellation raises
`CANCELLED`. Cancelling a concurrent waiter does not cancel the operation that
started recovery. Cancelling that recovery owner fails the shared recovery.
Recovery clears old node references. Observation-derived `tapAt` calls,
observation-root swipes, and focused engine keyboard input require a fresh
engine observation before they resume.
An observation or locator read started before recovery cannot publish references
after the connection changes. Each attempt owns its binding and recordings, so
late cleanup cannot change a later attempt.
The deterministic `browser.mouse` and `browser.keyboard` fixtures remain available
without an agent observation. Test code owns its input and can read current
geometry and focus with `browser.evaluate` before acting.
Recovery preserves the page's unsaved state, storage, the attempt's secret
taint, and the agent ledger. Operations already dispatched
are never retried. Dialog and route handlers are reattached. Video and trace
recording resume, but a segment lost during the disconnect cannot be recovered.
Code using `surfaceOf(engine)` must read its accessors again after recovery;
previously retained Playwright objects belong to the disconnected transport.
Persistent recovery does not support `headers`, `basicAuth`, `userAgent`, `app.clearState`,
or session state capture and restore. `app.restart` remains available. Omit
`reconnectEndpoint` to keep ordinary isolated contexts and the existing behavior.
A `browser` provider with `scope: 'attempt'` rides the same persistent
context, with the same limits: the lease's `cdpEndpoint` provisions the
attempt's browser and its `reconnectEndpoint` (else `cdpEndpoint` again)
reconnects to it. A lease is fresh by the provider's contract, so the engine
does not compare its context with earlier attempts': a hosted service may
restore browsers from one snapshot, which gives new browsers the same
context id.
The attempt's first page is the browser's own first tab, navigated to
`about:blank`, rather than a second tab beside it; a page opened after that,
such as the one `app.restart` opens, is a new tab.
## The active tab
`browser` is the whole browser, showing one active tab. What reads or acts on
a page acts on that tab: `goto`, `reload`, `back`, `forward`, `url`, `title`,
`waitForURL`, `locator`, `frameLocator`, `evaluate`, `waitForResponse`,
`waitForDownload`, `keyboard`, `mouse`, the `expect(browser)` matchers, and
every `screen` query. What belongs to the browser covers every tab:
`cookies`, `setCookies`, `route`, `unroute`, and `onDialog`. `setViewport`
sizes the active tab and every tab opened after it.
A tab the app opens itself, from a `target="_blank"` link or `window.open`,
is not followed: the active tab stays the one the attempt opened, so assert
on what that tab shows, or open the link's URL with `browser.goto`.
## The browser fixture
```ts
/**
* The browser the attempt drives, showing one active tab. Navigation, reads,
* `locator`, `frameLocator`, `evaluate`, `waitForResponse`, `waitForDownload`,
* the keyboard and mouse, `expect(browser)`, and `screen` act on the active
* tab; cookies, routes, and dialog handlers cover the whole browser, every
* tab included. A tab the app opens itself (a `target="_blank"` link,
* `window.open`) is not followed: the active tab stays the one the attempt
* opened.
*/
export interface Browser extends Expectable<BrowserExpectation> {
/** Navigates to an allowed URL. */
goto(
url: string,
options?: {
waitUntil?: 'load' | 'domcontentloaded' | 'networkidle';
timeout?: number;
},
): Promise<void>;
/** Reloads the current document. */
reload(options?: ActionOptions): Promise<void>;
/** Navigates browser history back once. */
back(options?: ActionOptions): Promise<void>;
/** Navigates browser history forward once. */
forward(options?: ActionOptions): Promise<void>;
/** Returns the current URL. */
url(): Promise<string>;
/** Returns the current title. */
title(): Promise<string>;
/** Waits for the current URL to match. */
waitForURL(url: string | RegExp, options?: { timeout?: number }): Promise<void>;
/** Creates a web-only CSS or XPath locator. */
locator(selector: string): Locator;
/** Creates a screen query scope inside one iframe. */
frameLocator(selector: string): FrameScreen;
/** Evaluates trusted test code in the page. */
evaluate<T extends JsonValue>(fn: string | (() => T | Promise<T>)): Promise<T>;
/** Evaluates trusted test code with one required JSON-safe argument. */
evaluate<T extends JsonValue, Arg extends JsonValue>(
fn: string | ((arg: Arg) => T | Promise<T>),
arg: Arg,
): Promise<T>;
/** Adds an attempt-scoped network route. */
route(
pattern: string | RegExp,
handler: (route: WebRoute) => void | Promise<void>,
): Promise<void>;
/** Removes matching attempt-scoped routes. */
unroute(pattern: string | RegExp): Promise<void>;
/** Waits for a matching response. */
waitForResponse(
pattern: string | RegExp,
options?: { timeout?: number },
): Promise<WebResponse>;
/** Returns cookies visible to the current context. */
cookies(): Promise<Cookie[]>;
/** Sets cookies after URL validation. */
setCookies(cookies: readonly Cookie[]): Promise<void>;
/** Sets the viewport size. */
setViewport(size: { width: number; height: number }): Promise<void>;
/** Registers an attempt-scoped dialog handler and returns an unsubscribe function. */
onDialog(handler: DialogHandler): Promise<() => Promise<void>>;
/** Runs a trigger and waits for its download. */
waitForDownload(
trigger: () => Promise<void>,
options?: { timeout?: number },
): Promise<{ path: string; suggestedFilename: string }>;
/** Viewport-level keyboard, for whatever has focus. */
readonly keyboard: {
/** Sends one key. */
press(key: string): Promise<void>;
/** Types plain text. */
type(text: string): Promise<void>;
};
/**
* Direct pointer input from test code, independent of agent observations.
* After CDP recovery, test code can read current geometry with `evaluate`
* before starting a pointer sequence.
*/
readonly mouse: {
/** Moves the pointer. */
move(x: number, y: number): Promise<void>;
/** Scrolls the pointer wheel. */
wheel(deltaX: number, deltaY: number): Promise<void>;
/** Presses the primary pointer button. */
down(): Promise<void>;
/** Releases the primary pointer button. */
up(): Promise<void>;
};
}
```
| Member | Default timeout |
| --- | --- |
| `goto`, `reload`, `back`, `forward` | `config.timeout`, 120000 ms, the same budget `app.open()` uses; `{ timeout }` overrides, capped by the test deadline |
| `waitForResponse`, `waitForDownload` | `config.actionTimeout`, 30000 ms; `{ timeout }` overrides, capped by the test deadline |
| `waitForURL` | `config.assertionTimeout`, 5000 ms |
| `url`, `title`, `evaluate`, `route`, `unroute`, `cookies`, `setCookies`, `setViewport`, `onDialog`, `keyboard.*`, `mouse.*` | `config.actionTimeout`, 30000 ms, not overridable |
Every `browser` call is a recorded `browser.<method>` step, except `locator` and
`frameLocator`: they build a locator without touching the page, and the
action or assertion on it is the step. A relative URL resolves against the
target's `app.url`, else `APP_URL_REQUIRED`. Declare `requires: ['browser']`
in a suite that also runs on other platforms.
### Navigation
`goto` defaults `waitUntil` to `'load'` and throws `POLICY_DENIED` for a
`file:`, `data:`, or `javascript:` URL. `waitForURL` polls every 100 ms; a
relative string resolves against the base URL and matches exactly after
normalization, a `RegExp` tests the full URL, anything else (a predicate
function, say) is `INVALID_ARGUMENT`, and a timeout is `ASSERTION_FAILED`. The other navigations throw `ACTION_FAILED`.
```ts
await browser.goto('/dashboard', { waitUntil: 'networkidle' });
await browser.waitForURL(/\/orders\/\d+$/, { timeout: 15_000 });
```
### Locators and frames
`locator` and `frameLocator`, at the page or inside a frame, throw
`INVALID_LOCATOR` for an empty selector. `frameLocator` throws
`LOCATOR_NOT_FOUND` for a missing frame and `LOCATOR_AMBIGUOUS` for several.
The selector is a Playwright selector: CSS by default, XPath with `xpath=` or
a leading `//`, and `>>` chains, so
`browser.locator('[data-testid="row"] >> nth=2 >> [data-testid="conditions"] > div')`
scopes CSS to one row.
```ts
const payment = browser.frameLocator('#payment-frame');
await payment.getByLabel('Card number').fill('4242424242424242');
```
`frameLocator` returns a `FrameScreen`: a `Screen` whose queries answer from
inside the frame, plus the two web-only escape hatches scoped to it.
```ts
export interface FrameScreen extends Screen {
/** Creates a web-only CSS or XPath locator inside this frame. */
locator(selector: string): Locator;
/** Creates a screen query scope inside an iframe nested in this frame. */
frameLocator(selector: string): FrameScreen;
}
```
Reach for the frame's `locator` only when the control has no accessible
name, label, placeholder, or test id; the [browser guide](/browser#reach-into-an-iframe)
shows when that applies.
Every `screen` query searches its scope and each closed shadow root the page
attached under it, with Playwright's own role, name, text, label, and
attribute matching and each node found once, so a control the observed tree
lists inside a closed root resolves and takes actions and reads. `locator`,
`frameLocator`, and `filter({ hasText })` keep Playwright's reach and stop at
a closed root; the [browser guide](/browser#shadow-dom) has the details.
### evaluate
The function runs in the page and cannot access variables from the test.
It is serialized by its source and inlined into the page, so it must not
close over anything outside its own body; helpers declared inside the body
work. Pass outside values through `arg`. Both `arg` and the return value
must be `JsonValue`, otherwise the call fails with `INVALID_ARGUMENT`.
An exception in the evaluated code is `EVALUATE_FAILED` with its message. A
Playwright timeout is `ACTION_FAILED`; a closed page or lost context is
`ENGINE_FAILURE`.
```ts
const count = await browser.evaluate(() => document.querySelectorAll('li').length);
const flag = await browser.evaluate(
(name: string) => window.localStorage.getItem(name),
'featureFlags',
);
```
### Routing
`route`, `unroute`, and `waitForResponse` take a string pattern (`*` within a
path segment, `**` across `/`) or a `RegExp`, both tested against the full
URL; a predicate function is `INVALID_ARGUMENT`. A route survives
`app.restart()`, `app.clearState()`, and session restore.
The handler must decide exactly once with `fulfill`, `continue`, or `abort`;
deciding twice or not at all is `ACTION_FAILED`, as is a `waitForResponse`
that nothing matches inside the deadline. The response resolves once its body
is known: `url`, `status`, and `headers` are always readable, and a body the
browser could not read (a connection reset short of the declared
`Content-Length`, a request the page aborted, or a redirect, whose body the
browser never keeps) rejects `text()` and `json()` with `ACTION_FAILED`
instead of an empty string. A genuinely empty body reads as `''`. A handler
that throws (a failed `expect` on the request, say) fails the next step with
that error, or the attempt at its end when no step follows; a handler still
running then gets the cleanup budget to finish. One that outlives the budget
fails the attempt with `CLEANUP_TIMEOUT`, and whatever it throws afterwards is
dropped.
```ts
await browser.route('**/api/quote', async (route) => {
await route.fulfill({ json: { cents: 4200 } });
});
const response = await browser.waitForResponse('**/api/orders');
expect(response.status).toBe(201);
```
```ts
/** `json` or `body`, never both; neither fulfills with an empty body. */
export type RouteFulfillResponse = {
status?: number;
headers?: Record<string, string>;
} & (
| { json: JsonValue; body?: never }
| { body: string; json?: never }
| { body?: never; json?: never }
);
export interface WebRoute {
/** The intercepted request. */
readonly request: {
readonly url: string;
readonly method: string;
readonly headers: Readonly<Record<string, string>>;
readonly postData?: string;
};
/** Fulfills the intercepted request once. */
fulfill(response: RouteFulfillResponse): Promise<void>;
/** Continues the intercepted request once. */
continue(): Promise<void>;
/** Aborts the intercepted request once. */
abort(): Promise<void>;
}
export interface WebResponse {
/** Response URL. */
readonly url: string;
/** HTTP status. */
readonly status: number;
/** Response headers, lower-cased names. */
readonly headers: Readonly<Record<string, string>>;
/** Parses the response body as JSON. */
json<T = unknown>(): Promise<T>;
/** Reads the response body as text. */
text(): Promise<string>;
}
```
### Cookies and viewport
`setCookies` validates every cookie before setting any; an unparseable
target or a forbidden scheme is `POLICY_DENIED` and nothing is set. For the
`domain` form the scheme follows the base URL and a leading `.` is stripped.
`setViewport` records the new size on the report. It works before the first
navigation too, as Playwright's `setViewportSize` does: the next `app.open`
loads at that size, so a phone-sized test never renders the desktop layout first.
The size holds for the rest of the attempt, through `app.restart()` and
`app.clearState()`.
```ts
export interface CookieFields {
/** Cookie name. */
name: string;
/** Cookie value. */
value: string;
/** Unix timestamp in whole seconds. */
expires?: number;
/** HttpOnly flag. */
httpOnly?: boolean;
/** Secure flag. */
secure?: boolean;
/** SameSite attribute. */
sameSite?: 'Strict' | 'Lax' | 'None';
}
/** `url`, or `domain` with an optional `path`, never both. */
export type Cookie = CookieFields &
(
| { url: string; domain?: never; path?: never }
| { url?: never; domain: string; path?: string }
);
```
```ts
await browser.setCookies([{ url: 'http://localhost:3000', name: 'tz', value: 'UTC' }]);
```
### Dialogs and downloads
A function handler must call `accept` or `dismiss`; one that does neither
has the dialog dismissed and fails the next step with `APP_NOT_OPEN`, as an
unhandled dialog does. One that throws fails the next step, or the attempt at
its end when no step follows, with its error: a failed `expect` stays
`ASSERTION_FAILED`, an unclassified throw is `ENGINE_FAILURE`.
`waitForDownload` registers the file as a `download`
artifact and throws `ACTION_FAILED` when it does not complete in time. A
trigger that resolves in time but starts no download fails with
`no download started within <n>ms; the trigger resolved after <m>ms`, where
the wait includes the trigger's own time. A trigger still running at the
timeout fails with the step timeout, and one that throws with its own error.
On a hosted browser the file comes back through the provider's
[`downloads`](/browser#downloads-on-the-provider).
```ts
/** A native dialog as a test's handler sees it. */
export interface Dialog {
/** The dialog's text. */
readonly message: string;
/** Accepts the dialog once. */
accept(text?: string): Promise<void>;
/** Dismisses the dialog once. */
dismiss(): Promise<void>;
}
```
```ts
const off = await browser.onDialog('accept');
await screen.getByRole('button', 'Delete').tap();
await off();
const file = await browser.waitForDownload(() =>
screen.getByRole('link', 'Export CSV').tap(),
);
```
### keyboard and mouse
Both namespaces are viewport-level. Prefer `locator.press` and
`locator.fill` when a target exists. `keyboard.type` takes plain text only,
never a `Secret`.
### JsonValue
```ts
/** A JSON scalar. */
export type JsonPrimitive = string | number | boolean | null;
/** Data that survives JSON serialization. */
export type JsonValue =
| JsonPrimitive
| { readonly [key: string]: JsonValue }
| readonly JsonValue[];
```
## Semantic capture recovery
When the semantic reader times out, agent observations can recover using a
fresh viewport screenshot. Playwright runs a new secure-field mask sweep
across every reachable frame, including open and closed shadow roots. Every
mask probe must succeed. The observation explicitly reports unavailable
semantics and clears earlier node references.
Recovery requires time left in the operation budget and permission from the
runner. `act` permits it before a secret fill; judgments also require
`vision: true` or `'only'`. Failed masking, cancellation, and hard engine
errors still stop the observation.
When fallback is permitted, the reader reserves one quarter of the remaining
observation budget, capped at two seconds, for the screenshot. The deadline
covers the page walk, metadata and element readback, and nested frames.
Semantic metadata crosses the Playwright connection as one JSON string to
reduce serialization overhead. Actions still use the live element handles
captured with that metadata. Pages that replace `JSON.stringify` or add
`toJSON` methods to object or array prototypes use structured transfer.
Cleanup does not wait for stalled protocol replies. An abandoned reader
cannot reuse node IDs or publish handles over a newer observation.
## Exported types
`WebOptions`, `WebScreencastOptions`, `WebConnectOptions`, `WebBasicAuth`, `BrowserName`,
`BrowserProvider`, `BrowserProviderScope`, `BrowserRequest`, `BrowserLease`,
`BrowserReleaseContext`, `BrowserProviderDownloads`, `BrowserDownloadContext`,
`PlaywrightLiveSurface`, `Browser`, `FrameScreen`,
`BrowserExpectation`, `WebRoute`, `RouteFulfillResponse`, `WebResponse`,
`Cookie`, `CookieFields`, `Dialog`, and `DialogHandler` are exported from the
package for typing config helpers and fixtures. The runtime exports are
`web`, [`surfaceOf`](#surfaceof), and `test`, `describe`, `beforeEach`,
`afterEach`, `beforeAll`, and `afterAll`, typed with the `browser` fixture.
## expect(browser)
`expect(browser)` returns the `BrowserExpectation` the engine attaches: `toHaveURL`,
`toHaveTitle`, and `toHaveClass`. See [browser matchers](/reference/expect#browser-matchers).
## surfaceOf
```ts
import { web, surfaceOf } from '@e2e-dev/web';
const engine = web();
const live = surfaceOf(engine); // PlaywrightLiveSurface | undefined
live!.page(); // the Page of the current attempt
live!.context(); // its BrowserContext
```
Use `surfaceOf(handle)` in a [custom executor](/executors#driving-the-page-yourself)
to access the current Playwright page and context directly. It returns
`undefined` for a handle from another package. The accessors throw
`INVALID_STATE` outside an active attempt. Direct Playwright calls are not
recorded as steps.