uwright 0.0.0-stage → 0.1.1

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
@@ -1,3 +1,113 @@
1
- # Temporary Holding Version
1
+ # Uwright
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Write browser tests in Markdown and watch them run. Uwright uses a model to interpret your steps, drives the browser, and saves an execution lock that you can review and commit with your tests.
4
+
5
+ Uwright is an early preview. Model-assisted checks run against the current page on each run, and an unchanged lock cannot guarantee a passing test.
6
+
7
+ ## Get started
8
+
9
+ You need Node.js 22.22.3 or later on the 22.x line, an OpenAI API key for a supported model, and a web app to test. Uwright defaults to `gpt-6-luna`, but you can configure other OpenAI models your key can access. `npx` fetches Uwright when needed, and the first test run downloads Chromium automatically.
10
+
11
+ 1. In your app's repository, create a starter configuration and flow:
12
+
13
+ ```sh
14
+ npx uwright init
15
+ ```
16
+
17
+ Set `target.baseUrl` in `uwright.config.yaml` to your running app's URL. Open `flows/example.flow.md` and describe the journey and expected outcome. For example:
18
+
19
+ ```markdown
20
+ ---
21
+ name: Open products
22
+ ---
23
+
24
+ ## Steps
25
+ 1. Open the home page.
26
+ 2. Click the Products link.
27
+
28
+ ## Expected Outcome
29
+ - The Products heading is visible.
30
+ ```
31
+
32
+ 2. Set `OPENAI_API_KEY` in your shell. Keep the key out of Git. Validate the flow and open the live viewer:
33
+
34
+ ```sh
35
+ npx uwright validate
36
+ npx uwright watch flows/example.flow.md
37
+ ```
38
+
39
+ 3. Review the steps in the browser and select **Start test**. The viewer shows the application, actions, checks, and logs. When the flow passes, Uwright saves its lock under `.uwright/lock/e2e/`. Review the lock and commit it with the Markdown.
40
+
41
+ If the viewer does not open, use the URL printed in the terminal. Press Ctrl-C in the terminal to stop the watch server. The URL grants control of the local run; keep it private.
42
+
43
+ ## Run and replay tests
44
+
45
+ Run these commands from the directory containing `uwright.config.yaml`:
46
+
47
+ `npx` downloads Uwright on demand if it is not installed in the repository.
48
+
49
+ ```sh
50
+ npx uwright run # Run all flows in heal mode
51
+ npx uwright run flows/example.flow.md # Run one flow
52
+ npx uwright run --mode strict # Replay locked actions
53
+ npx uwright run --headed # Open a visible browser for the app under test
54
+ npx uwright watch flows/example.flow.md --mode strict
55
+ npx uwright watch flows/example.flow.md --headed
56
+ npx uwright lock status
57
+ npx uwright lock diff
58
+ ```
59
+
60
+ Heal mode reuses recorded actions and can ask the model to find a replacement when the UI changes. It publishes updated locks after a successful run. Strict mode checks the lock before opening the application and blocks model-selected navigation. Both modes evaluate model-assisted checks against the current page. A check can make model calls in strict mode.
61
+
62
+ The terminal shows each flow as it starts, step progress, the result, and the saved HTML report path. A run stops on the first failure and reports how many flows were not run.
63
+
64
+ Watch lets you pause after a step, control the page, edit the Markdown, and ask the model to help clarify an assertion. Save the Markdown before selecting **Rerun**. Environment variables are read when watch starts. Restart it after changing them.
65
+
66
+ ## Organize your tests
67
+
68
+ Commit `uwright.config.yaml`, flows and skills in `flows/`, relevant `CONTEXT.md` files, non-sensitive test fixtures, and the corresponding `.uwright/lock/e2e/` files. Review lock changes like code. `uwright init` adds ignore rules for local artifacts and `.env` files without removing existing entries.
69
+
70
+ Uwright records full Playwright traces and screenshots in `.uwright/artifacts/`. These can contain credentials, page content, and network data. Keep them out of Git and restrict access to CI artifacts. Each run prints the report and trace paths. Open a trace with `npx playwright show-trace <path-to-trace.zip>`.
71
+
72
+ For sign-in flows, declare secret environment variable names in the flow or skill and supply their values through the environment. Do not put secret values in Markdown or lock files. Review generated locks before committing them.
73
+
74
+ ## Configuration
75
+
76
+ The `execution` section is optional. Uwright defaults to the `e2e` runtime and `heal` mode, including in CI. Set `execution.runtime` or `execution.mode` to override them, or use `--mode` for a single run. Uwright defaults to OpenAI and `gpt-6-luna` for compilation, navigation, and checks. Set `ai.compilerModel`, `ai.explorerModel`, and `ai.judgeModel` to use other OpenAI models:
77
+
78
+ ```yaml
79
+ target:
80
+ baseUrl: http://localhost:3000
81
+ ai:
82
+ compilerModel: your-openai-model
83
+ explorerModel: your-openai-model
84
+ judgeModel: your-openai-model
85
+ ```
86
+
87
+ Replace `your-openai-model` with a model ID available to your API key.
88
+
89
+ The model-call limit applies per e2e operation, rather than across an entire flow. See the [execution lock specification](design/lockfile-spec.md) for the lock format, recovery, and current limits. If an interrupted publication blocks a run, use `npx uwright lock recover`. The command refuses to overwrite conflicting external edits.
90
+
91
+ ## Current limits
92
+
93
+ - The e2e runtime is a preview. Model judgments are not deterministic and may fail or be incorrect. Review the report and clarify assertions when necessary.
94
+ - A recorded relative target such as “first session” can refer to the previously recorded item after the list order changes. Check the selected item independently.
95
+ - Natural-language guardrails are model instructions, not independently enforced safety rules. Use a test environment and test data.
96
+ - OpenAI is the implemented model provider. Mobile drivers and ACP are not implemented. Static validation cannot resolve every natural-language reference.
97
+ - Locks do not yet support all dynamic values and asset-path inputs. Lock diffs show full changed records rather than a concise semantic summary.
98
+ - Tests can fail when the target UI, data, network, authentication, or model provider changes. Full trace creation can also fail.
99
+
100
+ The legacy runtime and DemoAir example remain available in the source repository. See the [PRD](prd.md) and [implementation plan](implementation-plan.md) for planned work.
101
+
102
+ ## Develop and release
103
+
104
+ ```sh
105
+ npm ci
106
+ npx playwright install chromium
107
+ npm run typecheck
108
+ npm test
109
+ npm run build
110
+ node tests/mcp-smoke.mjs
111
+ ```
112
+
113
+ See [RELEASING.md](RELEASING.md) for npm trusted publishing and the `v1.2.3` tag convention.
@@ -0,0 +1,23 @@
1
+ import { access } from 'node:fs/promises';
2
+ import { execFile } from 'node:child_process';
3
+ import { promisify } from 'node:util';
4
+ import { createRequire } from 'node:module';
5
+ import path from 'node:path';
6
+ import { chromium, firefox, webkit } from 'playwright';
7
+ const execFileAsync = promisify(execFile);
8
+ const require = createRequire(import.meta.url);
9
+ export async function ensureBrowserInstalled(browser) {
10
+ const browserType = { chromium, firefox, webkit }[browser];
11
+ const executablePath = browserType.executablePath();
12
+ try {
13
+ await access(executablePath);
14
+ return;
15
+ }
16
+ catch {
17
+ // Install the configured browser on demand so `npx uwright` works in a fresh project.
18
+ }
19
+ process.stdout.write(`Downloading ${browser} for Uwright's first run...\n`);
20
+ const playwrightCli = path.join(path.dirname(require.resolve('playwright')), 'cli.js');
21
+ await execFileAsync(process.execPath, [playwrightCli, 'install', browser], { maxBuffer: 10 * 1024 * 1024 });
22
+ await access(executablePath);
23
+ }
@@ -0,0 +1,12 @@
1
+ export function parseCliArgs(args) {
2
+ const headed = args.includes('--headed');
3
+ const modeIndex = args.indexOf('--mode');
4
+ const modeSpecified = modeIndex >= 0;
5
+ const mode = modeSpecified ? args[modeIndex + 1] : undefined;
6
+ const selected = args.find((x, i) => !x.startsWith('-') && (!modeSpecified || i !== modeIndex + 1));
7
+ return { headed, modeSpecified, mode, selected };
8
+ }
9
+ export function applyHeaded(config, headed) {
10
+ if (headed)
11
+ config.target.headless = false;
12
+ }
package/dist/cli.js ADDED
@@ -0,0 +1,213 @@
1
+ #!/usr/bin/env node
2
+ import { execFile } from 'node:child_process';
3
+ import { mkdir, readFile, writeFile } from 'node:fs/promises';
4
+ import path from 'node:path';
5
+ import { promisify } from 'node:util';
6
+ import { applyHeaded, parseCliArgs } from './cli-args.js';
7
+ import { diffLocks } from './diff.js';
8
+ import { recoverE2ELocks } from './e2e-lock.js';
9
+ import { runE2E } from './e2e-runner.js';
10
+ import { e2eLockStatus } from './e2e-status.js';
11
+ import { assertFresh, getLock, migrateLegacyLocks, readLocks, recoverLocks } from './lock.js';
12
+ import { startMcp } from './mcp.js';
13
+ import { FlowError } from './model.js';
14
+ import { Runner } from './runner.js';
15
+ import { Watch } from './watch.js';
16
+ import { loadWorkspace } from './workspace.js';
17
+ const execFileAsync = promisify(execFile);
18
+ async function openWatch(url) {
19
+ const [command, ...args] = process.platform === 'darwin'
20
+ ? ['open', url]
21
+ : process.platform === 'win32'
22
+ ? ['rundll32', 'url.dll,FileProtocolHandler', url]
23
+ : ['xdg-open', url];
24
+ try {
25
+ await execFileAsync(command, args);
26
+ }
27
+ catch {
28
+ process.stderr.write('Could not open the browser automatically. Open the Watch URL above.\n');
29
+ }
30
+ }
31
+ const help = `Uwright
32
+
33
+ Usage: uwright <command>
34
+
35
+ init Create a starter workspace
36
+ validate Validate Markdown and configuration
37
+ watch <flow> [--mode strict|heal] [--headed]
38
+ run [flow] [--mode strict|heal|record|off] [--headed]
39
+ lock status Show lock coverage and drift
40
+ lock diff Compare locks with Git HEAD
41
+ lock recover Complete an interrupted lock update
42
+ lock migrate Migrate legacy generation locks
43
+ mcp Start the MCP stdio server
44
+
45
+ Traces are recorded by default and can contain secrets.
46
+ Use --headed to open a visible browser for the application under test.
47
+ `;
48
+ async function init() {
49
+ await mkdir('flows', { recursive: true });
50
+ const ignore = [
51
+ '.uwright/artifacts/',
52
+ '.uwright/lock/.write-lock/',
53
+ '.uwright/lock/e2e/**/.write-lock/',
54
+ '.uwright/lock/e2e/**/.transaction/',
55
+ '.uwright/lock/.transaction/',
56
+ '.uwright/lock/**/*.tmp-*',
57
+ '.uwright/lock/generations/',
58
+ '.uwright/legacy-locks/',
59
+ '.env',
60
+ '.env.*',
61
+ '!.env.example',
62
+ ];
63
+ let existing = '';
64
+ try {
65
+ existing = await readFile('.gitignore', 'utf8');
66
+ }
67
+ catch (e) {
68
+ if (e.code !== 'ENOENT')
69
+ throw e;
70
+ }
71
+ const lines = new Set(existing.split(/\r?\n/));
72
+ const missing = ignore.filter((line) => !lines.has(line));
73
+ if (missing.length)
74
+ await writeFile('.gitignore', existing + (existing && !existing.endsWith('\n') ? '\n' : '') + missing.join('\n') + '\n');
75
+ const files = {
76
+ 'uwright.config.yaml': `version: "2"\nflowsDir: ./flows\nlockDir: ./.uwright/lock\nartifactsDir: ./.uwright/artifacts\ntarget:\n platform: web\n baseUrl: http://localhost:3000\n browser: chromium\n headless: true\n`,
77
+ 'flows/example.flow.md': `---\nname: Example\n---\n\n## Steps\n1. Open the home page.\n\n## Expected Outcome\n- The page is visible.\n`,
78
+ };
79
+ for (const [f, content] of Object.entries(files)) {
80
+ try {
81
+ await writeFile(f, content, { flag: 'wx' });
82
+ process.stdout.write(`Created ${f}\n`);
83
+ }
84
+ catch (e) {
85
+ if (e.code !== 'EEXIST')
86
+ throw e;
87
+ process.stdout.write(`Kept ${f}\n`);
88
+ }
89
+ }
90
+ }
91
+ async function main() {
92
+ const [cmd, ...args] = process.argv.slice(2);
93
+ if (!cmd || cmd === '--help' || cmd === '-h') {
94
+ process.stdout.write(help);
95
+ return;
96
+ }
97
+ if (cmd === 'init') {
98
+ await init();
99
+ return;
100
+ }
101
+ if (cmd === 'mcp') {
102
+ await startMcp();
103
+ return;
104
+ }
105
+ const ws = await loadWorkspace();
106
+ if (cmd === 'watch') {
107
+ const { headed, modeSpecified, mode: modeArg, selected } = parseCliArgs(args);
108
+ const mode = modeSpecified ? modeArg : 'heal';
109
+ if (mode !== 'heal' && mode !== 'strict')
110
+ throw new FlowError('CONFIG_ERROR', 'Watch mode must be heal or strict');
111
+ applyHeaded(ws.config, headed);
112
+ const flow = ws.flows.find((f) => f.path === path.resolve(selected ?? '') || f.frontmatter.name === selected);
113
+ if (!flow)
114
+ throw new FlowError('FLOW_NOT_FOUND', 'Specify a flow to watch');
115
+ if (ws.config.execution.runtime !== 'e2e')
116
+ throw new FlowError('UNSUPPORTED_RUNTIME', 'Watch requires execution.runtime: e2e');
117
+ const watch = new Watch(flow.path, flow.frontmatter.name ?? path.basename(flow.path), ws.config.ai.compilerModel);
118
+ watch.setRerun(async () => {
119
+ const updated = await loadWorkspace();
120
+ applyHeaded(updated.config, headed);
121
+ const next = updated.flows.find((f) => f.path === flow.path);
122
+ if (!next)
123
+ throw new FlowError('FLOW_NOT_FOUND', 'Flow no longer exists');
124
+ await runE2E(updated, next, mode, watch);
125
+ });
126
+ const url = await watch.start();
127
+ process.stdout.write(`Watch: ${url}\nOpening your browser. Review the plan and select Start test. Press Ctrl-C to stop the watch server.\n`);
128
+ await openWatch(url);
129
+ await runE2E(ws, flow, mode, watch).catch((error) => watch.fail(error));
130
+ return;
131
+ }
132
+ if (cmd === 'validate') {
133
+ process.stdout.write(`Validated ${ws.flows.length} flows and ${ws.skills.length} skills. Natural-language references are checked during compilation.\n`);
134
+ return;
135
+ }
136
+ if (cmd === 'run') {
137
+ const { headed, modeSpecified, mode: modeArg, selected } = parseCliArgs(args);
138
+ const candidate = modeSpecified ? modeArg : ws.config.execution.mode;
139
+ if (!candidate || !['strict', 'heal', 'record', 'off'].includes(candidate))
140
+ throw new FlowError('CONFIG_ERROR', 'Invalid execution mode');
141
+ applyHeaded(ws.config, headed);
142
+ const flows = selected
143
+ ? ws.flows.filter((f) => f.path === path.resolve(selected) || f.frontmatter.name === selected)
144
+ : ws.flows;
145
+ if (!flows.length)
146
+ throw new FlowError('FLOW_NOT_FOUND', 'No flows matched');
147
+ process.stdout.write(`Running ${flows.length} flow${flows.length === 1 ? '' : 's'} (${candidate} mode).\n`);
148
+ let passed = 0;
149
+ for (const flow of flows) {
150
+ const name = path.relative(ws.root, flow.path);
151
+ process.stdout.write(`RUN ${name}\n`);
152
+ try {
153
+ if (ws.config.execution.runtime === 'e2e') {
154
+ const result = await runE2E(ws, flow, candidate);
155
+ process.stdout.write(`PASS ${name} (${result.compilerCalls} compiler calls, ${result.navigationModelCalls} navigation calls, ${result.judgments} model-assisted checks)\n`);
156
+ }
157
+ else {
158
+ const result = await new Runner(ws, candidate).run(flow);
159
+ process.stdout.write(`PASS ${name} (${result.modelCalls} model calls)\n`);
160
+ }
161
+ passed++;
162
+ }
163
+ catch (error) {
164
+ process.stderr.write(`FAIL ${name} (${passed} passed, ${flows.length - passed - 1} not run)\n`);
165
+ throw error;
166
+ }
167
+ }
168
+ process.stdout.write(`Completed: ${passed} passed.\n`);
169
+ return;
170
+ }
171
+ if (cmd === 'lock') {
172
+ if (args[0] === 'recover') {
173
+ await recoverLocks(ws);
174
+ await recoverE2ELocks(ws);
175
+ process.stdout.write('Lock recovery complete.\n');
176
+ return;
177
+ }
178
+ if (args[0] === 'migrate') {
179
+ await migrateLegacyLocks(ws);
180
+ process.stdout.write('Legacy locks migrated.\n');
181
+ return;
182
+ }
183
+ if (args[0] === 'diff') {
184
+ process.stdout.write(JSON.stringify(await diffLocks(ws), null, 2) + '\n');
185
+ return;
186
+ }
187
+ if (ws.config.execution.runtime === 'e2e') {
188
+ for (const doc of ws.flows) {
189
+ const status = await e2eLockStatus(ws, doc);
190
+ process.stdout.write(`${path.relative(ws.root, doc.path)} ${status}\n`);
191
+ }
192
+ return;
193
+ }
194
+ const locks = await readLocks(ws);
195
+ for (const doc of ws.flows) {
196
+ let status = 'fresh';
197
+ try {
198
+ assertFresh(ws, getLock(ws, locks, doc), doc);
199
+ }
200
+ catch (e) {
201
+ status = e instanceof FlowError ? e.code : 'invalid';
202
+ }
203
+ process.stdout.write(`${path.relative(ws.root, doc.path)} ${status}\n`);
204
+ }
205
+ return;
206
+ }
207
+ throw new FlowError('UNKNOWN_COMMAND', `Unknown command ${cmd}`);
208
+ }
209
+ main().catch((e) => {
210
+ const error = e instanceof FlowError ? e : new FlowError('ERROR', String(e), 1);
211
+ process.stderr.write(`${error.code}: ${error.message}\n`);
212
+ process.exitCode = error.exitCode;
213
+ });
package/dist/diff.js ADDED
@@ -0,0 +1,62 @@
1
+ import { execFile } from 'node:child_process';
2
+ import { readdir, realpath } from 'node:fs/promises';
3
+ import path from 'node:path';
4
+ import { isDeepStrictEqual, promisify } from 'node:util';
5
+ import { readE2ELockFiles } from './e2e-lock.js';
6
+ import { readLocks } from './lock.js';
7
+ import { FlowError } from './model.js';
8
+ const git = promisify(execFile);
9
+ async function e2eFiles(base, dir = 'e2e') {
10
+ if (dir.endsWith('.recordings')) {
11
+ const files = await readE2ELockFiles(path.join(base, dir));
12
+ return Object.fromEntries([...files].map(([name, content]) => [path.posix.join(dir, name), JSON.parse(content)]));
13
+ }
14
+ let children;
15
+ try {
16
+ children = await readdir(path.join(base, dir), { withFileTypes: true });
17
+ }
18
+ catch (error) {
19
+ if (error.code === 'ENOENT')
20
+ return {};
21
+ throw error;
22
+ }
23
+ const results = await Promise.all(children
24
+ .filter((child) => !child.name.startsWith('.'))
25
+ .map(async (child) => {
26
+ const name = path.posix.join(dir, child.name);
27
+ if (child.isDirectory())
28
+ return e2eFiles(base, name);
29
+ return {};
30
+ }));
31
+ return Object.assign({}, ...results);
32
+ }
33
+ export async function diffLocks(ws) {
34
+ let root;
35
+ try {
36
+ root = (await git('git', ['rev-parse', '--show-toplevel'], { cwd: ws.root })).stdout.trim();
37
+ await git('git', ['rev-parse', '--verify', 'HEAD'], { cwd: ws.root });
38
+ }
39
+ catch {
40
+ throw new FlowError('LOCK_DIFF_UNAVAILABLE', 'Lock diff requires a Git repository with a HEAD commit');
41
+ }
42
+ root = await realpath(root);
43
+ const basePath = path.resolve(ws.root, ws.config.lockDir);
44
+ const base = await realpath(basePath).catch(() => basePath);
45
+ const dir = path.relative(root, base).split(path.sep).join('/');
46
+ if (dir.startsWith('../') || path.isAbsolute(dir))
47
+ throw new FlowError('LOCK_DIFF_UNAVAILABLE', 'Lock directory is outside the Git repository');
48
+ const listing = await git('git', ['ls-tree', '-r', '--name-only', '-z', 'HEAD', '--', dir], { cwd: root });
49
+ const previous = {};
50
+ const isE2E = ws.config.execution.runtime === 'e2e';
51
+ for (const file of listing.stdout
52
+ .split('\0')
53
+ .filter((file) => (isE2E ? /\/e2e\/.*\/(?:[a-f0-9]{64}|plan)\.json$/.test(file) : file.endsWith('.lock.json')))) {
54
+ const data = await git('git', ['show', `HEAD:${file}`], { cwd: root });
55
+ previous[path.posix.relative(dir, file)] = JSON.parse(data.stdout);
56
+ }
57
+ const next = isE2E ? await e2eFiles(base) : await readLocks(ws);
58
+ const keys = [...new Set([...Object.keys(previous), ...Object.keys(next)])].sort();
59
+ return keys.flatMap((name) => isDeepStrictEqual(previous[name], next[name])
60
+ ? []
61
+ : [{ path: name, before: previous[name] ?? null, after: next[name] ?? null }]);
62
+ }
package/dist/driver.js ADDED
@@ -0,0 +1,187 @@
1
+ import { mkdir } from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ import { chromium, firefox, webkit, } from 'playwright';
4
+ import { ensureBrowserInstalled } from './browser-install.js';
5
+ import { FlowError } from './model.js';
6
+ class MissingLocatorError extends FlowError {
7
+ constructor(message) {
8
+ super('CACHE_STALE', message, 3);
9
+ }
10
+ }
11
+ export class WebDriver {
12
+ config;
13
+ tracePath;
14
+ browser;
15
+ context;
16
+ page;
17
+ constructor(config, tracePath) {
18
+ this.config = config;
19
+ this.tracePath = tracePath;
20
+ }
21
+ async start() {
22
+ await ensureBrowserInstalled(this.config.target.browser);
23
+ this.browser = await { chromium, firefox, webkit }[this.config.target.browser].launch({
24
+ headless: this.config.target.headless,
25
+ });
26
+ this.context = await this.browser.newContext({ viewport: this.config.target.viewport });
27
+ this.context.setDefaultTimeout(this.config.execution.defaultTimeoutMs);
28
+ await this.context.tracing.start({ screenshots: true, snapshots: true, sources: false });
29
+ this.page = await this.context.newPage();
30
+ }
31
+ async stop() {
32
+ if (this.context) {
33
+ await mkdir(path.dirname(this.tracePath), { recursive: true });
34
+ await this.context.tracing.stop({ path: this.tracePath });
35
+ await this.context.close();
36
+ }
37
+ if (this.browser)
38
+ await this.browser.close();
39
+ }
40
+ async locate(loc) {
41
+ const deadline = Date.now() + this.config.execution.defaultTimeoutMs;
42
+ for (;;) {
43
+ try {
44
+ return await this.locateOnce(loc);
45
+ }
46
+ catch (e) {
47
+ if (!(e instanceof MissingLocatorError) || Date.now() >= deadline)
48
+ throw e;
49
+ await new Promise((resolve) => setTimeout(resolve, 100));
50
+ }
51
+ }
52
+ }
53
+ async locateOnce(loc) {
54
+ const candidates = [];
55
+ if (loc.testId)
56
+ candidates.push(this.page.getByTestId(loc.testId));
57
+ if (loc.parentContext)
58
+ candidates.push(this.page
59
+ .getByRole('dialog', { name: loc.parentContext, exact: true })
60
+ .getByRole(loc.role, { name: loc.name, exact: true }));
61
+ candidates.push(this.page.getByRole(loc.role, { name: loc.name, exact: true }));
62
+ for (const c of candidates) {
63
+ const n = await c.count();
64
+ if (n === 1)
65
+ return c;
66
+ if (n > 1 && loc.nth !== undefined && loc.nth < n)
67
+ return c.nth(loc.nth);
68
+ if (n > 1)
69
+ throw new FlowError('CACHE_STALE', `Ambiguous ${loc.role} ${loc.name}`, 3);
70
+ }
71
+ if (loc.role === 'combobox' && loc.name) {
72
+ const controls = this.page.getByRole('combobox', { name: '', exact: true });
73
+ const matches = [];
74
+ for (let i = 0; i < (await controls.count()); i++) {
75
+ const control = controls.nth(i);
76
+ const labels = await control.locator('..').locator(':scope > label').allTextContents();
77
+ if (labels.some((label) => label.trim() === loc.name))
78
+ matches.push(control);
79
+ }
80
+ if (matches.length === 1)
81
+ return matches[0];
82
+ if (matches.length > 1)
83
+ throw new FlowError('CACHE_STALE', `Ambiguous adjacent label ${loc.name}`, 3);
84
+ }
85
+ throw new MissingLocatorError(`Missing ${loc.role} ${loc.name}`);
86
+ }
87
+ async action(action, value) {
88
+ try {
89
+ switch (action.kind) {
90
+ case 'open':
91
+ await this.page.goto(new URL(action.url, this.config.target.baseUrl).href);
92
+ break;
93
+ case 'click':
94
+ await (await this.locate(action.locator)).click();
95
+ break;
96
+ case 'fill':
97
+ await (await this.locate(action.locator)).fill(value ?? '');
98
+ break;
99
+ case 'select': {
100
+ const select = await this.locate(action.locator);
101
+ const chosen = value ?? '';
102
+ const labels = await select.locator('option').allTextContents();
103
+ await select.selectOption(labels.some((x) => x.trim() === chosen) ? { label: chosen } : chosen);
104
+ break;
105
+ }
106
+ case 'upload_file':
107
+ await (await this.locate(action.locator)).setInputFiles(value ?? '');
108
+ break;
109
+ case 'press':
110
+ await this.page.keyboard.press(action.key);
111
+ break;
112
+ case 'scroll':
113
+ await this.page.mouse.wheel(0, action.direction === 'down' ? action.amount : -action.amount);
114
+ break;
115
+ }
116
+ }
117
+ catch (e) {
118
+ if (e instanceof FlowError)
119
+ throw e;
120
+ throw new FlowError('CACHE_STALE', `Action ${action.kind} failed: ${String(e)}`, 3);
121
+ }
122
+ }
123
+ async assertion(a) {
124
+ const deadline = Date.now() + this.config.execution.defaultTimeoutMs;
125
+ do {
126
+ if (await this.assertionOnce(a))
127
+ return true;
128
+ if (Date.now() < deadline)
129
+ await new Promise((resolve) => setTimeout(resolve, 100));
130
+ } while (Date.now() < deadline);
131
+ return false;
132
+ }
133
+ async assertionOnce(a) {
134
+ try {
135
+ switch (a.kind) {
136
+ case 'url_contains':
137
+ return this.page.url().includes(a.value);
138
+ case 'visible_text':
139
+ return await this.page.getByText(a.value, { exact: false }).first().isVisible();
140
+ case 'not_visible_text':
141
+ return !(await this.page.getByText(a.value, { exact: false }).first().isVisible());
142
+ case 'locator_state': {
143
+ const loc = await this.locate(a.locator);
144
+ switch (a.state) {
145
+ case 'visible':
146
+ return loc.isVisible();
147
+ case 'hidden':
148
+ return loc.isHidden();
149
+ case 'enabled':
150
+ return loc.isEnabled();
151
+ case 'disabled':
152
+ return loc.isDisabled();
153
+ case 'checked':
154
+ return loc.isChecked();
155
+ case 'visible_and_enabled':
156
+ return (await loc.isVisible()) && (await loc.isEnabled());
157
+ }
158
+ }
159
+ case 'visual_judge_fallback':
160
+ throw new FlowError('JUDGE_REQUIRED', 'Visual judge is not configured', 1);
161
+ }
162
+ }
163
+ catch (e) {
164
+ if (e instanceof FlowError && e.code === 'JUDGE_REQUIRED')
165
+ throw e;
166
+ return false;
167
+ }
168
+ }
169
+ async observe() {
170
+ return await this.page.locator('body').ariaSnapshot();
171
+ }
172
+ async waitForChange(previous) {
173
+ const deadline = Date.now() + this.config.execution.defaultTimeoutMs;
174
+ do {
175
+ try {
176
+ if ((await this.observe()) !== previous)
177
+ return true;
178
+ }
179
+ catch {
180
+ /* A navigation can temporarily detach the body. */
181
+ }
182
+ if (Date.now() < deadline)
183
+ await new Promise((resolve) => setTimeout(resolve, 200));
184
+ } while (Date.now() < deadline);
185
+ return false;
186
+ }
187
+ }