@fliwright/vitest 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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Fliwright contributors.
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,15 @@
1
- # Temporary Holding Version
1
+ # @fliwright/vitest
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
+ Vitest fixtures for Fliwright Flutter E2E tests.
4
+
5
+ ```ts
6
+ import { expect, test } from '@fliwright/vitest';
7
+
8
+ test('increments the counter', async ({ page }) => {
9
+ await page.locator('text=Increment').click();
10
+ await expect(page.locator('text=Count: 1')).toBeVisible();
11
+ });
12
+ ```
13
+
14
+ Use `fliwright init` to create compatible configuration and a test-only Flutter
15
+ entrypoint. The current supported Vitest version is 5.0.5.
@@ -0,0 +1,78 @@
1
+ import { RunArtifactStore, TimelineArtifactStore, TimelineRecorder } from '@fliwright/core';
2
+ import type { FliwrightLogger, RecordingMode, RunSession, RunSessionResult, TimelineRunMode, TimelineNode, ScenarioDevicePreparation } from '@fliwright/core';
3
+ import type { RunnerTask } from 'vitest';
4
+ import { FinalizationBudget } from './FinalizationBudget.js';
5
+ /** Shared by the runner and fixture module, including separate Vitest module graphs. */
6
+ export declare class AttemptContext {
7
+ readonly session: RunSession;
8
+ readonly runId: string;
9
+ readonly testId: string;
10
+ readonly testName: string;
11
+ readonly attemptId: string;
12
+ managedApp?: import('@fliwright/core').ManagedAppAttemptEndpoint;
13
+ androidReadback?: import('@fliwright/core').AndroidAppReadbackReport;
14
+ managedAppDriver?: Promise<import('@fliwright/core').FliwrightDriver>;
15
+ cleanupManagedAppDriver?: (signal: AbortSignal) => Promise<void>;
16
+ devicePreparation?: ScenarioDevicePreparation;
17
+ recorder: TimelineRecorder;
18
+ artifactStore: TimelineArtifactStore;
19
+ runStore: RunArtifactStore;
20
+ recordingMode: RecordingMode;
21
+ logger?: FliwrightLogger;
22
+ failureContextPath?: string;
23
+ validate?: () => Error | undefined;
24
+ /** aroundEach setup can skip before Vitest enters the attempt hooks. */
25
+ onSetupSkipped?: () => Promise<void>;
26
+ /** Automatic fixtures can resolve before onBeforeTryTask inside aroundEach. */
27
+ beforeFixtures?: () => Promise<void>;
28
+ runnerEntered: boolean;
29
+ readonly evidenceErrors: string[];
30
+ beforeFinish?: (signal: AbortSignal) => Promise<void>;
31
+ onFailure?: (error: unknown, node: TimelineNode, signal: AbortSignal) => Promise<void>;
32
+ readonly runnerErrors: NonNullable<RunSessionResult['runnerErrors']>;
33
+ private readonly failures;
34
+ private progressQueue;
35
+ private journal;
36
+ private progressClosed;
37
+ persistenceIncomplete: boolean;
38
+ private readonly progressController;
39
+ private readonly finalizationScope;
40
+ finalization: FinalizationBudget;
41
+ /** Reserve a small part of the same deadline for writing the terminal result. */
42
+ get persistenceReserveMs(): number;
43
+ get finalizationSignal(): AbortSignal | undefined;
44
+ get runsRoot(): string;
45
+ recordEvidenceIssue(error: unknown): void;
46
+ finalizeStep(stage: string, work: (signal: AbortSignal) => Promise<void>): Promise<void>;
47
+ constructor(session: RunSession, runId: string, testId: string, testName: string, attemptId: string);
48
+ configure(options: {
49
+ runsRoot: string;
50
+ mode: TimelineRunMode;
51
+ logger: FliwrightLogger;
52
+ recordingMode?: RecordingMode;
53
+ testFinalizationBudgetMs?: number;
54
+ }): Promise<void>;
55
+ /** Resolve policy before an endpoint wait can be canceled, without opening an App connection. */
56
+ configureRecordingPolicy(options: {
57
+ recordingMode?: RecordingMode;
58
+ testFinalizationBudgetMs?: number;
59
+ }): void;
60
+ /**
61
+ * Seed a durable running marker before fixture setup can finish. The parent
62
+ * process uses this marker to recover an attempt whose worker disappeared.
63
+ * Configured runs roots are available through the CLI/preset environment;
64
+ * fixture configuration writes the marker again for config-only callers.
65
+ */
66
+ initialize(): Promise<void>;
67
+ private persistRunning;
68
+ private makeArtifactStore;
69
+ private makeRecorder;
70
+ private persistNodeProgress;
71
+ ignorePriorFailures(task: RunnerTask): void;
72
+ captureRunnerFailures(task: RunnerTask, phase: 'setup-or-body' | 'teardown' | 'final'): Promise<void>;
73
+ persist(result: RunSessionResult, finalized?: boolean, budget?: FinalizationBudget): Promise<void>;
74
+ private applyEvidenceIssues;
75
+ private appendJournal;
76
+ }
77
+ export declare function setAttemptContext(task: RunnerTask, context: AttemptContext): void;
78
+ export declare function requireAttemptContext(task: RunnerTask): AttemptContext;
@@ -0,0 +1,301 @@
1
+ import { mkdir, rename, writeFile } from 'node:fs/promises';
2
+ import { dirname, join } from 'node:path';
3
+ import { RunArtifactStore, RunProgressJournal, TimelineArtifactStore, TimelineRecorder, projectRunTrace, resolveFliwrightRunsRoot, mergeFliwrightConfig, readFliwrightEnvironment, } from '@fliwright/core';
4
+ import { FinalizationBudget } from './FinalizationBudget.js';
5
+ import { AsyncLocalStorage } from 'node:async_hooks';
6
+ const attemptKey = Symbol.for('@fliwright/vitest/active-attempt');
7
+ /** Shared by the runner and fixture module, including separate Vitest module graphs. */
8
+ export class AttemptContext {
9
+ session;
10
+ runId;
11
+ testId;
12
+ testName;
13
+ attemptId;
14
+ managedApp;
15
+ androidReadback;
16
+ managedAppDriver;
17
+ cleanupManagedAppDriver;
18
+ devicePreparation;
19
+ recorder;
20
+ artifactStore;
21
+ runStore;
22
+ recordingMode;
23
+ logger;
24
+ failureContextPath;
25
+ validate;
26
+ /** aroundEach setup can skip before Vitest enters the attempt hooks. */
27
+ onSetupSkipped;
28
+ /** Automatic fixtures can resolve before onBeforeTryTask inside aroundEach. */
29
+ beforeFixtures;
30
+ runnerEntered = false;
31
+ evidenceErrors = [];
32
+ beforeFinish;
33
+ onFailure;
34
+ runnerErrors = [];
35
+ failures = new WeakSet();
36
+ progressQueue = Promise.resolve();
37
+ journal;
38
+ progressClosed = false;
39
+ persistenceIncomplete = false;
40
+ progressController = new AbortController();
41
+ finalizationScope = new AsyncLocalStorage();
42
+ finalization;
43
+ /** Reserve a small part of the same deadline for writing the terminal result. */
44
+ get persistenceReserveMs() { return Math.min(250, this.finalization.timeoutMs / 5); }
45
+ get finalizationSignal() { return this.finalizationScope.getStore(); }
46
+ get runsRoot() { return dirname(this.runStore.runDir); }
47
+ recordEvidenceIssue(error) {
48
+ const message = this.session.redactReport(error instanceof Error ? error.message : String(error));
49
+ if (!this.evidenceErrors.includes(message))
50
+ this.evidenceErrors.push(message);
51
+ }
52
+ async finalizeStep(stage, work) {
53
+ try {
54
+ await this.finalization.run(stage, (signal) => this.finalizationScope.run(signal, () => work(signal)), this.persistenceReserveMs);
55
+ }
56
+ catch (error) {
57
+ this.recordEvidenceIssue(error);
58
+ }
59
+ }
60
+ constructor(session, runId, testId, testName, attemptId) {
61
+ this.session = session;
62
+ this.runId = runId;
63
+ this.testId = testId;
64
+ this.testName = testName;
65
+ this.attemptId = attemptId;
66
+ this.finalization = new FinalizationBudget(mergeFliwrightConfig({
67
+ environment: readFliwrightEnvironment(process.env),
68
+ }).recording.testFinalizationBudgetMs);
69
+ this.recordingMode = process.env.FLIWRIGHT_RECORDING_MODE === 'off' ? 'off'
70
+ : process.env.FLIWRIGHT_RECORDING_MODE === 'full' ? 'full' : 'standard';
71
+ this.configureRecordingPolicy({});
72
+ this.runStore = new RunArtifactStore({ runsRoot: resolveFliwrightRunsRoot({ projectRoot: process.env.FLIWRIGHT_PROJECT_ROOT }), runId });
73
+ this.artifactStore = this.makeArtifactStore();
74
+ this.journal = new RunProgressJournal(this.runStore, testId, attemptId);
75
+ this.recorder = this.makeRecorder();
76
+ session.bindRecorder(this.recorder);
77
+ session.configureProgressPersistence((result) => {
78
+ if (this.progressClosed)
79
+ return Promise.resolve();
80
+ // Each snapshot is owned by this attempt; serialize writes from concurrent
81
+ // branches so an older snapshot cannot overwrite a newer one.
82
+ const timeline = this.session.redactReport(this.recorder.toJSON());
83
+ if (this.recordingMode !== 'off')
84
+ result.eventsPath = 'events.jsonl';
85
+ this.progressQueue = this.progressQueue.then(async () => {
86
+ if (this.progressClosed)
87
+ return;
88
+ if (this.recordingMode !== 'off')
89
+ await this.appendJournal(result, timeline);
90
+ if (this.progressClosed)
91
+ return;
92
+ await this.runStore.writeAttemptResult(this.testId, this.attemptId, result, { signal: this.progressController.signal });
93
+ if (this.progressClosed)
94
+ return;
95
+ if (this.recordingMode !== 'off')
96
+ await this.artifactStore.writeTimeline(timeline, { signal: this.progressController.signal });
97
+ }).catch((error) => {
98
+ if (!this.progressController.signal.aborted)
99
+ this.recordEvidenceIssue(error);
100
+ });
101
+ return this.progressQueue;
102
+ });
103
+ }
104
+ async configure(options) {
105
+ await this.recorder.flushProgress();
106
+ await this.progressQueue;
107
+ const store = new RunArtifactStore({ runsRoot: options.runsRoot, runId: this.runId });
108
+ if (store.runDir !== this.runStore.runDir)
109
+ this.journal = new RunProgressJournal(store, this.testId, this.attemptId);
110
+ this.runStore = store;
111
+ this.artifactStore = this.makeArtifactStore();
112
+ this.logger = options.logger;
113
+ this.configureRecordingPolicy(options);
114
+ this.recorder = this.makeRecorder(options.mode);
115
+ this.session.bindRecorder(this.recorder);
116
+ await this.persistRunning();
117
+ }
118
+ /** Resolve policy before an endpoint wait can be canceled, without opening an App connection. */
119
+ configureRecordingPolicy(options) {
120
+ this.recordingMode = options.recordingMode ?? this.recordingMode;
121
+ this.session.configureRecording({ mode: this.recordingMode, captureEvidence: async () => (this.recordingMode === 'off' ? { status: 'disabled' }
122
+ : { status: 'unavailable', error: 'No app evidence source was configured for this attempt.' }) });
123
+ if (options.testFinalizationBudgetMs !== undefined) {
124
+ this.finalization = new FinalizationBudget(options.testFinalizationBudgetMs);
125
+ }
126
+ }
127
+ /**
128
+ * Seed a durable running marker before fixture setup can finish. The parent
129
+ * process uses this marker to recover an attempt whose worker disappeared.
130
+ * Configured runs roots are available through the CLI/preset environment;
131
+ * fixture configuration writes the marker again for config-only callers.
132
+ */
133
+ async initialize() {
134
+ // Fixture policy is not resolved yet. Keep only the recovery marker until
135
+ // configure() decides whether process recording is enabled.
136
+ if (process.env.FLIWRIGHT_RUNS_ROOT) {
137
+ await this.runStore.writeAttemptResult(this.testId, this.attemptId, this.session.snapshot());
138
+ }
139
+ }
140
+ async persistRunning() {
141
+ const result = this.session.snapshot();
142
+ if (this.recordingMode !== 'off')
143
+ result.eventsPath = 'events.jsonl';
144
+ if (this.recordingMode !== 'off')
145
+ await this.appendJournal(result, this.recorder.toJSON());
146
+ await this.runStore.writeAttemptResult(this.testId, this.attemptId, result);
147
+ }
148
+ makeArtifactStore() {
149
+ return new TimelineArtifactStore({ runId: this.runId,
150
+ attemptDir: this.runStore.attemptDir(this.testId, this.attemptId) });
151
+ }
152
+ makeRecorder(mode) {
153
+ return new TimelineRecorder({ runId: this.runId, testName: this.testName, mode, logger: this.logger,
154
+ onChange: (data) => this.persistNodeProgress(data),
155
+ onPersistenceError: (error) => {
156
+ this.evidenceErrors.push(this.session.redactReport(error instanceof Error ? error.message : String(error)));
157
+ },
158
+ });
159
+ }
160
+ async persistNodeProgress(data) {
161
+ if (this.recordingMode === 'off' || this.progressClosed)
162
+ return;
163
+ const result = this.session.snapshot();
164
+ result.eventsPath = 'events.jsonl';
165
+ // Timeline mutations may contain input/error metadata; use the same privacy
166
+ // boundary as RunSession operation snapshots before persisting any node.
167
+ const timeline = this.session.redactReport(data);
168
+ this.progressQueue = this.progressQueue.then(async () => {
169
+ if (!this.progressClosed)
170
+ await this.appendJournal(result, timeline);
171
+ });
172
+ await this.progressQueue;
173
+ }
174
+ ignorePriorFailures(task) {
175
+ for (const error of task.result?.errors ?? [])
176
+ this.failures.add(error);
177
+ }
178
+ async captureRunnerFailures(task, phase) {
179
+ const errors = task.result?.errors ?? [];
180
+ for (let index = 0; index < errors.length; index++) {
181
+ const original = errors[index];
182
+ if (this.failures.has(original))
183
+ continue;
184
+ this.failures.add(original);
185
+ const error = this.session.redactReport(original);
186
+ errors[index] = error;
187
+ this.failures.add(error);
188
+ this.runnerErrors.push({ message: error.message ?? String(error), stack: error.stack, phase });
189
+ const node = this.recorder.startNode('failure', error.message ?? this.testName, { metadata: { phase } });
190
+ this.recorder.failNode(node.id, {
191
+ code: 'unknown', title: this.testName, message: error.message ?? String(error),
192
+ recoveryHints: [{ kind: 'observe', description: 'Inspect the saved failure evidence and runner error.' }],
193
+ cause: error,
194
+ });
195
+ await this.finalizeStep('Failure evidence', async (signal) => {
196
+ await this.recorder.flushProgress();
197
+ if (this.recordingMode !== 'off')
198
+ for (const kind of ['screenshot', 'snapshot', 'diagnostics']) {
199
+ if (signal.aborted)
200
+ return;
201
+ const evidence = await this.session.checkpoint({ kind, reason: 'failure', operationId: node.id });
202
+ if (signal.aborted)
203
+ return;
204
+ this.recorder.addArtifacts(node.id, (evidence.artifactPaths ?? []).map((path) => ({ kind, path, metadata: evidence.artifactMetadata })));
205
+ }
206
+ });
207
+ await this.finalizeStep('Failure projection', async (signal) => { await this.onFailure?.(error, node, signal); });
208
+ await this.finalizeStep('Failure progress flush', () => this.recorder.flushProgress());
209
+ }
210
+ }
211
+ async persist(result, finalized = false, budget = this.finalization) {
212
+ const reserveMs = Math.min(250, budget.timeoutMs / 5);
213
+ let flushed = this.progressClosed;
214
+ try {
215
+ if (!this.progressClosed)
216
+ await budget.run('Progress flush', async () => {
217
+ await this.recorder.flushProgress();
218
+ await this.progressQueue;
219
+ }, reserveMs / 2);
220
+ flushed = true;
221
+ }
222
+ catch (error) {
223
+ this.persistenceIncomplete = true;
224
+ this.recordEvidenceIssue(error);
225
+ }
226
+ // Late evidence and queued progress must not overwrite terminal snapshots.
227
+ this.progressClosed = true;
228
+ this.progressController.abort();
229
+ result.finalized = finalized;
230
+ this.applyEvidenceIssues(result);
231
+ if (this.recordingMode !== 'off')
232
+ try {
233
+ await budget.run('Artifact persistence', async (signal) => {
234
+ result.eventsPath = 'events.jsonl';
235
+ const data = this.session.redactReport(this.recorder.complete(result.testOutcome));
236
+ if (flushed)
237
+ await this.appendJournal(result, data, finalized, signal);
238
+ if (signal.aborted)
239
+ return;
240
+ // A trace references only artifacts already owned by this attempt.
241
+ const traceDir = join(this.artifactStore.runDir, 'trace');
242
+ await mkdir(traceDir, { recursive: true });
243
+ if (signal.aborted)
244
+ return;
245
+ const tracePath = join(traceDir, 'trace.json');
246
+ const temporaryPath = `${tracePath}.${process.pid}.tmp`;
247
+ await writeFile(temporaryPath, JSON.stringify(projectRunTrace(result, data), null, 2), { signal });
248
+ if (signal.aborted)
249
+ return;
250
+ await rename(temporaryPath, tracePath);
251
+ if (signal.aborted)
252
+ return;
253
+ await this.artifactStore.writeTimeline(data, { signal });
254
+ }, reserveMs / 4);
255
+ }
256
+ catch (error) {
257
+ this.persistenceIncomplete = true;
258
+ this.recordEvidenceIssue(error);
259
+ }
260
+ this.applyEvidenceIssues(result);
261
+ try {
262
+ await budget.run('Result persistence', (signal) => this.runStore.writeAttemptResult(this.testId, this.attemptId, result, { signal }));
263
+ }
264
+ catch (error) {
265
+ this.persistenceIncomplete = true;
266
+ this.recordEvidenceIssue(error);
267
+ this.applyEvidenceIssues(result);
268
+ }
269
+ }
270
+ applyEvidenceIssues(result) {
271
+ if (!this.evidenceErrors.length)
272
+ return;
273
+ if (result.evidenceStatus !== 'disabled')
274
+ result.evidenceStatus = 'partial';
275
+ result.evidenceIssues = [...new Set([...(result.evidenceIssues ?? []), ...this.evidenceErrors])];
276
+ }
277
+ async appendJournal(result, timeline, finalized = false, signal = this.progressController.signal) {
278
+ try {
279
+ await this.journal.append(result, timeline, finalized, { signal });
280
+ }
281
+ catch (error) {
282
+ if (signal.aborted)
283
+ return;
284
+ const message = this.session.redactReport(`Progress journal persistence failed: ${error instanceof Error ? error.message : String(error)}`);
285
+ if (!this.evidenceErrors.includes(message))
286
+ this.evidenceErrors.push(message);
287
+ result.evidenceStatus = 'partial';
288
+ result.evidenceIssues = [...new Set([...(result.evidenceIssues ?? []), message])];
289
+ }
290
+ }
291
+ }
292
+ export function setAttemptContext(task, context) {
293
+ // Keep recorder/session internals out of Vitest's task serialization.
294
+ Object.defineProperty(task, attemptKey, { value: context, configurable: true });
295
+ }
296
+ export function requireAttemptContext(task) {
297
+ const context = task[attemptKey];
298
+ if (!context)
299
+ throw new Error('Fliwright fixtures require the Fliwright runner. Configure fliwrightPreset() in vitest.config.ts.');
300
+ return context;
301
+ }
@@ -0,0 +1,15 @@
1
+ /** One time allowance shared by Fliwright-owned teardown stages, excluding project hooks. */
2
+ export declare class FinalizationBudget {
3
+ readonly timeoutMs: number;
4
+ private deadline?;
5
+ private availableMs;
6
+ private active;
7
+ constructor(timeoutMs: number);
8
+ begin(): void;
9
+ pause(): void;
10
+ get remainingMs(): number;
11
+ run<T>(stage: string, work: (signal: AbortSignal) => Promise<T>, reserveMs?: number): Promise<T>;
12
+ }
13
+ export declare class FinalizationTimeoutError extends Error {
14
+ constructor(stage: string, budgetMs: number);
15
+ }
@@ -0,0 +1,57 @@
1
+ /** One time allowance shared by Fliwright-owned teardown stages, excluding project hooks. */
2
+ export class FinalizationBudget {
3
+ timeoutMs;
4
+ deadline;
5
+ availableMs;
6
+ active = 0;
7
+ constructor(timeoutMs) {
8
+ this.timeoutMs = timeoutMs;
9
+ this.availableMs = timeoutMs;
10
+ }
11
+ begin() {
12
+ this.deadline ??= performance.now() + this.availableMs;
13
+ }
14
+ pause() {
15
+ if (this.active !== 0 || this.deadline === undefined)
16
+ return;
17
+ this.availableMs = this.remainingMs;
18
+ this.deadline = undefined;
19
+ }
20
+ get remainingMs() {
21
+ return this.deadline === undefined ? this.availableMs : Math.max(0, this.deadline - performance.now());
22
+ }
23
+ async run(stage, work, reserveMs = 0) {
24
+ this.begin();
25
+ const remaining = this.remainingMs - reserveMs;
26
+ const timeout = new FinalizationTimeoutError(stage, this.timeoutMs);
27
+ if (remaining <= 0) {
28
+ this.pause();
29
+ throw timeout;
30
+ }
31
+ this.active++;
32
+ const controller = new AbortController();
33
+ let timer;
34
+ try {
35
+ return await Promise.race([
36
+ Promise.resolve().then(() => work(controller.signal)),
37
+ new Promise((_, reject) => {
38
+ timer = setTimeout(() => {
39
+ controller.abort(timeout);
40
+ reject(timeout);
41
+ }, Math.ceil(remaining));
42
+ }),
43
+ ]);
44
+ }
45
+ finally {
46
+ clearTimeout(timer);
47
+ this.active--;
48
+ this.pause();
49
+ }
50
+ }
51
+ }
52
+ export class FinalizationTimeoutError extends Error {
53
+ constructor(stage, budgetMs) {
54
+ super(`${stage} exceeded the ${budgetMs}ms test finalization budget.`);
55
+ this.name = 'FinalizationTimeoutError';
56
+ }
57
+ }
@@ -0,0 +1,6 @@
1
+ import type { Reporter } from 'vitest/node';
2
+ /** Parent-side persistence fallback for direct Vitest runs using fliwrightPreset. */
3
+ export declare class FliwrightRecoveryReporter implements Reporter {
4
+ onTestRunEnd(modules: Parameters<NonNullable<Reporter['onTestRunEnd']>>[0]): Promise<void>;
5
+ }
6
+ export default FliwrightRecoveryReporter;
@@ -0,0 +1,15 @@
1
+ import { restoreRunAttempts } from '@fliwright/core';
2
+ /** Parent-side persistence fallback for direct Vitest runs using fliwrightPreset. */
3
+ export class FliwrightRecoveryReporter {
4
+ async onTestRunEnd(modules) {
5
+ for (const module of modules)
6
+ for (const test of module.children.allTests()) {
7
+ const meta = test.meta();
8
+ const attempts = meta.fliwrightRecovery;
9
+ for (const attempt of attempts ?? []) {
10
+ await restoreRunAttempts([attempt], attempt.result.runId, attempt.runsRoot);
11
+ }
12
+ }
13
+ }
14
+ }
15
+ export default FliwrightRecoveryReporter;
@@ -0,0 +1,12 @@
1
+ import type { EndpointLease } from '@fliwright/core';
2
+ import type { RunnerTask } from 'vitest';
3
+ export declare function setTaskOwnershipErrorHandler(task: RunnerTask, handler: (error: unknown) => Promise<void>): void;
4
+ /** The runner and fixtures may live in separate Vitest module graphs. */
5
+ export declare function getTaskEndpointLease(task: RunnerTask): EndpointLease | undefined;
6
+ export declare function setTaskEndpointLease(task: RunnerTask, lease: EndpointLease): void;
7
+ /** Relaunch replaces endpoint ownership while retaining the task's device lease. */
8
+ export declare function releaseTaskAppEndpoint(task: RunnerTask): Promise<void>;
9
+ /** Runtime skip bypasses the final task hook; both runner and fixture must finish. */
10
+ export declare function resetTaskOwnershipPhases(task: RunnerTask): void;
11
+ export declare function finishTaskEndpointLeasePhase(task: RunnerTask, phase: 'cleanupComplete' | 'skipFinalized', finalize?: () => Promise<void>): Promise<void>;
12
+ export declare function releaseTaskEndpointLease(task: RunnerTask): Promise<void>;
@@ -0,0 +1,65 @@
1
+ import { releaseTaskNativeSession } from './TaskNativeSession.js';
2
+ const leaseKey = Symbol.for('@fliwright/vitest/task-endpoint-lease');
3
+ const releaseErrorKey = Symbol.for('@fliwright/vitest/task-ownership-release-error');
4
+ const phasesKey = Symbol.for('@fliwright/vitest/task-ownership-phases');
5
+ export function setTaskOwnershipErrorHandler(task, handler) {
6
+ task[releaseErrorKey] = handler;
7
+ }
8
+ /** The runner and fixtures may live in separate Vitest module graphs. */
9
+ export function getTaskEndpointLease(task) {
10
+ return task[leaseKey]?.lease;
11
+ }
12
+ export function setTaskEndpointLease(task, lease) {
13
+ task[leaseKey] = { lease };
14
+ }
15
+ /** Relaunch replaces endpoint ownership while retaining the task's device lease. */
16
+ export async function releaseTaskAppEndpoint(task) {
17
+ await getTaskEndpointLease(task)?.release();
18
+ delete task[leaseKey];
19
+ }
20
+ /** Runtime skip bypasses the final task hook; both runner and fixture must finish. */
21
+ export function resetTaskOwnershipPhases(task) {
22
+ task[phasesKey] = {};
23
+ }
24
+ export async function finishTaskEndpointLeasePhase(task, phase, finalize) {
25
+ const state = task[phasesKey];
26
+ // Plain Vitest tasks can use this runner without Fliwright's auto fixture.
27
+ if (!state) {
28
+ if (finalize) {
29
+ await releaseTaskEndpointLease(task);
30
+ await finalize();
31
+ }
32
+ return;
33
+ }
34
+ state[phase] = true;
35
+ if (finalize)
36
+ state.finalize = finalize;
37
+ if (state.cleanupComplete && state.skipFinalized) {
38
+ delete task[phasesKey];
39
+ await releaseTaskEndpointLease(task);
40
+ await state.finalize?.();
41
+ }
42
+ }
43
+ export async function releaseTaskEndpointLease(task) {
44
+ const lease = getTaskEndpointLease(task);
45
+ const errors = [];
46
+ try {
47
+ await lease?.release();
48
+ }
49
+ catch (error) {
50
+ errors.push(error);
51
+ }
52
+ delete task[leaseKey];
53
+ try {
54
+ await releaseTaskNativeSession(task);
55
+ }
56
+ catch (error) {
57
+ errors.push(...(error instanceof AggregateError ? error.errors : [error]));
58
+ }
59
+ for (const error of errors) {
60
+ const handler = task[releaseErrorKey];
61
+ if (!handler)
62
+ throw error;
63
+ await handler(error);
64
+ }
65
+ }
@@ -0,0 +1,5 @@
1
+ import { type ScenarioExecutionMode, type TestScenario } from '@fliwright/core';
2
+ import type { RunnerTestCase } from 'vitest';
3
+ export declare function blockTaskManagedApp(task: RunnerTestCase): void;
4
+ /** Runs before the attempt's Adapter, endpoint acquisition and all Bridge work. */
5
+ export declare function prepareTaskManagedApp(task: RunnerTestCase, scenario: TestScenario | undefined, mode: ScenarioExecutionMode | undefined, signal: AbortSignal, nativeEnabled?: boolean): Promise<void>;
@@ -0,0 +1,26 @@
1
+ import { fingerprintScenario, prepareManagedAppAttempt, readManagedAppControl, ScenarioPreparationError } from '@fliwright/core';
2
+ import { requireAttemptContext } from './AttemptContext.js';
3
+ import { disposeTaskNativeAttempt } from './TaskNativeSession.js';
4
+ import { releaseTaskAppEndpoint } from './TaskEndpointLease.js';
5
+ const dirtyKey = Symbol.for('@fliwright/vitest/managed-app-cleanup-unconfirmed');
6
+ export function blockTaskManagedApp(task) { task[dirtyKey] = true; }
7
+ /** Runs before the attempt's Adapter, endpoint acquisition and all Bridge work. */
8
+ export async function prepareTaskManagedApp(task, scenario, mode, signal, nativeEnabled = false) {
9
+ if (mode !== 'managed-start' || !nativeEnabled)
10
+ return;
11
+ if (task[dirtyKey])
12
+ throw new ScenarioPreparationError('The previous managed app connection cleanup was not confirmed; a new managed run is required.');
13
+ const attempt = requireAttemptContext(task);
14
+ if (attempt.managedApp)
15
+ return;
16
+ const control = readManagedAppControl();
17
+ if (!control)
18
+ throw new ScenarioPreparationError('Managed device scenarios require a live app supervisor. Use managed CLI run/script or a Cloud Worker.');
19
+ signal.throwIfAborted();
20
+ await disposeTaskNativeAttempt(task);
21
+ await releaseTaskAppEndpoint(task);
22
+ attempt.managedApp = await prepareManagedAppAttempt(control, {
23
+ attemptKey: `${attempt.runId}/${task.id}/${attempt.attemptId}`,
24
+ ...(scenario ? { scenarioName: scenario.name, scenarioFingerprint: fingerprintScenario(scenario) } : {}),
25
+ }, { signal });
26
+ }
@@ -0,0 +1,17 @@
1
+ import { type NativeConfig, type NativeRuntime, type RunSession, type TestScenario } from '@fliwright/core';
2
+ import { type NativeDeviceSession } from '@fliwright/native';
3
+ import type { RunnerTask, RunnerTestCase } from 'vitest';
4
+ export type NativeDeviceProvider = (config: NativeConfig, options: {
5
+ signal: AbortSignal;
6
+ }) => Promise<NativeDeviceSession>;
7
+ export declare function hasTaskNativeRuntime(task: RunnerTask): boolean;
8
+ /** Called before acquiring the endpoint so separate VM URLs cannot bypass device exclusion. */
9
+ export declare function prepareTaskNativeSession(task: RunnerTask, config: NativeConfig | undefined, signal: AbortSignal, provider?: NativeDeviceProvider): Promise<void>;
10
+ export declare function quarantineTaskNativeSession(task: RunnerTask): Promise<void>;
11
+ export declare function taskNativeRuntime(task: RunnerTestCase, session: RunSession, attemptId: string): Promise<NativeRuntime>;
12
+ export declare function verifyTaskNativeBinding(task: RunnerTestCase, driver: {
13
+ sendRequest(method: string): Promise<unknown>;
14
+ }, attemptId: string, scenario?: TestScenario): Promise<void>;
15
+ export declare function disposeTaskNativeAttempt(task: RunnerTask): Promise<void>;
16
+ /** Release last, after endpoint ownership and all attempt evidence have finished. */
17
+ export declare function releaseTaskNativeSession(task: RunnerTask): Promise<void>;