uwright 0.0.0-stage → 0.1.4

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
+ Uwright makes browser testing easier to write and cheaper to run. Describe a user journey in Markdown. AI helps you create and update the test, while routine runs replay it without relying on AI to drive every step.
4
+
5
+ ## See it in action
6
+
7
+ ![Edit a Markdown flow in Uwright, then watch it run live against Softprobe Blackbox Explorer](assets/uwright-markdown-live.gif)
8
+
9
+ ## Get started
10
+
11
+ You need Node.js 22.22.3 or later, 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.
12
+
13
+ 1. In your app's repository, create a starter configuration and flow:
14
+
15
+ ```sh
16
+ npx uwright init
17
+ ```
18
+
19
+ `uwright/config.yaml` points to the DemoAir flight search app. For your own app, change `target.baseUrl` and update `uwright/flows/flight-search.flow.md`. The starter flow demonstrates a London to Paris search:
20
+
21
+ ```markdown
22
+ ---
23
+ name: Search London to Paris flights
24
+ ---
25
+
26
+ ## Steps
27
+ 1. Open the flight search home page at `/`.
28
+ 2. Select `London Heathrow (LHR)` as the departure airport and `Paris Charles de Gaulle (CDG)` as the arrival airport. Keep the default departure date.
29
+ 3. Click the Search button.
30
+
31
+ ## Expected Outcome
32
+ - The flight search results page shows at least one button named `Select →`.
33
+ ```
34
+
35
+ 2. Set your API key in the shell. Keep the key out of Git. Validate the flow and open the live viewer:
36
+
37
+ ```sh
38
+ export OPENAI_API_KEY="your-openai-api-key"
39
+ npx uwright validate
40
+ npx uwright watch uwright/flows/flight-search.flow.md
41
+ ```
42
+
43
+ 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/locks/e2e/`. Review the lock and commit it with the Markdown.
44
+
45
+ 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.
46
+
47
+ ## Run and replay tests
48
+
49
+ Run these commands from the directory containing `uwright/`:
50
+
51
+ `npx` downloads Uwright on demand if it is not installed in the repository.
52
+
53
+ ```sh
54
+ npx uwright run # Run all flows in heal mode
55
+ npx uwright run uwright/flows/flight-search.flow.md # Run one flow
56
+ npx uwright run --mode strict # Replay locked actions
57
+ npx uwright run --headed # Open a visible browser for the app under test
58
+ npx uwright watch uwright/flows/flight-search.flow.md --mode strict
59
+ npx uwright watch uwright/flows/flight-search.flow.md --headed
60
+ npx uwright lock status
61
+ npx uwright lock diff
62
+ ```
63
+
64
+ Heal mode reuses recorded actions and can ask the model to find a replacement when an action is missing or stale. It publishes updated locks after a successful run. Strict mode checks the lock before opening the application and replays locked actions without model-selected navigation. Both modes evaluate checks against the current page, and those model-assisted checks can make model calls. A passing replay therefore does not depend on a past model verdict, though model-assisted checks can still vary.
65
+
66
+ 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.
67
+
68
+ 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.
69
+
70
+ ## Organize your tests
71
+
72
+ Commit `uwright/`, including its config, flows, skills, context, non-sensitive fixtures, and locks. Review generated lock changes for sensitive data before committing. `uwright/.gitignore` excludes local artifacts and lock publication state. Existing workspaces using `uwright.config.yaml` continue to work with their configured paths.
73
+
74
+ Uwright records full Playwright traces and screenshots in `uwright/local/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>`.
75
+
76
+ 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.
77
+
78
+ ## Configuration
79
+
80
+ 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 uses `gpt-6-luna` by default for compilation, navigation, and checks. Set `ai.defaultModel` to change all three. Set `ai.compilerModel`, `ai.explorerModel`, or `ai.judgeModel` to override a model for one role:
81
+
82
+ ```yaml
83
+ target:
84
+ baseUrl: http://localhost:3000
85
+ ai:
86
+ defaultModel: gpt-6-luna
87
+ ```
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 remains 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,219 @@
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
+ try {
50
+ await readFile('uwright.config.yaml');
51
+ throw new FlowError('CONFIG_ERROR', 'An existing uwright.config.yaml workspace was found; it has not been changed.');
52
+ }
53
+ catch (error) {
54
+ if (error.code !== 'ENOENT')
55
+ throw error;
56
+ }
57
+ await mkdir('uwright/flows', { recursive: true });
58
+ const files = {
59
+ 'uwright/config.yaml': `version: "2"\ntarget:\n platform: web\n baseUrl: https://demoair.softprobe.ai/\n browser: chromium\n headless: true\n`,
60
+ 'uwright/flows/flight-search.flow.md': `---\nname: Search London to Paris flights\n---\n\n## Steps\n1. Open the flight search home page at \`/\`.\n2. Select \`London Heathrow (LHR)\` as the departure airport and \`Paris Charles de Gaulle (CDG)\` as the arrival airport. Keep the default departure date.\n3. Click the Search button.\n\n## Expected Outcome\n- The flight search results page shows at least one button named \`Select →\`.\n`,
61
+ };
62
+ const ignorePath = 'uwright/.gitignore';
63
+ const ignore = [
64
+ '/local/',
65
+ '/locks/**/.write-lock/',
66
+ '/locks/**/.transaction/',
67
+ '/locks/**/*.tmp-*',
68
+ '/locks/generations/',
69
+ ];
70
+ let existing = '';
71
+ try {
72
+ existing = await readFile(ignorePath, 'utf8');
73
+ }
74
+ catch (error) {
75
+ if (error.code !== 'ENOENT')
76
+ throw error;
77
+ }
78
+ const lines = new Set(existing.split(/\r?\n/));
79
+ const missing = ignore.filter((line) => !lines.has(line));
80
+ if (missing.length) {
81
+ await writeFile(ignorePath, existing + (existing && !existing.endsWith('\n') ? '\n' : '') + missing.join('\n') + '\n');
82
+ process.stdout.write(`Updated ${ignorePath}\n`);
83
+ }
84
+ for (const [file, content] of Object.entries(files)) {
85
+ try {
86
+ await writeFile(file, content, { flag: 'wx' });
87
+ process.stdout.write(`Created ${file}\n`);
88
+ }
89
+ catch (error) {
90
+ if (error.code !== 'EEXIST')
91
+ throw error;
92
+ process.stdout.write(`Kept ${file}\n`);
93
+ }
94
+ }
95
+ process.stdout.write('Commit uwright/ and review generated recordings for sensitive data. Local files are ignored.\n');
96
+ }
97
+ async function main() {
98
+ const [cmd, ...args] = process.argv.slice(2);
99
+ if (!cmd || cmd === '--help' || cmd === '-h') {
100
+ process.stdout.write(help);
101
+ return;
102
+ }
103
+ if (cmd === 'init') {
104
+ await init();
105
+ return;
106
+ }
107
+ if (cmd === 'mcp') {
108
+ await startMcp();
109
+ return;
110
+ }
111
+ const ws = await loadWorkspace();
112
+ if (cmd === 'watch') {
113
+ const { headed, modeSpecified, mode: modeArg, selected } = parseCliArgs(args);
114
+ const mode = modeSpecified ? modeArg : 'heal';
115
+ if (mode !== 'heal' && mode !== 'strict')
116
+ throw new FlowError('CONFIG_ERROR', 'Watch mode must be heal or strict');
117
+ applyHeaded(ws.config, headed);
118
+ const flow = ws.flows.find((f) => f.path === path.resolve(selected ?? '') || f.frontmatter.name === selected);
119
+ if (!flow)
120
+ throw new FlowError('FLOW_NOT_FOUND', 'Specify a flow to watch');
121
+ if (ws.config.execution.runtime !== 'e2e')
122
+ throw new FlowError('UNSUPPORTED_RUNTIME', 'Watch requires execution.runtime: e2e');
123
+ const watch = new Watch(flow.path, flow.frontmatter.name ?? path.basename(flow.path), ws.config.ai.compilerModel);
124
+ watch.setRerun(async () => {
125
+ const updated = await loadWorkspace();
126
+ applyHeaded(updated.config, headed);
127
+ const next = updated.flows.find((f) => f.path === flow.path);
128
+ if (!next)
129
+ throw new FlowError('FLOW_NOT_FOUND', 'Flow no longer exists');
130
+ await runE2E(updated, next, mode, watch);
131
+ });
132
+ const url = await watch.start();
133
+ process.stdout.write(`Watch: ${url}\nOpening your browser. Review the plan and select Start test. Press Ctrl-C to stop the watch server.\n`);
134
+ await openWatch(url);
135
+ await runE2E(ws, flow, mode, watch).catch((error) => watch.fail(error));
136
+ return;
137
+ }
138
+ if (cmd === 'validate') {
139
+ process.stdout.write(`Validated ${ws.flows.length} flows and ${ws.skills.length} skills. Natural-language references are checked during compilation.\n`);
140
+ return;
141
+ }
142
+ if (cmd === 'run') {
143
+ const { headed, modeSpecified, mode: modeArg, selected } = parseCliArgs(args);
144
+ const candidate = modeSpecified ? modeArg : ws.config.execution.mode;
145
+ if (!candidate || !['strict', 'heal', 'record', 'off'].includes(candidate))
146
+ throw new FlowError('CONFIG_ERROR', 'Invalid execution mode');
147
+ applyHeaded(ws.config, headed);
148
+ const flows = selected
149
+ ? ws.flows.filter((f) => f.path === path.resolve(selected) || f.frontmatter.name === selected)
150
+ : ws.flows;
151
+ if (!flows.length)
152
+ throw new FlowError('FLOW_NOT_FOUND', 'No flows matched');
153
+ process.stdout.write(`Running ${flows.length} flow${flows.length === 1 ? '' : 's'} (${candidate} mode).\n`);
154
+ let passed = 0;
155
+ for (const flow of flows) {
156
+ const name = path.relative(ws.root, flow.path);
157
+ process.stdout.write(`RUN ${name}\n`);
158
+ try {
159
+ if (ws.config.execution.runtime === 'e2e') {
160
+ const result = await runE2E(ws, flow, candidate);
161
+ process.stdout.write(`PASS ${name} (${result.compilerCalls} compiler calls, ${result.navigationModelCalls} navigation calls, ${result.judgments} model-assisted checks)\n`);
162
+ }
163
+ else {
164
+ const result = await new Runner(ws, candidate).run(flow);
165
+ process.stdout.write(`PASS ${name} (${result.modelCalls} model calls)\n`);
166
+ }
167
+ passed++;
168
+ }
169
+ catch (error) {
170
+ process.stderr.write(`FAIL ${name} (${passed} passed, ${flows.length - passed - 1} not run)\n`);
171
+ throw error;
172
+ }
173
+ }
174
+ process.stdout.write(`Completed: ${passed} passed.\n`);
175
+ return;
176
+ }
177
+ if (cmd === 'lock') {
178
+ if (args[0] === 'recover') {
179
+ await recoverLocks(ws);
180
+ await recoverE2ELocks(ws);
181
+ process.stdout.write('Lock recovery complete.\n');
182
+ return;
183
+ }
184
+ if (args[0] === 'migrate') {
185
+ await migrateLegacyLocks(ws);
186
+ process.stdout.write('Legacy locks migrated.\n');
187
+ return;
188
+ }
189
+ if (args[0] === 'diff') {
190
+ process.stdout.write(JSON.stringify(await diffLocks(ws), null, 2) + '\n');
191
+ return;
192
+ }
193
+ if (ws.config.execution.runtime === 'e2e') {
194
+ for (const doc of ws.flows) {
195
+ const status = await e2eLockStatus(ws, doc);
196
+ process.stdout.write(`${path.relative(ws.root, doc.path)} ${status}\n`);
197
+ }
198
+ return;
199
+ }
200
+ const locks = await readLocks(ws);
201
+ for (const doc of ws.flows) {
202
+ let status = 'fresh';
203
+ try {
204
+ assertFresh(ws, getLock(ws, locks, doc), doc);
205
+ }
206
+ catch (e) {
207
+ status = e instanceof FlowError ? e.code : 'invalid';
208
+ }
209
+ process.stdout.write(`${path.relative(ws.root, doc.path)} ${status}\n`);
210
+ }
211
+ return;
212
+ }
213
+ throw new FlowError('UNKNOWN_COMMAND', `Unknown command ${cmd}`);
214
+ }
215
+ main().catch((e) => {
216
+ const error = e instanceof FlowError ? e : new FlowError('ERROR', String(e), 1);
217
+ process.stderr.write(`${error.code}: ${error.message}\n`);
218
+ process.exitCode = error.exitCode;
219
+ });
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
+ }