@fliwright/vitest 0.0.0-stage → 0.1.0

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/index.js ADDED
@@ -0,0 +1,658 @@
1
+ import { afterAll, afterEach as vitestAfterEach, beforeAll, beforeEach as vitestBeforeEach, describe, expect as vitestExpect, test as vitestTest, } from 'vitest';
2
+ import { AsyncLocalStorage } from 'node:async_hooks';
3
+ import { mkdir, readFile, writeFile } from 'node:fs/promises';
4
+ import { dirname, join, resolve } from 'node:path';
5
+ import { AgentRuntime, AssertRuntime, AiRuntime, Assertion, FileLogSink, FliwrightDriver, FlowRuntime, JsonlLogSink, MockRuntime, PassiveAgent, Page as FliwrightPage, PrettyLogFormatter, readWorkspaceConfigSync, resolveFliwrightRunsRoot, resolveFliwrightCacheRoot, resolveFliwrightProjectRoot, StructuredLogger, RunArtifactStore, EvidenceCapture, createExpect, resolveAiConfig, ScenarioCoordinator, ScenarioResolver, fingerprintScenario, DEFAULT_FLIWRIGHT_CONFIG, EndpointLeaseManager, mergeFliwrightConfig, readFliwrightEnvironment, } from '@fliwright/core';
6
+ import { requireAttemptContext } from './AttemptContext.js';
7
+ import { getTaskEndpointLease, setTaskEndpointLease, finishTaskEndpointLeasePhase } from './TaskEndpointLease.js';
8
+ import { withTaskPreparation } from './TestRegistration.js';
9
+ export { FliwrightRunner, createFliwrightRunner } from './runner.js';
10
+ export { fliwrightPreset } from './preset.js';
11
+ export { FliwrightRecoveryReporter } from './RecoveryReporter.js';
12
+ export function defineConfig(overrides) {
13
+ return {
14
+ timeout: 5000,
15
+ screenshot: 'file',
16
+ recording: { ...DEFAULT_FLIWRIGHT_CONFIG.recording, ...overrides.recording },
17
+ ...overrides,
18
+ };
19
+ }
20
+ /**
21
+ * Decide where run artifacts go for a fliwright test run.
22
+ * Precedence is implemented by @fliwright/core:
23
+ * explicit config.runsRoot > FLIWRIGHT_RUNS_ROOT env > project-local root.
24
+ */
25
+ export function resolveRunsRoot(config) {
26
+ return resolveFliwrightRunsRoot({
27
+ runsRoot: config.runsRoot,
28
+ projectRoot: config.projectRoot ?? process.env.FLIWRIGHT_PROJECT_ROOT ?? resolveFliwrightProjectRoot(),
29
+ });
30
+ }
31
+ const sharedDrivers = new Map();
32
+ const endpointLeases = new EndpointLeaseManager();
33
+ let nextPluginId = 1;
34
+ const pluginIds = new WeakMap();
35
+ const testContext = new AsyncLocalStorage();
36
+ let currentTestContext = null;
37
+ const scenarioConfigs = new WeakMap();
38
+ export function createFliwrightTest(config, options) {
39
+ // Persistent Vitest workers reuse fixture modules across reruns. Resolve
40
+ // process settings at fixture use so a new run does not retain the old root.
41
+ const resolveConfig = () => ({ ...config,
42
+ ...mergeFliwrightConfig({ environment: readFliwrightEnvironment(process.env), explicit: config }),
43
+ });
44
+ const resolveDriver = options?.driverProvider
45
+ ? () => options.driverProvider()
46
+ : () => getSharedDriver(resolveConfig());
47
+ let fliwrightTest = vitestTest.extend({
48
+ _fliwrightEndpointLease: [async ({ task }, use) => {
49
+ await requireAttemptContext(task).beforeFixtures?.();
50
+ const endpoint = resolveConfig().vmServiceUrl.trim();
51
+ if (endpoint && getTaskEndpointLease(task)) {
52
+ // A retry retains ownership but starts a fresh fixture lifecycle.
53
+ setTaskEndpointLease(task, getTaskEndpointLease(task));
54
+ }
55
+ try {
56
+ await use(undefined);
57
+ }
58
+ finally {
59
+ // Dynamic skip bypasses onAfterRunTask. Normal tasks retain ownership
60
+ // through runner evidence/finalization and all retries.
61
+ try {
62
+ // Vitest 4.1 sets pending before unwinding an aroundEach skip;
63
+ // that field is present at runtime but omitted from TaskResult.
64
+ const pendingSkip = task.result?.pending === true;
65
+ if ((task.result?.state === 'skip' || pendingSkip) && !requireAttemptContext(task).runnerEntered) {
66
+ await requireAttemptContext(task).onSetupSkipped?.();
67
+ }
68
+ }
69
+ finally {
70
+ await finishTaskEndpointLeasePhase(task, 'cleanupComplete');
71
+ }
72
+ }
73
+ }, { auto: true }],
74
+ timeline: async ({ task }, use) => {
75
+ const config = resolveConfig();
76
+ const testName = getTestName(task);
77
+ const attempt = requireAttemptContext(task);
78
+ const cwd = config.projectRoot ?? process.env.FLIWRIGHT_PROJECT_ROOT ?? config.timelineDir ?? resolveFliwrightProjectRoot();
79
+ const runsRoot = resolveRunsRoot({ runsRoot: config.runsRoot, projectRoot: cwd });
80
+ const store = new RunArtifactStore({ runsRoot, runId: attempt.runId });
81
+ const logger = createRunLogger(config, {
82
+ runId: attempt.runId, testName, mode: config.mode ?? 'test',
83
+ runDir: store.attemptDir(task.id, attempt.attemptId),
84
+ });
85
+ await attempt.configure({ runsRoot, mode: config.mode ?? 'test', logger, recordingMode: config.recording?.mode,
86
+ testFinalizationBudgetMs: config.recording?.testFinalizationBudgetMs });
87
+ if (config.vmServiceUrl.trim()) {
88
+ const lease = getTaskEndpointLease(task);
89
+ attempt.session.configureEndpointLease(lease ? {
90
+ run: (endpoint, execute) => lease.run(() => endpointLeases.run(endpoint, execute)),
91
+ } : endpointLeases, config.vmServiceUrl);
92
+ }
93
+ const timeline = { recorder: attempt.recorder,
94
+ artifactStore: attempt.artifactStore, runId: attempt.runId, logger, runSession: attempt.session };
95
+ attempt.onFailure = async (error, node, signal) => {
96
+ await writeFailureProjection(timeline, error, node, config, signal);
97
+ if (!signal.aborted)
98
+ attempt.failureContextPath = 'failures.json';
99
+ };
100
+ if (config.agentPolicy?.passive === true && (config.agentPolicy.onFailure ?? 'diagnose') === 'diagnose') {
101
+ attempt.beforeFinish = (signal) => diagnoseTimelineFailures(timeline, config, resolveDriver, signal, () => Math.max(1, attempt.finalization.remainingMs - attempt.persistenceReserveMs));
102
+ }
103
+ const ctx = testContext.getStore();
104
+ if (ctx)
105
+ ctx.timeline = timeline;
106
+ attempt.validate = () => {
107
+ const required = config.requireAssertions ?? config.recording?.requireAssertions
108
+ ?? (config.mode !== 'script' && DEFAULT_FLIWRIGHT_CONFIG.recording.requireAssertions);
109
+ if (required && !timeline.recorder.toJSON().nodes.some((node) => node.kind === 'assertion')
110
+ // The runner resets Vitest counts before every attempt, after aroundEach fixtures resolve.
111
+ && (vitestExpect.getState().assertionCalls ?? 0) === 0
112
+ && task.context.expect.getState().assertionCalls === 0) {
113
+ return new Error('Test mode requires at least one executed assertion, but none were recorded. Add an assertion or use script mode.');
114
+ }
115
+ return undefined;
116
+ };
117
+ logger.info(`${config.mode === 'script' ? 'Script' : 'Test'} started`);
118
+ await use(timeline);
119
+ },
120
+ driver: async ({ task, timeline }, use) => {
121
+ const driver = await resolveDriver();
122
+ timeline.driver = driver;
123
+ const testName = getTestName(task);
124
+ const previous = currentTestContext;
125
+ const ctx = { driver, testName, timeline };
126
+ currentTestContext = ctx;
127
+ let useFailed = false;
128
+ try {
129
+ await testContext.run(ctx, async () => {
130
+ await use(driver);
131
+ });
132
+ }
133
+ catch (error) {
134
+ useFailed = true;
135
+ throw error;
136
+ }
137
+ finally {
138
+ currentTestContext = previous;
139
+ if (options?.driverProvider) {
140
+ const attempt = requireAttemptContext(task);
141
+ try {
142
+ // Calling dispose even after an earlier stage exhausts its budget
143
+ // still initiates transport cleanup; only the wait is bounded.
144
+ if (attempt.finalization.remainingMs <= attempt.persistenceReserveMs) {
145
+ const controller = new AbortController();
146
+ controller.abort(new Error('Driver cleanup exceeded the test finalization budget.'));
147
+ void driver.dispose({ signal: controller.signal }).catch((error) => attempt.recordEvidenceIssue(error));
148
+ }
149
+ await attempt.finalization.run('Driver cleanup', (signal) => driver.dispose({ signal }), attempt.persistenceReserveMs);
150
+ }
151
+ catch (error) {
152
+ attempt.recordEvidenceIssue(error);
153
+ if (!useFailed && task.result?.state !== 'fail')
154
+ throw error;
155
+ }
156
+ }
157
+ }
158
+ },
159
+ page: async ({ task, timeline, driver }, use) => {
160
+ const config = resolveConfig();
161
+ timeline.driver = driver;
162
+ const testName = getTestName(task);
163
+ const ctx = { driver, testName, timeline };
164
+ const previous = currentTestContext;
165
+ currentTestContext = ctx;
166
+ try {
167
+ await testContext.run(ctx, async () => {
168
+ const page = new FliwrightPage((method, params) => driver.sendRequest(method, params), {
169
+ recorder: timeline.recorder, artifactStore: timeline.artifactStore, runSession: timeline.runSession,
170
+ });
171
+ configureRunSessionEvidence(timeline, page, config, () => requireAttemptContext(task).finalizationSignal);
172
+ const recordingMode = config.recording?.mode ?? parseRecordingMode(process.env.FLIWRIGHT_RECORDING_MODE) ?? 'standard';
173
+ if (recordingMode !== 'off')
174
+ await captureTestLifecycleScreenshot(timeline, page, 'start');
175
+ try {
176
+ await use(page);
177
+ }
178
+ finally {
179
+ if (recordingMode !== 'off' && (config.recording?.testFinalScreenshots ?? DEFAULT_FLIWRIGHT_CONFIG.recording.testFinalScreenshots)) {
180
+ await requireAttemptContext(task).finalizeStep('Final screenshot', async (signal) => {
181
+ if (!signal.aborted)
182
+ await captureTestLifecycleScreenshot(timeline, page, 'finish', signal);
183
+ });
184
+ }
185
+ }
186
+ });
187
+ }
188
+ finally {
189
+ currentTestContext = previous;
190
+ }
191
+ },
192
+ aiRuntime: async ({ task, timeline, driver }, use) => {
193
+ const config = resolveConfig();
194
+ timeline.driver = driver;
195
+ const testName = getTestName(task);
196
+ const runtime = new AiRuntime(resolveAiConfig(config.ai), {
197
+ attemptDir: timeline.artifactStore.runDir,
198
+ page: driver.page,
199
+ driver,
200
+ testName,
201
+ runId: timeline.runId,
202
+ cwd: process.cwd(),
203
+ });
204
+ await use(runtime);
205
+ },
206
+ flow: async ({ page, timeline }, use) => {
207
+ await use(new FlowRuntime({ recorder: timeline.recorder, artifactStore: timeline.artifactStore, page,
208
+ runSession: timeline.runSession }));
209
+ },
210
+ mock: async ({ driver, timeline }, use) => {
211
+ await use(new MockRuntime(driver.mock, timeline.recorder));
212
+ },
213
+ agent: async ({ aiRuntime, timeline }, use) => {
214
+ await use(new AgentRuntime({ aiRuntime, recorder: timeline.recorder }));
215
+ },
216
+ assert: async ({ page, mock, timeline }, use) => {
217
+ await use(new AssertRuntime({
218
+ page,
219
+ mock,
220
+ recorder: timeline.recorder,
221
+ artifactStore: timeline.artifactStore,
222
+ }));
223
+ },
224
+ logger: async ({ timeline }, use) => {
225
+ await use(timeline.logger);
226
+ },
227
+ });
228
+ const selected = resolveConfig().defaultScenario;
229
+ if (selected) {
230
+ fliwrightTest = fliwrightTest.extend({
231
+ _fliwrightDefaultScenario: [async ({ driver, timeline }, use) => {
232
+ const selectedScenario = new ScenarioResolver(resolveConfig().scenarios ?? {}).resolve(selected);
233
+ const node = timeline.recorder.startNode('step', `Scenario: ${selected}`);
234
+ await new ScenarioCoordinator(driver).apply(selectedScenario, { mode: resolveConfig().scenarioMode ?? 'attach' });
235
+ timeline.recorder.passNode(node.id, { scenarioName: selected, scenarioFingerprint: fingerprintScenario(selectedScenario) });
236
+ await use(undefined);
237
+ }, { auto: true }],
238
+ });
239
+ }
240
+ return withScenarioSupport(fliwrightTest, resolveConfig);
241
+ }
242
+ function withScenarioSupport(test, resolveConfig) {
243
+ const prepare = async (task, signal) => {
244
+ const config = resolveConfig();
245
+ requireAttemptContext(task).configureRecordingPolicy({ recordingMode: config.recording?.mode,
246
+ testFinalizationBudgetMs: config.recording?.testFinalizationBudgetMs });
247
+ const endpoint = config.vmServiceUrl.trim();
248
+ if (endpoint && !getTaskEndpointLease(task)) {
249
+ const lease = await endpointLeases.acquire(endpoint, { signal: AbortSignal.any([signal, task.context.signal]) });
250
+ if (signal.aborted) {
251
+ await lease.release();
252
+ signal.throwIfAborted();
253
+ }
254
+ setTaskEndpointLease(task, lease);
255
+ }
256
+ };
257
+ const scenarioTest = withTaskPreparation(test, prepare);
258
+ scenarioConfigs.set(scenarioTest, resolveConfig);
259
+ scenarioTest.scenario = (scenarioName) => {
260
+ const config = resolveConfig();
261
+ if (config.defaultScenario && config.defaultScenario !== scenarioName)
262
+ throw new Error(`Explicit scenario '${scenarioName}' conflicts with selected scenario '${config.defaultScenario}'.`);
263
+ if (config.defaultScenario === scenarioName)
264
+ return (name, handler, timeout) => { scenarioTest(name, handler, timeout); };
265
+ const scenarios = config.scenarios;
266
+ if (!scenarios) {
267
+ throw new Error(`Test scenario '${scenarioName}' was requested, but defineConfig({ scenarios }) is missing.`);
268
+ }
269
+ const scenario = new ScenarioResolver(scenarios).resolve(scenarioName);
270
+ // The automatic fixture adds preparation without wrapping the handler, so
271
+ // Vitest still discovers and lazily injects its project fixture dependencies.
272
+ const prepared = scenarioTest.extend({
273
+ _fliwrightScenario: [async ({ driver, timeline }, use) => {
274
+ const scenarioNode = timeline.recorder.startNode('step', `Scenario: ${scenarioName}`);
275
+ await timeline.recorder.flushProgress();
276
+ await new ScenarioCoordinator(driver).apply(scenario, {
277
+ mode: config.scenarioMode ?? 'attach',
278
+ });
279
+ timeline.recorder.passNode(scenarioNode.id, {
280
+ scenarioName, scenarioFingerprint: fingerprintScenario(scenario),
281
+ });
282
+ await timeline.recorder.flushProgress();
283
+ await use(undefined);
284
+ }, { auto: true }],
285
+ });
286
+ return (name, handler, timeout) => { prepared(name, handler, timeout); };
287
+ };
288
+ return scenarioTest;
289
+ }
290
+ export function extendFliwrightTest(base, fixtures) {
291
+ const resolveConfig = scenarioConfigs.get(base);
292
+ if (!resolveConfig)
293
+ throw new Error('extendFliwrightTest requires a base from createFliwrightTest or extendFliwrightTest.');
294
+ const extended = base.extend(fixtures);
295
+ return withScenarioSupport(extended, resolveConfig);
296
+ }
297
+ function configureRunSessionEvidence(timeline, page, config, getFinalizationSignal) {
298
+ const session = timeline.runSession;
299
+ if (!session)
300
+ return;
301
+ const mode = config.recording?.mode ?? parseRecordingMode(process.env.FLIWRIGHT_RECORDING_MODE) ?? 'standard';
302
+ const budget = config.recording?.failureCaptureBudgetMs ?? DEFAULT_FLIWRIGHT_CONFIG.recording.failureCaptureBudgetMs;
303
+ const capture = new EvidenceCapture({ totalBudgetMs: budget, channelTimeoutMs: budget / 3 });
304
+ session.configureRecording({
305
+ mode,
306
+ captureEvidence: async (request) => {
307
+ if (mode === 'off' && request.reason !== 'explicit')
308
+ return { status: 'disabled' };
309
+ const signal = getFinalizationSignal();
310
+ const suffix = `${request.operationId ?? 'checkpoint'}-${request.reason}`;
311
+ const sources = {
312
+ screenshot: async () => {
313
+ const screenshot = await page.screenshot({ waitForAnimations: true });
314
+ signal?.throwIfAborted();
315
+ return timeline.artifactStore.writeScreenshot(suffix, screenshot);
316
+ },
317
+ snapshot: async () => {
318
+ const snapshot = await page.snapshot();
319
+ signal?.throwIfAborted();
320
+ return timeline.artifactStore.writeSnapshot(suffix, snapshot);
321
+ },
322
+ diagnostics: async () => {
323
+ const frame = await page.captureFrame({ screenshot: false, snapshot: false, diagnostics: true });
324
+ signal?.throwIfAborted();
325
+ return timeline.artifactStore.writeDiagnostics(suffix, frame.diagnostics ?? frame);
326
+ },
327
+ };
328
+ const result = await capture.capture(request.reason === 'failure' ? suffix : `${suffix}-${request.kind}`, request.reason === 'failure' ? sources : { [request.kind]: sources[request.kind] }, { signal });
329
+ const channel = result.channels[request.kind];
330
+ const artifact = channel.value;
331
+ return { status: channel.status, ...(artifact ? { artifactPaths: [artifact.path] } : {}),
332
+ ...(channel.error ? { error: channel.error } : {}) };
333
+ },
334
+ });
335
+ }
336
+ async function captureTestLifecycleScreenshot(timeline, page, reason, signal) {
337
+ const node = timeline.recorder.startNode('step', `Test ${reason} screenshot`, {
338
+ metadata: { lifecycle: reason },
339
+ });
340
+ await timeline.recorder.flushProgress();
341
+ if (signal?.aborted)
342
+ return;
343
+ const result = await timeline.runSession?.checkpoint({ kind: 'screenshot', reason })
344
+ ?? { status: 'disabled' };
345
+ if (signal?.aborted)
346
+ return;
347
+ const artifacts = result.artifactPaths?.map((path) => ({ kind: 'screenshot', path, mimeType: 'image/png' })) ?? [];
348
+ if (artifacts.length)
349
+ timeline.recorder.addArtifacts(node.id, artifacts);
350
+ timeline.recorder.passNode(node.id, { evidenceStatus: result.status });
351
+ await timeline.recorder.flushProgress();
352
+ }
353
+ export function createFliwrightScript(config) {
354
+ return createFliwrightTest({ ...config, mode: 'script', requireAssertions: false });
355
+ }
356
+ export const test = createFliwrightTest(testConfigFromEnv());
357
+ export const script = createFliwrightScript(testConfigFromEnv());
358
+ export function beforeEach(hook, timeout) {
359
+ vitestBeforeEach(hook, timeout);
360
+ }
361
+ export function afterEach(hook, timeout) {
362
+ vitestAfterEach(hook, timeout);
363
+ }
364
+ export { afterAll, beforeAll, describe };
365
+ export function expect(locator, title) {
366
+ const context = testContext.getStore() ?? currentTestContext;
367
+ const locatorTimeline = locator.assertionTimeline;
368
+ if (!context)
369
+ return createExpect(locator, undefined, { ...locatorTimeline, title: title ?? locatorTimeline?.title });
370
+ return new Assertion(locator, false, undefined, process.env.FLIWRIGHT_RECORDING_REPLAY === '1' ? undefined : context.driver.healing, context.testName, (method, params) => context.driver.sendRequest(method, params), locatorTimeline?.recorder
371
+ ? { ...locatorTimeline, title: title ?? locatorTimeline.title }
372
+ : context.timeline
373
+ ? {
374
+ title,
375
+ recorder: context.timeline.recorder,
376
+ artifactStore: context.timeline.artifactStore,
377
+ page: context.driver.page,
378
+ runSession: context.timeline.runSession,
379
+ }
380
+ : { title });
381
+ }
382
+ /** Project the same saved evidence to the CLI/MCP report; never recapture it. */
383
+ async function writeFailureProjection(timeline, error, node, config, signal) {
384
+ const outputPath = join(timeline.artifactStore.runDir, 'failures.json');
385
+ const readArtifact = async (kind) => {
386
+ const artifact = node.artifacts?.find((item) => item.kind === kind);
387
+ return artifact ? readFile(join(timeline.artifactStore.runDir, artifact.path)).catch(() => undefined) : undefined;
388
+ };
389
+ const [snapshot, diagnostics] = await Promise.all([readArtifact('snapshot'), readArtifact('diagnostics')]);
390
+ if (signal.aborted)
391
+ return;
392
+ const screenshot = node.artifacts?.find((artifact) => artifact.kind === 'screenshot');
393
+ const original = error;
394
+ const lines = original.stack?.split('\n') ?? [];
395
+ const frame = lines.find((line) => line.includes('.test.') || line.includes('.script.')) ?? lines[1] ?? '';
396
+ const parsed = frame.match(/\(?((?:file:\/\/\/|\/|[A-Za-z]:\\)[^\n()]+):(\d+):(\d+)\)?$/);
397
+ const source = original.stacks?.[0] ?? (parsed ? { file: parsed[1], line: Number(parsed[2]) } : undefined);
398
+ let healingSuggestion;
399
+ try {
400
+ const report = timeline.driver?.healing.getReports(timeline.recorder.testName).at(-1);
401
+ if (report)
402
+ healingSuggestion = { originalSelector: report.originalSelector, suggestedSelector: report.suggestedSelector,
403
+ confidence: report.confidence, scores: report.scores };
404
+ }
405
+ catch { /* Keep the original failure when no healing report is available. */ }
406
+ const entry = {
407
+ testName: timeline.recorder.testName,
408
+ ...(healingSuggestion ? { healingSuggestion } : {}),
409
+ assertion: { matcher: 'unknown', expected: 'pass', actual: original.message ?? String(error), timeout: config.timeout ?? 5000 },
410
+ widgetTree: snapshot ? JSON.parse(snapshot.toString()) : { error: 'Evidence unavailable' },
411
+ ...(diagnostics ? { diagnostics: JSON.parse(diagnostics.toString()) } : {}),
412
+ source: { file: source?.file ?? '<unknown>', line: source?.line ?? 0, snippet: original.message ?? String(error) },
413
+ ...(screenshot && config.screenshot !== 'off' ? { screenshot: { mimeType: 'image/png', path: screenshot.path } } : {}),
414
+ timestamp: node.startedAt,
415
+ };
416
+ await mkdir(dirname(outputPath), { recursive: true });
417
+ const entries = await readFile(outputPath, 'utf8').then((text) => JSON.parse(text)).catch(() => []);
418
+ if (signal.aborted)
419
+ return;
420
+ entries.push(timeline.runSession?.redactReport(entry) ?? entry);
421
+ await writeFile(outputPath, JSON.stringify(entries, null, 2), { signal });
422
+ }
423
+ async function getSharedDriver(config) {
424
+ const vmServiceUrl = toWebSocketUrl(config.vmServiceUrl);
425
+ if (!vmServiceUrl) {
426
+ throw new Error('No VM Service URL provided. Set FLIWRIGHT_VM_URL or FLIWRIGHT_VM_SERVICE_URL, or use createFliwrightTest({ vmServiceUrl }).');
427
+ }
428
+ const cacheRoot = resolveFliwrightCacheRoot({ cacheRoot: config.cacheRoot,
429
+ projectRoot: config.projectRoot ?? process.env.FLIWRIGHT_PROJECT_ROOT });
430
+ const key = `${sharedDriverCacheKey(vmServiceUrl, config.plugins)}:${cacheRoot}`;
431
+ let pending = sharedDrivers.get(key);
432
+ if (!pending) {
433
+ pending = (async () => {
434
+ const driver = new FliwrightDriver({ plugins: config.plugins, cacheRoot });
435
+ try {
436
+ await driver.connect(vmServiceUrl);
437
+ await listenToDiagnostics(driver);
438
+ return driver;
439
+ }
440
+ catch (error) {
441
+ await driver.dispose().catch(() => undefined);
442
+ throw error;
443
+ }
444
+ })();
445
+ sharedDrivers.set(key, pending);
446
+ }
447
+ try {
448
+ return await pending;
449
+ }
450
+ catch (error) {
451
+ if (sharedDrivers.get(key) === pending)
452
+ sharedDrivers.delete(key);
453
+ throw error;
454
+ }
455
+ }
456
+ function sharedDriverCacheKey(vmServiceUrl, plugins) {
457
+ return JSON.stringify({
458
+ vmServiceUrl,
459
+ plugins: (plugins ?? []).map((plugin) => `${plugin.name}:${pluginIdentity(plugin)}`),
460
+ });
461
+ }
462
+ function pluginIdentity(plugin) {
463
+ const existing = pluginIds.get(plugin);
464
+ if (existing !== undefined)
465
+ return existing;
466
+ const id = nextPluginId++;
467
+ pluginIds.set(plugin, id);
468
+ return id;
469
+ }
470
+ async function listenToDiagnostics(driver) {
471
+ try {
472
+ await driver.listenToDiagnostics();
473
+ }
474
+ catch {
475
+ // Diagnostics are helpful for AI reports but should not prevent tests from running.
476
+ }
477
+ }
478
+ function testConfigFromEnv() {
479
+ return {
480
+ vmServiceUrl: toWebSocketUrl(process.env.FLIWRIGHT_VM_URL
481
+ ?? process.env.FLIWRIGHT_VM_SERVICE_URL
482
+ ?? readWorkspaceConfigSync().vmServiceUrl
483
+ ?? ''),
484
+ timeout: parsePositiveInt(process.env.FLIWRIGHT_FAILURE_TIMEOUT_MS) ?? 5000,
485
+ screenshot: parseScreenshotMode(process.env.FLIWRIGHT_SCREENSHOT_MODE),
486
+ log: logConfigFromEnv(),
487
+ };
488
+ }
489
+ function parseScreenshotMode(value) {
490
+ if (value === 'base64' || value === 'off')
491
+ return value;
492
+ return 'file';
493
+ }
494
+ function parseRecordingMode(value) {
495
+ if (value === 'standard' || value === 'full' || value === 'off')
496
+ return value;
497
+ return undefined;
498
+ }
499
+ function parsePositiveInt(value) {
500
+ if (!value)
501
+ return undefined;
502
+ const parsed = Number.parseInt(value, 10);
503
+ return Number.isFinite(parsed) && parsed > 0 ? parsed : undefined;
504
+ }
505
+ function createRunLogger(config, options) {
506
+ const logConfig = mergeLogConfig(config.log, logConfigFromEnv());
507
+ return new StructuredLogger({
508
+ runId: options.runId,
509
+ testName: options.testName,
510
+ mode: options.mode,
511
+ kind: options.mode === 'script' ? 'script' : 'test',
512
+ level: logConfig.level ?? 'info',
513
+ sinks: createLogSinks(logConfig, options.runDir),
514
+ });
515
+ }
516
+ function createLogSinks(config, runDir) {
517
+ const format = config.format ?? 'pretty';
518
+ if (format === 'silent')
519
+ return [];
520
+ const outputs = config.outputs ?? ['jsonl-file'];
521
+ const sinks = [];
522
+ for (const output of outputs) {
523
+ switch (output) {
524
+ case 'stderr':
525
+ sinks.push(new FileDescriptorLogSink(2, format));
526
+ break;
527
+ case 'stdout':
528
+ sinks.push(new FileDescriptorLogSink(1, format));
529
+ break;
530
+ case 'file':
531
+ sinks.push(new FileLogSink(resolveLogPath(config.filePath, runDir, 'logs/run.log'), new PrettyLogFormatter({ color: false })));
532
+ break;
533
+ case 'jsonl-file':
534
+ sinks.push(new JsonlLogSink(resolveLogPath(config.jsonlPath, runDir, 'logs/events.jsonl')));
535
+ break;
536
+ default:
537
+ break;
538
+ }
539
+ }
540
+ return sinks;
541
+ }
542
+ class FileDescriptorLogSink {
543
+ sink;
544
+ constructor(fd, format) {
545
+ const stream = fd === 1 ? process.stdout : process.stderr;
546
+ this.sink = new (class {
547
+ write(event) {
548
+ stream.write(`${formatEventForStream(event, format)}\n`);
549
+ }
550
+ })();
551
+ }
552
+ write(event) {
553
+ void this.sink.write(event);
554
+ }
555
+ }
556
+ function formatEventForStream(event, format) {
557
+ switch (format) {
558
+ case 'jsonl':
559
+ return JSON.stringify(event);
560
+ case 'compact':
561
+ return `${event.level.toUpperCase()} ${event.kind}: ${event.message}`;
562
+ case 'pretty':
563
+ default:
564
+ return new PrettyLogFormatter({ color: true }).format(event);
565
+ }
566
+ }
567
+ function resolveLogPath(path, runDir, fallback) {
568
+ const template = path ?? join(runDir, fallback);
569
+ const expanded = template.replace('{runDir}', runDir);
570
+ return resolve(process.cwd(), expanded);
571
+ }
572
+ function mergeLogConfig(primary, fallback) {
573
+ return {
574
+ ...fallback,
575
+ ...primary,
576
+ outputs: primary?.outputs ?? fallback?.outputs,
577
+ };
578
+ }
579
+ function logConfigFromEnv() {
580
+ const level = parseLogLevel(process.env.FLIWRIGHT_LOG_LEVEL);
581
+ const format = parseLogFormat(process.env.FLIWRIGHT_LOG_FORMAT);
582
+ const outputs = parseLogOutputs(process.env.FLIWRIGHT_LOG_OUTPUT);
583
+ const config = {
584
+ ...(level ? { level } : {}),
585
+ ...(format ? { format } : {}),
586
+ ...(outputs ? { outputs } : {}),
587
+ ...(process.env.FLIWRIGHT_LOG_FILE ? { filePath: process.env.FLIWRIGHT_LOG_FILE } : {}),
588
+ ...(process.env.FLIWRIGHT_LOG_JSONL ? { jsonlPath: process.env.FLIWRIGHT_LOG_JSONL } : {}),
589
+ };
590
+ return Object.keys(config).length ? config : undefined;
591
+ }
592
+ function parseLogLevel(value) {
593
+ if (value === 'trace' || value === 'debug' || value === 'info' || value === 'warn' || value === 'error' || value === 'success') {
594
+ return value;
595
+ }
596
+ return undefined;
597
+ }
598
+ function parseLogFormat(value) {
599
+ if (value === 'pretty' || value === 'compact' || value === 'jsonl' || value === 'silent')
600
+ return value;
601
+ return undefined;
602
+ }
603
+ function parseLogOutputs(value) {
604
+ if (!value)
605
+ return undefined;
606
+ const outputs = value.split(',').map((part) => part.trim()).filter(Boolean);
607
+ const parsed = outputs.filter((output) => output === 'stderr' || output === 'stdout' || output === 'file' || output === 'jsonl-file');
608
+ return parsed.length ? parsed : undefined;
609
+ }
610
+ function toWebSocketUrl(url) {
611
+ if (!url)
612
+ return '';
613
+ const converted = url
614
+ .replace('http://', 'ws://')
615
+ .replace('https://', 'wss://');
616
+ return converted.endsWith('/ws') ? converted : converted.replace(/\/?$/, '/ws');
617
+ }
618
+ function getTestName(task) {
619
+ const candidate = task;
620
+ if (typeof candidate.name === 'string')
621
+ return candidate.name;
622
+ return '<unknown>';
623
+ }
624
+ async function diagnoseTimelineFailures(timeline, config, resolveDriver, signal, remainingMs) {
625
+ if (config.agentPolicy?.passive !== true || (config.agentPolicy.onFailure ?? 'diagnose') !== 'diagnose')
626
+ return;
627
+ const failures = timeline.recorder.toJSON().agentVisibleFailures ?? [];
628
+ if (failures.length === 0)
629
+ return;
630
+ try {
631
+ const driver = await resolveDriver();
632
+ if (signal.aborted)
633
+ return;
634
+ const data = timeline.recorder.toJSON();
635
+ for (const failure of failures) {
636
+ if (signal.aborted)
637
+ return;
638
+ const aiRuntime = new AiRuntime({ ...resolveAiConfig(config.ai),
639
+ timeoutMs: Math.min(config.ai?.timeoutMs ?? Infinity, remainingMs()),
640
+ }, {
641
+ attemptDir: timeline.artifactStore.runDir, page: driver.page, driver, testName: timeline.recorder.testName, runId: timeline.runId, cwd: process.cwd(),
642
+ });
643
+ const agent = new PassiveAgent({ aiRuntime, recorder: timeline.recorder, passive: true, signal });
644
+ const currentNode = data.nodes.find((node) => node.id === failure.timelineNodeId);
645
+ await agent.diagnose(failure, {
646
+ currentNode,
647
+ recentNodes: data.nodes.slice(-8),
648
+ artifacts: currentNode?.artifacts,
649
+ });
650
+ }
651
+ }
652
+ catch (error) {
653
+ timeline.logger.warn('Passive AI diagnosis failed; preserving the original failure.', {
654
+ error: error instanceof Error ? error.message : String(error),
655
+ });
656
+ throw error;
657
+ }
658
+ }
@@ -0,0 +1,17 @@
1
+ import type { FliwrightPathsConfig, FliwrightRecordingConfig, ScenarioExecutionMode, TestScenario } from '@fliwright/core';
2
+ export interface FliwrightVitestPresetOptions {
3
+ runner?: string;
4
+ test?: Record<string, unknown>;
5
+ recording?: Partial<FliwrightRecordingConfig>;
6
+ paths?: Partial<FliwrightPathsConfig>;
7
+ runsRoot?: string;
8
+ cacheRoot?: string;
9
+ projectRoot?: string;
10
+ scenarios?: Record<string, TestScenario>;
11
+ scenarioMode?: ScenarioExecutionMode;
12
+ defaultScenario?: string;
13
+ }
14
+ /** Returns a Vitest config fragment using the built Fliwright runner adapter. */
15
+ export declare function fliwrightPreset(options?: FliwrightVitestPresetOptions): {
16
+ test: Record<string, unknown>;
17
+ };