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/dist/lock.js ADDED
@@ -0,0 +1,295 @@
1
+ import { createHash, randomUUID } from 'node:crypto';
2
+ import { mkdir, readdir, readFile, rename, rm, writeFile } from 'node:fs/promises';
3
+ import { hostname } from 'node:os';
4
+ import path from 'node:path';
5
+ import { z } from 'zod';
6
+ import { FlowError, lockSchema } from './model.js';
7
+ import { contextsFor } from './workspace.js';
8
+ export function hash(value) {
9
+ return createHash('sha256').update(value).digest('hex');
10
+ }
11
+ export function hashes(ws, doc) {
12
+ return {
13
+ sourceHash: hash(doc.source),
14
+ contextHash: hash(contextsFor(ws, doc)
15
+ .map((d) => d.source)
16
+ .join('\n')),
17
+ };
18
+ }
19
+ function baseDir(ws) {
20
+ return path.resolve(ws.root, ws.config.lockDir);
21
+ }
22
+ function key(ws, doc) {
23
+ return path
24
+ .relative(path.resolve(ws.root, ws.config.flowsDir), doc.path)
25
+ .split(path.sep)
26
+ .join('/')
27
+ .replace(/\.md$/, '.lock.json');
28
+ }
29
+ function lockPath(base, name) {
30
+ const resolved = path.resolve(base, name);
31
+ if (!name.endsWith('.lock.json') || path.isAbsolute(name) || !resolved.startsWith(base + path.sep))
32
+ throw new FlowError('LOCK_INVALID', `Invalid lock path: ${name}`);
33
+ return resolved;
34
+ }
35
+ async function readOptional(file) {
36
+ try {
37
+ return await readFile(file, 'utf8');
38
+ }
39
+ catch (e) {
40
+ if (e.code === 'ENOENT')
41
+ return null;
42
+ throw e;
43
+ }
44
+ }
45
+ async function walk(dir) {
46
+ try {
47
+ const entries = await readdir(dir, { withFileTypes: true });
48
+ return (await Promise.all(entries
49
+ .filter((e) => !e.name.startsWith('.'))
50
+ .map((e) => e.isDirectory()
51
+ ? walk(path.join(dir, e.name))
52
+ : Promise.resolve(e.isFile() && e.name.endsWith('.lock.json') ? [path.join(dir, e.name)] : [])))).flat();
53
+ }
54
+ catch (e) {
55
+ if (e.code === 'ENOENT')
56
+ return [];
57
+ throw e;
58
+ }
59
+ }
60
+ const journalSchema = z.object({
61
+ version: z.literal(1),
62
+ entries: z.array(z.object({ name: z.string(), before: z.string().nullable(), after: z.string() })),
63
+ });
64
+ const ownerSchema = z.object({ pid: z.number().int().positive(), host: z.string() });
65
+ async function acquire(base) {
66
+ const mutex = path.join(base, '.write-lock');
67
+ try {
68
+ await mkdir(mutex);
69
+ }
70
+ catch (e) {
71
+ if (e.code === 'EEXIST')
72
+ throw new FlowError('LOCK_BUSY', 'Another Uwright lock operation is active, or a previous operation was interrupted. Run uwright lock recover if needed.');
73
+ throw e;
74
+ }
75
+ try {
76
+ await writeFile(path.join(mutex, 'owner.json'), JSON.stringify({ pid: process.pid, host: hostname() }), {
77
+ flag: 'wx',
78
+ });
79
+ }
80
+ catch (e) {
81
+ await rm(mutex, { recursive: true, force: true });
82
+ throw e;
83
+ }
84
+ return async () => {
85
+ await rm(mutex, { recursive: true, force: true });
86
+ };
87
+ }
88
+ async function readUnlocked(ws) {
89
+ const base = baseDir(ws);
90
+ const result = {};
91
+ for (const file of await walk(base)) {
92
+ const name = path.relative(base, file).split(path.sep).join('/');
93
+ try {
94
+ result[name] = lockSchema.parse(JSON.parse(await readFile(file, 'utf8')));
95
+ }
96
+ catch (e) {
97
+ throw new FlowError('LOCK_INVALID', `Invalid lock ${name}: ${String(e)}`);
98
+ }
99
+ }
100
+ return result;
101
+ }
102
+ async function assertNoJournal(base) {
103
+ if ((await readOptional(path.join(base, '.transaction', 'journal.json'))) !== null)
104
+ throw new FlowError('LOCK_RECOVERY_REQUIRED', 'An interrupted lock update needs recovery. Run uwright lock recover.');
105
+ try {
106
+ await readdir(path.join(base, '.transaction'));
107
+ throw new FlowError('LOCK_RECOVERY_REQUIRED', 'An interrupted lock update needs recovery. Run uwright lock recover.');
108
+ }
109
+ catch (e) {
110
+ if (e.code !== 'ENOENT')
111
+ throw e;
112
+ }
113
+ }
114
+ export async function readLocks(ws) {
115
+ const base = baseDir(ws);
116
+ try {
117
+ await readdir(base);
118
+ }
119
+ catch (e) {
120
+ if (e.code === 'ENOENT')
121
+ return {};
122
+ throw e;
123
+ }
124
+ const release = await acquire(base);
125
+ try {
126
+ await assertNoJournal(base);
127
+ if ((await readOptional(path.join(base, 'CURRENT'))) !== null)
128
+ throw new FlowError('LOCK_LEGACY_FORMAT', 'Legacy generation found. Run uwright lock migrate.');
129
+ return await readUnlocked(ws);
130
+ }
131
+ finally {
132
+ await release();
133
+ }
134
+ }
135
+ export function getLock(ws, locks, doc) {
136
+ return locks[key(ws, doc)];
137
+ }
138
+ export function assertFresh(ws, lock, doc) {
139
+ if (!lock)
140
+ throw new FlowError('LOCK_MISSING_IN_STRICT_MODE', `No lock for ${doc.path}`, 3);
141
+ const h = hashes(ws, doc);
142
+ if (lock.sourceHash !== h.sourceHash || lock.contextHash !== h.contextHash)
143
+ throw new FlowError('LOCK_DRIFT_DETECTED', `Source changed: ${doc.path}`, 3);
144
+ }
145
+ async function replaceFile(file, content) {
146
+ await mkdir(path.dirname(file), { recursive: true });
147
+ const temp = `${file}.tmp-${randomUUID()}`;
148
+ try {
149
+ await writeFile(temp, content, { flag: 'wx' });
150
+ await rename(temp, file);
151
+ }
152
+ finally {
153
+ await rm(temp, { force: true });
154
+ }
155
+ }
156
+ async function publish(base, entries) {
157
+ for (const entry of entries) {
158
+ const current = await readOptional(lockPath(base, entry.name));
159
+ if (current !== entry.before && current !== entry.after)
160
+ throw new FlowError('LOCK_RECOVERY_CONFLICT', `Lock changed outside the transaction: ${entry.name}`);
161
+ }
162
+ for (const entry of entries) {
163
+ const file = lockPath(base, entry.name);
164
+ if ((await readOptional(file)) !== entry.after)
165
+ await replaceFile(file, entry.after);
166
+ }
167
+ }
168
+ export async function commitLocks(ws, updates, expected) {
169
+ const base = baseDir(ws);
170
+ await mkdir(base, { recursive: true });
171
+ const release = await acquire(base);
172
+ try {
173
+ await assertNoJournal(base);
174
+ const current = await readUnlocked(ws);
175
+ if (JSON.stringify(current) !== JSON.stringify(expected))
176
+ throw new FlowError('LOCK_CONFLICT', 'Locks changed during the run');
177
+ const entries = [...updates]
178
+ .map(([doc, lock]) => {
179
+ const name = key(ws, doc);
180
+ const relativeSource = path.relative(ws.root, doc.path).split(path.sep).join('/');
181
+ return {
182
+ name,
183
+ before: current[name] ? JSON.stringify(current[name], null, 2) + '\n' : null,
184
+ after: JSON.stringify({ ...lock, source: relativeSource }, null, 2) + '\n',
185
+ };
186
+ })
187
+ .filter((entry) => entry.before !== entry.after)
188
+ .sort((a, b) => a.name.localeCompare(b.name));
189
+ if (!entries.length)
190
+ return;
191
+ // Capture actual bytes to support valid locks whose formatting differs from ours.
192
+ for (const entry of entries)
193
+ entry.before = await readOptional(lockPath(base, entry.name));
194
+ const dir = path.join(base, '.transaction');
195
+ await mkdir(dir);
196
+ const temp = path.join(dir, 'journal.tmp');
197
+ await writeFile(temp, JSON.stringify({ version: 1, entries }), { flag: 'wx' });
198
+ await rename(temp, path.join(dir, 'journal.json'));
199
+ await publish(base, entries);
200
+ await rm(dir, { recursive: true, force: true });
201
+ }
202
+ finally {
203
+ await release();
204
+ }
205
+ }
206
+ export async function recoverLocks(ws) {
207
+ const base = baseDir(ws);
208
+ await mkdir(base, { recursive: true });
209
+ const mutex = path.join(base, '.write-lock');
210
+ const ownerText = await readOptional(path.join(mutex, 'owner.json'));
211
+ if (ownerText !== null) {
212
+ let owner;
213
+ try {
214
+ owner = ownerSchema.parse(JSON.parse(ownerText));
215
+ }
216
+ catch {
217
+ throw new FlowError('LOCK_RECOVERY_REQUIRED', 'Invalid lock owner; confirm no writer is active before removing .write-lock manually.');
218
+ }
219
+ if (owner.host !== hostname())
220
+ throw new FlowError('LOCK_BUSY', 'Lock owner is on another host; confirm it is stopped before removing .write-lock manually.');
221
+ try {
222
+ process.kill(owner.pid, 0);
223
+ throw new FlowError('LOCK_BUSY', `Process ${owner.pid} still holds the lock.`);
224
+ }
225
+ catch (e) {
226
+ if (e instanceof FlowError)
227
+ throw e;
228
+ if (e.code !== 'ESRCH')
229
+ throw e;
230
+ }
231
+ await rm(mutex, { recursive: true, force: true });
232
+ }
233
+ else {
234
+ try {
235
+ await readdir(mutex);
236
+ throw new FlowError('LOCK_BUSY', 'Lock has no owner information; confirm no writer is active before removing .write-lock manually.');
237
+ }
238
+ catch (e) {
239
+ if (e.code !== 'ENOENT')
240
+ throw e;
241
+ }
242
+ }
243
+ const release = await acquire(base);
244
+ try {
245
+ const dir = path.join(base, '.transaction');
246
+ const raw = await readOptional(path.join(dir, 'journal.json'));
247
+ if (raw !== null) {
248
+ let journal;
249
+ try {
250
+ journal = journalSchema.parse(JSON.parse(raw));
251
+ for (const entry of journal.entries) {
252
+ lockPath(base, entry.name);
253
+ lockSchema.parse(JSON.parse(entry.after));
254
+ }
255
+ }
256
+ catch (e) {
257
+ throw new FlowError('LOCK_INVALID', `Invalid recovery journal: ${String(e)}`);
258
+ }
259
+ await publish(base, journal.entries);
260
+ }
261
+ await rm(dir, { recursive: true, force: true });
262
+ }
263
+ finally {
264
+ await release();
265
+ }
266
+ }
267
+ export async function migrateLegacyLocks(ws) {
268
+ const base = baseDir(ws);
269
+ const id = (await readOptional(path.join(base, 'CURRENT')))?.trim();
270
+ if (!id || !/^[a-f0-9-]+$/.test(id))
271
+ throw new FlowError('LOCK_LEGACY_FORMAT', 'No valid legacy generation found');
272
+ const raw = await readOptional(path.join(base, 'generations', `${id}.json`));
273
+ if (!raw)
274
+ throw new FlowError('LOCK_LEGACY_FORMAT', 'Legacy generation is missing');
275
+ const parsed = z.record(z.string(), lockSchema).parse(JSON.parse(raw));
276
+ const updates = new Map();
277
+ for (const [name, lock] of Object.entries(parsed)) {
278
+ const doc = [...ws.flows, ...ws.skills].find((d) => key(ws, d) === name);
279
+ if (!doc)
280
+ throw new FlowError('LOCK_LEGACY_FORMAT', `No source found for ${name}`);
281
+ updates.set(doc, lock);
282
+ }
283
+ const existing = await readUnlocked(ws);
284
+ for (const [doc, lock] of updates) {
285
+ const prior = existing[key(ws, doc)];
286
+ const portable = { ...lock, source: path.relative(ws.root, doc.path).split(path.sep).join('/') };
287
+ if (prior && JSON.stringify(prior) !== JSON.stringify(portable))
288
+ throw new FlowError('LOCK_CONFLICT', `Lock already exists for ${doc.path}`);
289
+ }
290
+ await commitLocks(ws, updates, existing);
291
+ const archive = path.resolve(ws.root, '.uwright', 'legacy-locks');
292
+ await mkdir(archive, { recursive: true });
293
+ await writeFile(path.join(archive, `${id}.json`), raw);
294
+ await rm(path.join(base, 'CURRENT'));
295
+ }
package/dist/mcp.js ADDED
@@ -0,0 +1,65 @@
1
+ import path from 'node:path';
2
+ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
3
+ import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
4
+ import { z } from 'zod';
5
+ import { diffLocks } from './diff.js';
6
+ import { WebDriver } from './driver.js';
7
+ import { runE2E } from './e2e-runner.js';
8
+ import { Runner } from './runner.js';
9
+ import { loadWorkspace } from './workspace.js';
10
+ const result = (data) => ({ content: [{ type: 'text', text: JSON.stringify(data, null, 2) }] });
11
+ export async function startMcp() {
12
+ const server = new McpServer({ name: 'uwright', version: '0.1.0' });
13
+ server.registerTool('uwright_get_catalog', { description: 'List flows and reusable skills', inputSchema: {} }, async () => {
14
+ const ws = await loadWorkspace();
15
+ const secrets = [...ws.contexts, ...ws.skills, ...ws.flows]
16
+ .flatMap((d) => d.frontmatter.secrets)
17
+ .map((k) => [k, process.env[k]]);
18
+ const clean = (v) => secrets.reduce((text, [k, value]) => (value ? text.split(value).join(`[REDACTED:${k}]`) : text), v);
19
+ return result({
20
+ contexts: ws.contexts.map((d) => clean(d.source)),
21
+ skills: ws.skills.map((s) => JSON.parse(clean(JSON.stringify(s.frontmatter)))),
22
+ flows: ws.flows.map((f) => ({ path: f.path, name: clean(f.frontmatter.name ?? '') })),
23
+ });
24
+ });
25
+ server.registerTool('uwright_validate', { description: 'Validate the workspace', inputSchema: {} }, async () => {
26
+ const ws = await loadWorkspace();
27
+ return result({
28
+ valid: true,
29
+ flows: ws.flows.length,
30
+ skills: ws.skills.length,
31
+ notice: 'Natural-language references are checked during compilation.',
32
+ });
33
+ });
34
+ server.registerTool('uwright_run', { description: 'Run a flow', inputSchema: { flowPath: z.string(), mode: z.enum(['strict', 'heal', 'record']) } }, async ({ flowPath, mode }) => {
35
+ const ws = await loadWorkspace();
36
+ const flow = ws.flows.find((f) => f.path === path.resolve(flowPath) || f.frontmatter.name === flowPath);
37
+ if (!flow)
38
+ throw new Error('Flow not found');
39
+ return result(ws.config.execution.runtime === 'e2e' ? await runE2E(ws, flow, mode) : await new Runner(ws, mode).run(flow));
40
+ });
41
+ server.registerTool('uwright_diff_lock', { description: 'Read lock generation', inputSchema: {} }, async () => {
42
+ const ws = await loadWorkspace();
43
+ return result(await diffLocks(ws));
44
+ });
45
+ server.registerTool('uwright_inspect_screen', { description: 'Inspect accessibility tree at a URL', inputSchema: { urlOrDeepLink: z.string() } }, async ({ urlOrDeepLink }) => {
46
+ const ws = await loadWorkspace();
47
+ const d = new WebDriver(ws.config, path.join(ws.root, ws.config.artifactsDir, `inspect-${Date.now()}`, 'trace.zip'));
48
+ try {
49
+ await d.start();
50
+ await d.page.goto(new URL(urlOrDeepLink, ws.config.target.baseUrl).href);
51
+ let tree = await d.observe();
52
+ for (const doc of [...ws.contexts, ...ws.skills, ...ws.flows])
53
+ for (const key of doc.frontmatter.secrets) {
54
+ const v = process.env[key];
55
+ if (v)
56
+ tree = tree.split(v).join(`[REDACTED:${key}]`);
57
+ }
58
+ return result({ treeText: tree });
59
+ }
60
+ finally {
61
+ await d.stop();
62
+ }
63
+ });
64
+ await server.connect(new StdioServerTransport());
65
+ }
package/dist/model.js ADDED
@@ -0,0 +1,115 @@
1
+ import { z } from 'zod';
2
+ export const secretKey = z.string().regex(/^[A-Z][A-Z0-9_]*$/);
3
+ export const configSchema = z.object({
4
+ version: z.coerce.string().default('2'),
5
+ flowsDir: z.string().default('./flows'),
6
+ lockDir: z.string().default('./.uwright/lock'),
7
+ artifactsDir: z.string().default('./.uwright/artifacts'),
8
+ target: z.object({
9
+ platform: z.literal('web').default('web'),
10
+ baseUrl: z.string().url(),
11
+ browser: z.enum(['chromium', 'firefox', 'webkit']).default('chromium'),
12
+ headless: z.boolean().default(true),
13
+ viewport: z.object({ width: z.number(), height: z.number() }).default({ width: 1280, height: 800 }),
14
+ }),
15
+ ai: z
16
+ .object({
17
+ provider: z.literal('openai').default('openai'),
18
+ compilerModel: z.string().default('gpt-6-luna'),
19
+ explorerModel: z.string().default('gpt-6-luna'),
20
+ judgeModel: z.string().default('gpt-6-luna'),
21
+ maxStepsPerExplore: z.number().int().positive().default(8),
22
+ maxModelCallsPerFlow: z.number().int().positive().default(30),
23
+ })
24
+ .default({
25
+ provider: 'openai',
26
+ compilerModel: 'gpt-6-luna',
27
+ explorerModel: 'gpt-6-luna',
28
+ judgeModel: 'gpt-6-luna',
29
+ maxStepsPerExplore: 8,
30
+ maxModelCallsPerFlow: 30,
31
+ }),
32
+ execution: z
33
+ .object({
34
+ runtime: z.enum(['legacy', 'e2e']).default('e2e'),
35
+ mode: z.enum(['strict', 'heal', 'record', 'off']).default('heal'),
36
+ defaultTimeoutMs: z.number().positive().default(5000),
37
+ })
38
+ .default({ runtime: 'e2e', mode: 'heal', defaultTimeoutMs: 5000 }),
39
+ });
40
+ export const frontmatterSchema = z.object({
41
+ name: z.string().min(1).optional(),
42
+ description: z.string().optional(),
43
+ secrets: z.array(secretKey).default([]),
44
+ inputs: z
45
+ .array(z.object({
46
+ name: z.string(),
47
+ description: z.string().optional(),
48
+ required: z.boolean().default(false),
49
+ default: z.string().optional(),
50
+ }))
51
+ .default([]),
52
+ tags: z.array(z.string()).default([]),
53
+ timeout_sec: z.number().positive().default(120),
54
+ });
55
+ export class FlowError extends Error {
56
+ code;
57
+ exitCode;
58
+ constructor(code, message, exitCode = 2) {
59
+ super(message);
60
+ this.code = code;
61
+ this.exitCode = exitCode;
62
+ }
63
+ }
64
+ export const locatorSchema = z.object({
65
+ role: z.string(),
66
+ name: z.string(),
67
+ testId: z.string().optional(),
68
+ parentContext: z.string().optional(),
69
+ nth: z.number().int().nonnegative().optional(),
70
+ });
71
+ export const valueSchema = z.union([
72
+ z.object({ type: z.literal('literal'), value: z.string() }),
73
+ z.object({ type: z.literal('secret'), envKey: secretKey }),
74
+ z.object({
75
+ type: z.literal('generator'),
76
+ fn: z.enum(['unique_email', 'unique_uuid', 'unique_string', 'unique_phone', 'today_yyyy_mm_dd', 'timestamp_iso']),
77
+ }),
78
+ z.object({ type: z.literal('skill_input'), inputName: z.string() }),
79
+ z.object({ type: z.literal('asset_path'), filename: z.string() }),
80
+ ]);
81
+ export const actionSchema = z.union([
82
+ z.object({ kind: z.literal('open'), url: z.string() }),
83
+ z.object({ kind: z.literal('click'), locator: locatorSchema }),
84
+ z.object({ kind: z.literal('fill'), locator: locatorSchema, valueSource: valueSchema }),
85
+ z.object({ kind: z.literal('select'), locator: locatorSchema, valueSource: valueSchema }),
86
+ z.object({ kind: z.literal('upload_file'), locator: locatorSchema, valueSource: valueSchema }),
87
+ z.object({ kind: z.literal('press'), key: z.string() }),
88
+ z.object({ kind: z.literal('scroll'), direction: z.enum(['up', 'down']), amount: z.number() }),
89
+ ]);
90
+ export const assertionSchema = z.union([
91
+ z.object({ kind: z.literal('url_contains'), value: z.string() }),
92
+ z.object({ kind: z.literal('visible_text'), value: z.string() }),
93
+ z.object({ kind: z.literal('not_visible_text'), value: z.string() }),
94
+ z.object({
95
+ kind: z.literal('locator_state'),
96
+ locator: locatorSchema,
97
+ state: z.enum(['visible', 'hidden', 'enabled', 'disabled', 'checked', 'visible_and_enabled']),
98
+ }),
99
+ z.object({ kind: z.literal('visual_judge_fallback'), claim: z.string() }),
100
+ ]);
101
+ export const stepSchema = z.union([
102
+ z.object({ kind: z.literal('actions'), text: z.string(), actions: z.array(actionSchema) }),
103
+ z.object({ kind: z.literal('skill'), text: z.string(), name: z.string(), inputs: z.record(z.string(), valueSchema) }),
104
+ z.object({ kind: z.literal('visual'), text: z.string(), claim: z.string() }),
105
+ ]);
106
+ export const lockSchema = z.object({
107
+ version: z.literal(1),
108
+ source: z.string(),
109
+ sourceHash: z.string(),
110
+ contextHash: z.string(),
111
+ steps: z.array(stepSchema),
112
+ setup: z.array(stepSchema),
113
+ teardown: z.array(stepSchema),
114
+ outcomes: z.array(assertionSchema),
115
+ });
@@ -0,0 +1,43 @@
1
+ import { z } from 'zod';
2
+ import { FlowError } from './model.js';
3
+ export const navigationSchema = z.object({ kind: z.literal('navigate'), path: z.string().startsWith('/') });
4
+ export function captureNavigation(summary, baseUrl, secrets, actualUrl) {
5
+ const match = /^navigate to ("(?:[^"\\]|\\.)*")$/.exec(summary);
6
+ if (!match)
7
+ return;
8
+ try {
9
+ const raw = JSON.parse(match[1]);
10
+ if (typeof raw !== 'string')
11
+ return;
12
+ const base = new URL(baseUrl), target = new URL(raw, base);
13
+ if (target.origin !== base.origin || target.username || target.password)
14
+ return;
15
+ const value = `${target.pathname}${target.search}${target.hash}`;
16
+ const actual = actualUrl ?? '';
17
+ const decoded = decodeURIComponent(`${value}\n${actual}`);
18
+ if (/\[REDACTED|<secret:/i.test(value))
19
+ return;
20
+ if (Object.values(secrets).some((secret) => secret &&
21
+ (value.includes(secret) ||
22
+ value.includes(encodeURIComponent(secret)) ||
23
+ actual.includes(secret) ||
24
+ actual.includes(encodeURIComponent(secret)) ||
25
+ decoded.includes(secret))))
26
+ return;
27
+ return { kind: 'navigate', path: value };
28
+ }
29
+ catch {
30
+ return;
31
+ }
32
+ }
33
+ export async function replayNavigation(page, action, baseUrl, timeout) {
34
+ const base = new URL(baseUrl), target = new URL(action.path, base);
35
+ if (target.origin !== base.origin || target.username || target.password)
36
+ throw new FlowError('LOCK_INVALID', 'Recorded navigation leaves the configured origin', 3);
37
+ try {
38
+ await page.goto(target.href, { waitUntil: 'load', timeout });
39
+ }
40
+ catch {
41
+ throw new FlowError('ACTION_UNCERTAIN', 'Navigation may have been attempted; inspect the page before retrying', 3);
42
+ }
43
+ }
@@ -0,0 +1,50 @@
1
+ import { mkdir, readFile, rename, writeFile } from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ /** A local, source-aligned report. Screenshots may contain sensitive UI data. */
4
+ export class RunViewer {
5
+ directory;
6
+ title;
7
+ tracePath;
8
+ file;
9
+ events = [];
10
+ status = 'running';
11
+ constructor(directory, title, tracePath) {
12
+ this.directory = directory;
13
+ this.title = title;
14
+ this.tracePath = tracePath;
15
+ this.file = path.join(directory, 'index.html');
16
+ }
17
+ async start() {
18
+ await mkdir(this.directory, { recursive: true });
19
+ await this.write();
20
+ }
21
+ async add(event, screenshot) {
22
+ const filename = `screen-${this.events.length + 1}.png`;
23
+ try {
24
+ await screenshot(path.join(this.directory, filename));
25
+ event.screenshot = filename;
26
+ }
27
+ catch {
28
+ // The report remains useful if a browser closed before a screenshot.
29
+ }
30
+ this.events.push(event);
31
+ await this.write();
32
+ }
33
+ async finish(status) {
34
+ this.status = status;
35
+ await this.write();
36
+ }
37
+ async write() {
38
+ const data = JSON.stringify({
39
+ title: this.title,
40
+ status: this.status,
41
+ events: this.events,
42
+ tracePath: this.tracePath,
43
+ }).replace(/[<>&\u2028\u2029]/g, (c) => `\\u${c.charCodeAt(0).toString(16).padStart(4, '0')}`);
44
+ const template = await readFile(new URL('./templates/run-viewer.html', import.meta.url), 'utf8');
45
+ const html = template.replace('__UWRIGHT_REPORT_DATA_JSON__', data);
46
+ const temporary = path.join(this.directory, 'index.tmp');
47
+ await writeFile(temporary, html);
48
+ await rename(temporary, this.file);
49
+ }
50
+ }