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/dist/runner.js ADDED
@@ -0,0 +1,447 @@
1
+ import { randomBytes, randomUUID } from 'node:crypto';
2
+ import { access } from 'node:fs/promises';
3
+ import path from 'node:path';
4
+ import { openai } from '@ai-sdk/openai';
5
+ import { generateText, NoObjectGeneratedError, Output } from 'ai';
6
+ import { z } from 'zod';
7
+ import { WebDriver } from './driver.js';
8
+ import { assertFresh, commitLocks, getLock, hashes, readLocks } from './lock.js';
9
+ import { actionSchema, assertionSchema, FlowError, valueSchema, } from './model.js';
10
+ import { contextsFor } from './workspace.js';
11
+ const bindingStepSchema = z.union([
12
+ z.object({ kind: z.literal('actions'), text: z.string() }),
13
+ z.object({ kind: z.literal('skill'), text: z.string(), name: z.string(), inputs: z.record(z.string(), valueSchema) }),
14
+ z.object({ kind: z.literal('visual'), text: z.string(), claim: z.string() }),
15
+ ]);
16
+ const bindingSchema = z.object({
17
+ steps: z.array(bindingStepSchema),
18
+ setup: z.array(bindingStepSchema).default([]),
19
+ teardown: z.array(bindingStepSchema).default([]),
20
+ });
21
+ const decisionSchema = z.object({
22
+ decision: z.enum(['action', 'done', 'blocked']),
23
+ action: actionSchema.nullish(),
24
+ reason: z.string().nullish(),
25
+ });
26
+ const compiledSchema = z.object({ assertions: z.array(assertionSchema) });
27
+ export class Runner {
28
+ ws;
29
+ mode;
30
+ modelOverride;
31
+ locks = {};
32
+ updates = new Map();
33
+ secrets = new Map();
34
+ values = new Map();
35
+ calls = 0;
36
+ active = [];
37
+ driver;
38
+ constructor(ws, mode, modelOverride) {
39
+ this.ws = ws;
40
+ this.mode = mode;
41
+ this.modelOverride = modelOverride;
42
+ this.driver = new WebDriver(ws.config, path.join(ws.root, ws.config.artifactsDir, `run-${randomUUID()}`, 'trace.zip'));
43
+ }
44
+ redact(s) {
45
+ for (const [key, value] of this.secrets)
46
+ if (value)
47
+ s = s.split(value).join(`[REDACTED:${key}]`);
48
+ return s;
49
+ }
50
+ async model(schema, prompt, kind = 'compiler') {
51
+ if (this.mode === 'strict' && kind !== 'judge')
52
+ throw new FlowError('STRICT_MODEL_CALL', 'Strict mode cannot call a navigation model', 3);
53
+ const model = kind === 'explorer'
54
+ ? this.ws.config.ai.explorerModel
55
+ : kind === 'judge'
56
+ ? this.ws.config.ai.judgeModel
57
+ : this.ws.config.ai.compilerModel;
58
+ for (let attempt = 0; attempt < 2; attempt++) {
59
+ if (++this.calls > this.ws.config.ai.maxModelCallsPerFlow)
60
+ throw new FlowError('EXPLORE_BUDGET_EXCEEDED', 'Model call budget exceeded', 1);
61
+ const guidance = attempt
62
+ ? '\nYour previous response did not match the required schema. Every locator requires a role and a name string. Use an empty name for unnamed elements. Return only supported kinds and fields.'
63
+ : '';
64
+ try {
65
+ const input = this.redact(prompt + guidance);
66
+ const output = this.modelOverride
67
+ ? schema.parse(await this.modelOverride(input, kind))
68
+ : (await generateText({
69
+ model: openai(model),
70
+ output: Output.object({ schema }),
71
+ providerOptions: { openai: { strictJsonSchema: false } },
72
+ prompt: input,
73
+ })).output;
74
+ if (this.redact(JSON.stringify(output)) !== JSON.stringify(output))
75
+ throw new Error('Model returned a secret');
76
+ return output;
77
+ }
78
+ catch (e) {
79
+ const invalid = e instanceof z.ZodError || NoObjectGeneratedError.isInstance(e);
80
+ if (invalid && attempt === 0)
81
+ continue;
82
+ throw new FlowError('MODEL_ERROR', invalid ? 'Model output did not match the required schema' : this.redact(String(e)), 1);
83
+ }
84
+ }
85
+ throw new FlowError('MODEL_ERROR', 'Model output did not match the required schema', 1);
86
+ }
87
+ async value(v, doc, inputs) {
88
+ switch (v.type) {
89
+ case 'literal':
90
+ return v.value;
91
+ case 'secret': {
92
+ const value = this.secrets.get(v.envKey);
93
+ if (!value)
94
+ throw new FlowError('CONFIG_SECRET_MISSING', `Secret not declared or missing: ${v.envKey}`);
95
+ return value;
96
+ }
97
+ case 'skill_input': {
98
+ const source = inputs[v.inputName];
99
+ if (!source)
100
+ throw new FlowError('SKILL_INPUT_MISSING', `Missing input ${v.inputName}`);
101
+ return this.value(source, doc, {});
102
+ }
103
+ case 'asset_path': {
104
+ if (path.basename(v.filename) !== v.filename)
105
+ throw new FlowError('ASSET_NOT_FOUND', 'Invalid asset filename');
106
+ for (const base of [
107
+ path.join(path.dirname(this.rootFlow.path), 'assets'),
108
+ path.join(path.dirname(doc.path), 'assets'),
109
+ path.resolve(this.ws.root, this.ws.config.flowsDir, 'assets'),
110
+ ]) {
111
+ const p = path.join(base, v.filename);
112
+ try {
113
+ await access(p);
114
+ return p;
115
+ }
116
+ catch { }
117
+ }
118
+ throw new FlowError('ASSET_NOT_FOUND', `Asset not found: ${v.filename}`);
119
+ }
120
+ case 'generator': {
121
+ const k = JSON.stringify(v);
122
+ let value = this.values.get(k);
123
+ if (!value) {
124
+ switch (v.fn) {
125
+ case 'unique_email':
126
+ value = `uwright-${randomUUID()}@example.test`;
127
+ break;
128
+ case 'unique_uuid':
129
+ value = randomUUID();
130
+ break;
131
+ case 'unique_string':
132
+ value = randomBytes(12).toString('hex');
133
+ break;
134
+ case 'unique_phone':
135
+ value = `555${String(Math.floor(Math.random() * 10000000)).padStart(7, '0')}`;
136
+ break;
137
+ case 'today_yyyy_mm_dd':
138
+ value = new Date().toISOString().slice(0, 10);
139
+ break;
140
+ case 'timestamp_iso':
141
+ value = new Date().toISOString();
142
+ }
143
+ this.values.set(k, value);
144
+ }
145
+ return value;
146
+ }
147
+ }
148
+ }
149
+ rootFlow;
150
+ async executeAction(action, doc, inputs) {
151
+ let value;
152
+ if ('valueSource' in action)
153
+ value = await this.value(action.valueSource, doc, inputs);
154
+ await this.driver.action(action, value);
155
+ }
156
+ async explore(text, doc, inputs, prefix = []) {
157
+ const actions = [...prefix];
158
+ const seen = new Set();
159
+ let feedback = '';
160
+ for (let i = 0; i < this.ws.config.ai.maxStepsPerExplore; i++) {
161
+ const observed = await this.driver.observe();
162
+ const tree = this.redact(observed);
163
+ const prompt = `You control a browser to accomplish exactly the current goal, not later steps.
164
+ Return done immediately once that goal is accomplished.
165
+ Return one action at a time.
166
+ Use accessible role and name exactly as shown.
167
+ If a role in the accessibility tree has no quoted accessible name, its name is the empty string, even if adjacent text describes it.
168
+ When identical roles and names appear more than once, use nth with a zero-based index in tree order.
169
+ For a select action use an option label or value.
170
+ Never place secret values in output.
171
+ Use {type:"secret",envKey:"NAME"} for secrets, {type:"skill_input",inputName:"name"} for inputs, {type:"asset_path",filename:"..."} for uploads, and generator values when appropriate.
172
+ Configured base URL: ${this.ws.config.target.baseUrl}
173
+ Current URL: ${this.driver.page.url()}
174
+ Use the configured base URL for the home page. Do not invent a domain.
175
+ Goal: ${text}
176
+ Actions already executed for this goal: ${JSON.stringify(actions)}
177
+ Previous rejected action: ${feedback}
178
+ Inputs: ${JSON.stringify(inputs)}
179
+ Declared secrets: ${[...this.secrets.keys()].join(', ')}
180
+ Context and guardrails: ${contextsFor(this.ws, doc)
181
+ .map((x) => x.source)
182
+ .join('\n')}
183
+ Flow or skill context: ${doc.source}
184
+ Current page: ${tree}`;
185
+ const decision = await this.model(decisionSchema, prompt, 'explorer');
186
+ if (process.env.UWRIGHT_DEBUG === '1')
187
+ process.stderr.write(this.redact(`Explorer ${JSON.stringify(decision)}${feedback ? `; feedback: ${feedback}` : ''}\n`));
188
+ if (decision.decision === 'done')
189
+ return actions;
190
+ if (decision.decision === 'blocked') {
191
+ if (await this.driver.waitForChange(observed))
192
+ continue;
193
+ throw new FlowError('EXPLORATION_BLOCKED', this.redact(decision.reason ?? 'Blocked'), 1);
194
+ }
195
+ if (!decision.action)
196
+ throw new FlowError('MODEL_ERROR', 'Explorer returned action without an action', 1);
197
+ const signature = JSON.stringify([tree, decision.action]);
198
+ if (seen.has(signature)) {
199
+ feedback = `The action ${JSON.stringify(decision.action)} was already tried without progress. Choose a different action or report done.`;
200
+ continue;
201
+ }
202
+ seen.add(signature);
203
+ try {
204
+ await this.executeAction(decision.action, doc, inputs);
205
+ actions.push(decision.action);
206
+ feedback = '';
207
+ }
208
+ catch (e) {
209
+ if (!(e instanceof FlowError) || e.code !== 'CACHE_STALE')
210
+ throw e;
211
+ feedback = this.redact(`${JSON.stringify(decision.action)} failed: ${e.message}. Use only the exact role and accessible name in the current tree, with nth for duplicate unnamed elements.`);
212
+ }
213
+ }
214
+ throw new FlowError('EXPLORE_BUDGET_EXCEEDED', `Step budget exceeded: ${text}`, 1);
215
+ }
216
+ async bind(doc) {
217
+ const sections = {
218
+ steps: doc.sections.steps ?? [],
219
+ setup: doc.sections.setup ?? [],
220
+ teardown: doc.sections.teardown ?? [],
221
+ };
222
+ const result = await this.model(bindingSchema, `Bind each numbered source item in order to exactly one step.
223
+ For ordinary steps, return {kind:"actions",text}.
224
+ For a skill call, return {kind:"skill",text,name,inputs}.
225
+ For a visual check, return {kind:"visual",text,claim}.
226
+ Do not invent steps or browser actions.
227
+ Use skill_input, literal, generator, secret, or asset_path value sources.
228
+
229
+ Sections: ${JSON.stringify(sections)}
230
+ Document context: ${doc.source}
231
+ Skills: ${JSON.stringify(this.ws.skills.map((s) => s.frontmatter))}
232
+ Context: ${contextsFor(this.ws, doc)
233
+ .map((d) => d.source)
234
+ .join('\n')}`);
235
+ const bindSection = (key) => {
236
+ if (result[key].length !== sections[key].length)
237
+ throw new FlowError('MODEL_ERROR', `Binder returned wrong number of ${key} steps`, 1);
238
+ return result[key].map((step, i) => {
239
+ const text = sections[key][i].text;
240
+ return step.kind === 'actions' ? { kind: 'actions', text, actions: [] } : { ...step, text };
241
+ });
242
+ };
243
+ return { steps: bindSection('steps'), setup: bindSection('setup'), teardown: bindSection('teardown') };
244
+ }
245
+ async outcomes(doc) {
246
+ const bullets = doc.sections[doc === this.rootFlow ? 'expected outcome' : 'postconditions'] ?? [];
247
+ const result = await this.model(compiledSchema, `Compile every outcome to exactly one deterministic assertion for the current page.
248
+ For an outcome requiring a matching element, set locator.nth to 0.
249
+ For a visible button, use locator_state.
250
+ Each locator must include role and name strings, even when the name is empty.
251
+ Do not copy changing request or response values into assertions.
252
+ Verify the full claim, not merely a heading.
253
+ If supported deterministic assertions cannot verify the claim, use visual_judge_fallback.
254
+
255
+ Outcomes: ${JSON.stringify(bullets)}
256
+ Page: ${await this.driver.observe()}`);
257
+ if (result.assertions.length !== bullets.length)
258
+ throw new FlowError('EXPECTED_OUTCOME_FAILED', 'Every outcome must compile to one assertion', 1);
259
+ return result.assertions;
260
+ }
261
+ async judge(claim) {
262
+ if (this.secrets.size)
263
+ throw new FlowError('VISUAL_SECRET_UNSAFE', 'Cannot send a screenshot to a model when secrets are declared', 1);
264
+ if (++this.calls > this.ws.config.ai.maxModelCallsPerFlow)
265
+ throw new FlowError('EXPLORE_BUDGET_EXCEEDED', 'Model call budget exceeded', 1);
266
+ const schema = z.object({
267
+ verdict: z.enum(['holds', 'fails', 'inconclusive']),
268
+ evidence: z.string(),
269
+ confidence: z.number().min(0).max(1),
270
+ });
271
+ const image = await this.driver.page.screenshot({ type: 'png' });
272
+ const text = this.redact(`Judge only whether this claim holds. Return your verdict, evidence and confidence. Claim: ${claim}\nCurrent accessibility tree: ${await this.driver.observe()}`);
273
+ const result = await generateText({
274
+ model: openai(this.ws.config.ai.judgeModel),
275
+ output: Output.object({ schema }),
276
+ messages: [
277
+ {
278
+ role: 'user',
279
+ content: [
280
+ { type: 'text', text },
281
+ { type: 'image', image },
282
+ ],
283
+ },
284
+ ],
285
+ });
286
+ process.stderr.write('Visual judge invoked. Screenshots and traces may contain secrets.\n');
287
+ return result.output.verdict === 'holds' && result.output.confidence >= 0.75;
288
+ }
289
+ async verify(assertions, skill) {
290
+ for (const a of assertions) {
291
+ if (!(a.kind === 'visual_judge_fallback' ? await this.judge(a.claim) : await this.driver.assertion(a)))
292
+ throw new FlowError(skill ? 'SKILL_POSTCONDITION_FAILED' : 'EXPECTED_OUTCOME_FAILED', `Failed assertion: ${JSON.stringify(a)}`, 1);
293
+ }
294
+ }
295
+ async steps(steps, doc, inputs) {
296
+ for (const step of steps) {
297
+ if (step.kind === 'visual') {
298
+ if (!(await this.judge(step.claim)))
299
+ throw new FlowError('VISUAL_CHECK_FAILED', `Visual check failed: ${step.text}`, 1);
300
+ continue;
301
+ }
302
+ if (step.kind === 'skill') {
303
+ const skill = this.ws.skills.find((s) => s.frontmatter.name === step.name);
304
+ if (!skill)
305
+ throw new FlowError('SKILL_NOT_FOUND', `Unknown skill ${step.name}`);
306
+ const bound = {};
307
+ for (const [key, value] of Object.entries(step.inputs)) {
308
+ if (value.type === 'skill_input') {
309
+ const parent = inputs[value.inputName];
310
+ if (!parent)
311
+ throw new FlowError('SKILL_INPUT_MISSING', `Missing input ${value.inputName}`);
312
+ bound[key] = parent;
313
+ }
314
+ else
315
+ bound[key] = value;
316
+ }
317
+ await this.executeDoc(skill, bound);
318
+ continue;
319
+ }
320
+ let i = 0;
321
+ try {
322
+ for (; i < step.actions.length; i++)
323
+ await this.executeAction(step.actions[i], doc, inputs);
324
+ }
325
+ catch (e) {
326
+ if (this.mode !== 'heal' || !(e instanceof FlowError) || e.code !== 'CACHE_STALE')
327
+ throw e;
328
+ step.actions = await this.explore(step.text, doc, inputs, step.actions.slice(0, i));
329
+ continue;
330
+ }
331
+ if (step.actions.length === 0) {
332
+ if (this.mode === 'strict')
333
+ throw new FlowError('LOCK_INVALID', 'Empty locked step', 3);
334
+ step.actions = await this.explore(step.text, doc, inputs);
335
+ }
336
+ }
337
+ }
338
+ async executeDoc(doc, inputs = {}) {
339
+ const name = doc.frontmatter.name ?? doc.path;
340
+ if (this.active.includes(name))
341
+ throw new FlowError('SKILL_CIRCULAR_DEPENDENCY', `Skill cycle: ${[...this.active, name].join(' -> ')}`);
342
+ this.active.push(name);
343
+ try {
344
+ for (const input of doc.frontmatter.inputs) {
345
+ if (!inputs[input.name] && input.default !== undefined)
346
+ inputs[input.name] = { type: 'literal', value: input.default };
347
+ if (input.required && !inputs[input.name])
348
+ throw new FlowError('SKILL_INPUT_MISSING', `Missing input ${input.name}`);
349
+ }
350
+ let lock = this.mode === 'record' || this.mode === 'off'
351
+ ? undefined
352
+ : (this.updates.get(doc) ?? getLock(this.ws, this.locks, doc));
353
+ if (this.mode === 'strict')
354
+ assertFresh(this.ws, lock, doc);
355
+ if (lock && this.mode === 'heal') {
356
+ try {
357
+ assertFresh(this.ws, lock, doc);
358
+ }
359
+ catch {
360
+ lock = undefined;
361
+ }
362
+ }
363
+ if (lock)
364
+ lock = structuredClone(lock);
365
+ else {
366
+ const b = await this.bind(doc);
367
+ lock = { version: 1, source: doc.path, ...hashes(this.ws, doc), ...b, outcomes: [] };
368
+ }
369
+ let primary;
370
+ try {
371
+ await this.steps(lock.setup, doc, inputs);
372
+ await this.steps(lock.steps, doc, inputs);
373
+ if (!lock.outcomes.length)
374
+ lock.outcomes = await this.outcomes(doc);
375
+ await this.verify(lock.outcomes, doc !== this.rootFlow);
376
+ }
377
+ catch (e) {
378
+ primary = e;
379
+ }
380
+ finally {
381
+ try {
382
+ await this.steps(lock.teardown, doc, inputs);
383
+ }
384
+ catch (e) {
385
+ process.stderr.write(`Teardown failed: ${this.redact(String(e))}\n`);
386
+ }
387
+ }
388
+ if (primary)
389
+ throw primary;
390
+ if (this.mode !== 'strict' && this.mode !== 'off')
391
+ this.updates.set(doc, lock);
392
+ }
393
+ finally {
394
+ this.active.pop();
395
+ }
396
+ }
397
+ async run(doc) {
398
+ this.rootFlow = doc;
399
+ for (const d of [doc, ...this.ws.skills, ...this.ws.contexts])
400
+ for (const key of d.frontmatter.secrets) {
401
+ const value = process.env[key];
402
+ if (!value)
403
+ throw new FlowError('CONFIG_SECRET_MISSING', `Missing environment variable ${key}`);
404
+ this.secrets.set(key, value);
405
+ }
406
+ this.locks = await readLocks(this.ws);
407
+ if (this.mode === 'strict') {
408
+ const visited = new Set();
409
+ const preflight = (d) => {
410
+ if (visited.has(d.path))
411
+ return;
412
+ visited.add(d.path);
413
+ const l = getLock(this.ws, this.locks, d);
414
+ assertFresh(this.ws, l, d);
415
+ for (const step of [...l.setup, ...l.steps, ...l.teardown])
416
+ if (step.kind === 'skill') {
417
+ const s = this.ws.skills.find((x) => x.frontmatter.name === step.name);
418
+ if (!s)
419
+ throw new FlowError('SKILL_NOT_FOUND', `Unknown skill ${step.name}`);
420
+ preflight(s);
421
+ }
422
+ };
423
+ preflight(doc);
424
+ }
425
+ try {
426
+ await this.driver.start();
427
+ await this.executeDoc(doc);
428
+ if (this.updates.size) {
429
+ for (const lock of this.updates.values()) {
430
+ const data = JSON.stringify(lock);
431
+ if (this.redact(data) !== data)
432
+ throw new FlowError('SECRET_IN_LOCK', 'Refusing to write a lock containing a secret', 1);
433
+ }
434
+ await commitLocks(this.ws, this.updates, this.locks);
435
+ }
436
+ return { passed: true, modelCalls: this.calls, updated: this.updates.size };
437
+ }
438
+ catch (e) {
439
+ if (e instanceof FlowError)
440
+ throw new FlowError(e.code, this.redact(e.message), e.exitCode);
441
+ throw new FlowError('RUN_FAILED', this.redact(String(e)), 1);
442
+ }
443
+ finally {
444
+ await this.driver.stop();
445
+ }
446
+ }
447
+ }
@@ -0,0 +1,99 @@
1
+ import { z } from 'zod';
2
+ import { FlowError } from './model.js';
3
+ export const secretFillSchema = z.object({
4
+ kind: z.literal('fill-secret'),
5
+ secret: z.string().regex(/^[A-Z][A-Z0-9_]*$/),
6
+ parameter: z.string().min(1).optional(),
7
+ target: z.discriminatedUnion('by', [
8
+ z.object({ by: z.literal('label'), value: z.string().min(1) }),
9
+ z.object({ by: z.literal('test-id'), value: z.string().min(1) }),
10
+ z.object({ by: z.literal('placeholder'), value: z.string().min(1) }),
11
+ ]),
12
+ });
13
+ export const literalFillSchema = secretFillSchema
14
+ .omit({ secret: true, parameter: true, kind: true })
15
+ .extend({ kind: z.literal('fill-literal'), value: z.string() });
16
+ function locate(page, target) {
17
+ if (target.by === 'label')
18
+ return page.getByLabel(target.value, { exact: true });
19
+ if (target.by === 'test-id')
20
+ return page.getByTestId(target.value);
21
+ return page.getByPlaceholder(target.value, { exact: true });
22
+ }
23
+ async function focusedField(page) {
24
+ const focus = page.locator(':focus');
25
+ if ((await focus.count()) !== 1)
26
+ return;
27
+ const details = await focus.evaluate((element) => {
28
+ if (!(element instanceof HTMLInputElement || element instanceof HTMLTextAreaElement))
29
+ return undefined;
30
+ return {
31
+ value: element.value,
32
+ labels: [...(element.labels ?? [])]
33
+ .map((label) => label.textContent?.trim())
34
+ .filter((text) => !!text),
35
+ ariaLabel: element.getAttribute('aria-label')?.trim(),
36
+ testId: element.getAttribute('data-testid')?.trim(),
37
+ placeholder: element.getAttribute('placeholder')?.trim(),
38
+ };
39
+ });
40
+ if (!details)
41
+ return;
42
+ const candidates = [];
43
+ if (details.testId)
44
+ candidates.push({ by: 'test-id', value: details.testId });
45
+ for (const label of [...details.labels, ...(details.ariaLabel ? [details.ariaLabel] : [])])
46
+ candidates.push({ by: 'label', value: label });
47
+ if (details.placeholder)
48
+ candidates.push({ by: 'placeholder', value: details.placeholder });
49
+ for (const target of candidates) {
50
+ const locator = locate(page, target);
51
+ if ((await locator.count()) === 1 && (await locator.evaluate((element) => element === document.activeElement)))
52
+ return { value: details.value, target };
53
+ }
54
+ }
55
+ export async function captureSecretFill(page, secrets) {
56
+ const field = await focusedField(page);
57
+ if (!field?.value)
58
+ return;
59
+ const matches = Object.entries(secrets).filter(([, value]) => value === field.value);
60
+ if (matches.length === 1)
61
+ return { kind: 'fill-secret', secret: matches[0][0], target: field.target };
62
+ }
63
+ export async function captureLiteralFill(page, allowed, secrets) {
64
+ const field = await focusedField(page);
65
+ if (!field || !allowed.includes(field.value))
66
+ return;
67
+ if (Object.values(secrets).some((secret) => secret && (field.value.includes(secret) || (field.value && secret.includes(field.value)))))
68
+ return;
69
+ return { kind: 'fill-literal', value: field.value, target: field.target };
70
+ }
71
+ export async function replaySecretFill(page, action, secrets) {
72
+ const value = secrets[action.secret];
73
+ if (!value)
74
+ throw new FlowError('CONFIG_SECRET_MISSING', `Missing environment variable ${action.secret}`);
75
+ const locator = locate(page, action.target);
76
+ if ((await locator.count()) !== 1)
77
+ throw new FlowError('CACHE_STALE', `Secret field ${action.target.by} ${JSON.stringify(action.target.value)} is missing or ambiguous`, 3);
78
+ try {
79
+ await locator.fill(value);
80
+ if ((await locator.inputValue()) !== value)
81
+ throw new Error('Value did not match');
82
+ }
83
+ catch {
84
+ throw new FlowError('ACTION_UNCERTAIN', `Secret fill may have been attempted on ${action.target.by} ${JSON.stringify(action.target.value)}; inspect the page before retrying`, 3);
85
+ }
86
+ }
87
+ export async function replayLiteralFill(page, action) {
88
+ const locator = locate(page, action.target);
89
+ if ((await locator.count()) !== 1)
90
+ throw new FlowError('CACHE_STALE', `Field ${action.target.by} ${JSON.stringify(action.target.value)} is missing or ambiguous`, 3);
91
+ try {
92
+ await locator.fill(action.value);
93
+ if ((await locator.inputValue()) !== action.value)
94
+ throw new Error('Value did not match');
95
+ }
96
+ catch {
97
+ throw new FlowError('ACTION_UNCERTAIN', `Fill may have been attempted on ${action.target.by} ${JSON.stringify(action.target.value)}; inspect the page before retrying`, 3);
98
+ }
99
+ }
@@ -0,0 +1,79 @@
1
+ import { z } from 'zod';
2
+ import { FlowError } from './model.js';
3
+ export const tapSchema = z.object({
4
+ kind: z.literal('tap'),
5
+ role: z.enum(['button', 'link', 'tab']),
6
+ name: z.string().min(1),
7
+ });
8
+ export async function beginTapCapture(page) {
9
+ await page.evaluate(() => {
10
+ const key = Symbol.for('uwright.lastTap');
11
+ if (!Reflect.has(document, key)) {
12
+ const state = {};
13
+ Reflect.set(document, key, state);
14
+ document.addEventListener('click', (event) => {
15
+ const target = event.target instanceof Element
16
+ ? event.target.closest('button,a,[role="button"],[role="link"],[role="tab"]')
17
+ : null;
18
+ if (!target)
19
+ return;
20
+ const role = target.getAttribute('role') ||
21
+ (target.tagName === 'BUTTON' ? 'button' : target.tagName === 'A' ? 'link' : '');
22
+ const name = (target.getAttribute('aria-label') || target.textContent || '').replace(/\s+/g, ' ').trim();
23
+ state.last = { role, name };
24
+ }, true);
25
+ }
26
+ const state = Reflect.get(document, key);
27
+ state.last = undefined;
28
+ });
29
+ }
30
+ export async function captureTap(page, summary) {
31
+ const direct = /^tap (button|link|tab) ("(?:[^"\\]|\\.)*")$/.exec(summary);
32
+ const point = /^tap the point \([^)]*\) on (?:node|button|link|tab) ("(?:[^"\\]|\\.)*")$/.exec(summary);
33
+ const last = await page.evaluate(() => Reflect.get(document, Symbol.for('uwright.lastTap'))?.last);
34
+ const match = direct ?? point;
35
+ if (!match)
36
+ return;
37
+ let name;
38
+ try {
39
+ name = JSON.parse((direct ? match[2] : match[1]));
40
+ }
41
+ catch {
42
+ return;
43
+ }
44
+ const parsed = tapSchema.safeParse({ kind: 'tap', role: direct ? match[1] : last?.role, name });
45
+ if (!parsed.success)
46
+ return;
47
+ const locator = page.getByRole(parsed.data.role, { name: parsed.data.name, exact: true });
48
+ if (point && !last)
49
+ return;
50
+ if (last && (last.role !== parsed.data.role || last.name !== parsed.data.name))
51
+ return;
52
+ if (last) {
53
+ try {
54
+ await locator.first().waitFor({ state: 'attached', timeout: 4000 });
55
+ }
56
+ catch {
57
+ return;
58
+ }
59
+ }
60
+ if ((await locator.count()) !== 1)
61
+ return;
62
+ const focused = await locator.evaluate((element) => element === document.activeElement);
63
+ if (!focused) {
64
+ if (!last || last.role !== parsed.data.role || last.name !== parsed.data.name)
65
+ return;
66
+ }
67
+ return parsed.data;
68
+ }
69
+ export async function replayTap(page, action) {
70
+ const locator = page.getByRole(action.role, { name: action.name, exact: true });
71
+ if ((await locator.count()) !== 1)
72
+ throw new FlowError('CACHE_STALE', `Target ${action.role} ${JSON.stringify(action.name)} is missing or ambiguous`, 3);
73
+ try {
74
+ await locator.click();
75
+ }
76
+ catch {
77
+ throw new FlowError('ACTION_UNCERTAIN', `Click may have been attempted on ${action.role} ${JSON.stringify(action.name)}; inspect the page before retrying`, 3);
78
+ }
79
+ }