@fliwright/tdd 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.
Files changed (47) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +7 -2
  3. package/dist/baseline/AppCapabilityResetAdapter.d.ts +6 -0
  4. package/dist/baseline/AppCapabilityResetAdapter.js +41 -0
  5. package/dist/baseline/BaselineManager.d.ts +67 -0
  6. package/dist/baseline/BaselineManager.js +145 -0
  7. package/dist/baseline/StorageResetAdapter.d.ts +19 -0
  8. package/dist/baseline/StorageResetAdapter.js +43 -0
  9. package/dist/daemon/DaemonTransport.d.ts +37 -0
  10. package/dist/daemon/DaemonTransport.js +1 -0
  11. package/dist/daemon/FlutterDaemonController.d.ts +19 -0
  12. package/dist/daemon/FlutterDaemonController.js +109 -0
  13. package/dist/daemon/FlutterDaemonEndpointSource.d.ts +23 -0
  14. package/dist/daemon/FlutterDaemonEndpointSource.js +37 -0
  15. package/dist/daemon/ReloadStrategy.d.ts +28 -0
  16. package/dist/daemon/ReloadStrategy.js +72 -0
  17. package/dist/daemon/SubprocessDaemonTransport.d.ts +29 -0
  18. package/dist/daemon/SubprocessDaemonTransport.js +155 -0
  19. package/dist/devassist/DevAssistCoordinator.d.ts +74 -0
  20. package/dist/devassist/DevAssistCoordinator.js +388 -0
  21. package/dist/diagnostics/TddFailureContext.d.ts +56 -0
  22. package/dist/diagnostics/TddFailureContext.js +220 -0
  23. package/dist/executor/FocusedRerunRecipe.d.ts +7 -0
  24. package/dist/executor/FocusedRerunRecipe.js +57 -0
  25. package/dist/executor/PersistentTestExecutor.d.ts +59 -0
  26. package/dist/executor/PersistentTestExecutor.js +242 -0
  27. package/dist/executor/ResultReporter.d.ts +23 -0
  28. package/dist/executor/ResultReporter.js +50 -0
  29. package/dist/generator/RedFirstTestGenerator.d.ts +32 -0
  30. package/dist/generator/RedFirstTestGenerator.js +189 -0
  31. package/dist/index.d.ts +36 -0
  32. package/dist/index.js +20 -0
  33. package/dist/repair/TddRepairPlanner.d.ts +54 -0
  34. package/dist/repair/TddRepairPlanner.js +132 -0
  35. package/dist/runtime/TddRuntime.d.ts +87 -0
  36. package/dist/runtime/TddRuntime.js +589 -0
  37. package/dist/selectors/SelectorSynthesizer.d.ts +34 -0
  38. package/dist/selectors/SelectorSynthesizer.js +174 -0
  39. package/dist/spec/InteractionSpec.d.ts +94 -0
  40. package/dist/spec/InteractionSpec.js +236 -0
  41. package/dist/spec/InteractionSpecCoverage.d.ts +17 -0
  42. package/dist/spec/InteractionSpecCoverage.js +69 -0
  43. package/dist/types.d.ts +314 -0
  44. package/dist/types.js +2 -0
  45. package/dist/workflow/RedFirstWorkflow.d.ts +28 -0
  46. package/dist/workflow/RedFirstWorkflow.js +33 -0
  47. package/package.json +42 -3
@@ -0,0 +1,57 @@
1
+ import { stat } from 'node:fs/promises';
2
+ import { relative, resolve, sep } from 'node:path';
3
+ /**
4
+ * Encodes the Vitest 5 focused rerun recipe for the persistent TDD executor.
5
+ * Vitest 5 replaces changeNamePattern/changeFilenamePattern with specification-scoped
6
+ * filters plus rerunTestSpecifications.
7
+ */
8
+ export async function focusAndRerun(vitest, file, testName) {
9
+ const specifications = await resolveSpecifications(vitest, file);
10
+ if (specifications.length === 0) {
11
+ throw new Error(`No Vitest specifications found for ${file}`);
12
+ }
13
+ const savedPatterns = specifications.map((spec) => spec.testNamePattern);
14
+ try {
15
+ if (testName) {
16
+ const pattern = new RegExp(testName);
17
+ for (const spec of specifications)
18
+ spec.testNamePattern = pattern;
19
+ }
20
+ return await vitest.rerunTestSpecifications(specifications);
21
+ }
22
+ finally {
23
+ specifications.forEach((spec, index) => {
24
+ spec.testNamePattern = savedPatterns[index];
25
+ });
26
+ }
27
+ }
28
+ async function resolveSpecifications(vitest, file) {
29
+ let specifications = vitest.getModuleSpecifications(file);
30
+ if (specifications.length > 0)
31
+ return specifications;
32
+ specifications = (await vitest.globTestSpecifications([file])).filter((spec) => spec.moduleId === file);
33
+ if (specifications.length > 0)
34
+ return specifications;
35
+ const candidate = resolve(file);
36
+ if (!(await isFile(candidate)))
37
+ return [];
38
+ // When a persistent watcher has cleared its module cache between reruns,
39
+ // create a specification directly for the exact file. Generated candidates
40
+ // are deliberately excluded from normal project discovery, and ordinary
41
+ // files use this only as a race-safe fallback.
42
+ return vitest.projects
43
+ .filter((project) => isWithinProject(project.config.root, candidate))
44
+ .map((project) => project.createSpecification(candidate));
45
+ }
46
+ function isWithinProject(root, file) {
47
+ const path = relative(root, file);
48
+ return path !== '' && !path.startsWith(`..${sep}`) && path !== '..' && !path.startsWith(sep);
49
+ }
50
+ async function isFile(path) {
51
+ try {
52
+ return (await stat(path)).isFile();
53
+ }
54
+ catch {
55
+ return false;
56
+ }
57
+ }
@@ -0,0 +1,59 @@
1
+ import type { TddFailureArtifacts, TddFailureAssertion, TddFailureSource } from '../diagnostics/TddFailureContext.js';
2
+ export interface TestRunOutcome {
3
+ status: 'red' | 'green';
4
+ testName?: string;
5
+ failure?: {
6
+ message?: string;
7
+ };
8
+ failureDetails?: TddFailureDetails;
9
+ timelinePath?: string;
10
+ timelineNodeId?: string;
11
+ }
12
+ export interface BootOptions {
13
+ configRoot: string;
14
+ vmServiceUrl?: string;
15
+ driverProvider: () => Promise<unknown>;
16
+ runsRoot?: string;
17
+ sharedConfig?: Partial<import('@fliwright/core').FliwrightProjectConfig>;
18
+ defaultScenario?: string;
19
+ scenarioMode?: 'managed-start' | 'attach';
20
+ }
21
+ export declare class PersistentTestExecutor {
22
+ private vitest?;
23
+ private reporter?;
24
+ private previousDefaultScenario?;
25
+ private previousScenarioMode?;
26
+ private previousVmServiceUrl?;
27
+ private previousVmUrl?;
28
+ private previousTddMode?;
29
+ private previousScreenshotMode?;
30
+ private previousFailureTimeoutMs?;
31
+ private previousRunsRoot?;
32
+ private previousRunId?;
33
+ private previousSharedConfig?;
34
+ private previousProjectRoot?;
35
+ private runsRoot?;
36
+ private envApplied;
37
+ boot(opts: BootOptions): Promise<void>;
38
+ rerun(file: string, testName?: string): Promise<TestRunOutcome>;
39
+ dispose(): Promise<void>;
40
+ private pickResult;
41
+ private restoreRuntimeEnv;
42
+ private applyRuntimeEnv;
43
+ private snapshotPreviousEnv;
44
+ private attemptDirectory;
45
+ private readFailureDetails;
46
+ private readTimelineArtifacts;
47
+ }
48
+ export declare function defaultArtifactsRoot(configRoot: string): string;
49
+ /**
50
+ * Default RuntimeSnapshot status-file path a read-only monitor (e.g. the VS Code TDD Loop panel)
51
+ * polls: `<projectRoot>/.fliwright/tdd-status.json`. The project root is derived from the same
52
+ * configRoot convention as {@link defaultArtifactsRoot}.
53
+ */
54
+ export declare function defaultStatusFilePath(configRoot: string): string;
55
+ export interface TddFailureDetails {
56
+ assertion?: TddFailureAssertion;
57
+ source?: TddFailureSource;
58
+ artifacts?: TddFailureArtifacts;
59
+ }
@@ -0,0 +1,242 @@
1
+ import { mkdir, readFile } from 'node:fs/promises';
2
+ import { basename, join, resolve } from 'node:path';
3
+ import { FLIWRIGHT_RUNS_ROOT_ENV, RunArtifactStore, parseTimelineData, resolveFliwrightRunsRoot, resolveFliwrightCacheRoot, mergeFliwrightConfig, readFliwrightEnvironment } from '@fliwright/core';
4
+ import { fileURLToPath } from 'node:url';
5
+ import { startVitest } from 'vitest/node';
6
+ import { focusAndRerun } from './FocusedRerunRecipe.js';
7
+ import { collectResultsFromModules, ResultReporter } from './ResultReporter.js';
8
+ export class PersistentTestExecutor {
9
+ vitest;
10
+ reporter;
11
+ previousDefaultScenario;
12
+ previousScenarioMode;
13
+ previousVmServiceUrl;
14
+ previousVmUrl;
15
+ previousTddMode;
16
+ previousScreenshotMode;
17
+ previousFailureTimeoutMs;
18
+ previousRunsRoot;
19
+ previousRunId;
20
+ previousSharedConfig;
21
+ previousProjectRoot;
22
+ runsRoot;
23
+ envApplied = false;
24
+ async boot(opts) {
25
+ if (this.vitest)
26
+ return;
27
+ // Apply env first; if anything after it throws, restore it so the CLI connection worker is not
28
+ // left with TDD env vars leaking into unrelated (batch) test runs.
29
+ await this.applyRuntimeEnv(opts);
30
+ try {
31
+ this.reporter = new ResultReporter();
32
+ this.vitest = await startVitest('test', [], {
33
+ config: opts.configRoot,
34
+ watch: true,
35
+ standalone: true,
36
+ reporters: [this.reporter],
37
+ pool: 'forks',
38
+ maxWorkers: 1,
39
+ }, {
40
+ // macOS FSEvents can deliver a config write from before boot after a
41
+ // focused run starts, causing Vite to close its active module cache.
42
+ ...(process.platform === 'darwin' ? { server: { watch: { usePolling: true } } } : {}),
43
+ plugins: [{ name: 'fliwright-runner', config(config) {
44
+ const runtimeConfig = config;
45
+ (runtimeConfig.test ??= {}).runner ??= fileURLToPath(import.meta.resolve('@fliwright/vitest/runner'));
46
+ } }]
47
+ });
48
+ if (!this.vitest)
49
+ throw new Error('Failed to start Vitest');
50
+ // A directly used executor can receive storage through the project's
51
+ // Vitest preset. Resolve the same root the worker actually receives.
52
+ const workerRoot = this.vitest.projects[0]?.config.env?.FLIWRIGHT_RUNS_ROOT;
53
+ if (workerRoot)
54
+ this.runsRoot = resolve(String(workerRoot));
55
+ await mkdir(this.runsRoot, { recursive: true });
56
+ }
57
+ catch (error) {
58
+ await this.dispose().catch(() => undefined);
59
+ throw error;
60
+ }
61
+ // The provider is kept for same-process executor experiments. Vitest workers cannot
62
+ // receive live driver objects through process boundaries, so the production path also injects
63
+ // FLIWRIGHT_VM_SERVICE_URL for ordinary @fliwright/vitest fixtures.
64
+ void opts.driverProvider;
65
+ }
66
+ async rerun(file, testName) {
67
+ if (!this.vitest || !this.reporter)
68
+ throw new Error('PersistentTestExecutor not booted');
69
+ this.reporter.drain();
70
+ // The public API returns the exact run we requested. A reporter's next
71
+ // event may instead belong to a watcher refresh (or contain no modules).
72
+ const run = await focusAndRerun(this.vitest, file, testName);
73
+ const files = run.testModules;
74
+ const results = collectResultsFromModules(files);
75
+ const picked = this.pickResult(results, testName);
76
+ const resolvedTestName = picked?.testName ?? testName;
77
+ const timelineArtifacts = await this.readTimelineArtifacts(picked);
78
+ const failureDetails = picked?.status === 'red' && resolvedTestName
79
+ ? await this.readFailureDetails(picked)
80
+ : undefined;
81
+ return {
82
+ status: picked?.status ?? 'red',
83
+ testName: resolvedTestName,
84
+ failure: picked?.status === 'red' ? { message: picked.message }
85
+ : !picked ? { message: run.unhandledErrors.map((error) => {
86
+ if (error && typeof error === 'object' && 'message' in error)
87
+ return String(error.message);
88
+ return JSON.stringify(error);
89
+ }).join('\n') || 'Focused run returned no matching test result.' } : undefined,
90
+ failureDetails,
91
+ timelinePath: failureDetails?.artifacts?.timelinePath ?? timelineArtifacts.timelinePath,
92
+ timelineNodeId: failureDetails?.artifacts?.timelineNodeId ?? timelineArtifacts.timelineNodeId,
93
+ };
94
+ }
95
+ async dispose() {
96
+ try {
97
+ await this.vitest?.close();
98
+ }
99
+ finally {
100
+ this.vitest = undefined;
101
+ this.reporter = undefined;
102
+ if (this.envApplied)
103
+ this.restoreRuntimeEnv();
104
+ }
105
+ }
106
+ pickResult(results, testName) {
107
+ if (!testName)
108
+ return results.find((result) => result.status === 'red') ?? results[0];
109
+ return results.find((result) => result.testName === testName)
110
+ ?? results.find((result) => result.testName.includes(testName));
111
+ }
112
+ restoreRuntimeEnv() {
113
+ restoreEnv('FLIWRIGHT_SCENARIO_MODE', this.previousScenarioMode);
114
+ restoreEnv('FLIWRIGHT_DEFAULT_SCENARIO', this.previousDefaultScenario);
115
+ restoreEnv('FLIWRIGHT_VM_SERVICE_URL', this.previousVmServiceUrl);
116
+ restoreEnv('FLIWRIGHT_VM_URL', this.previousVmUrl);
117
+ restoreEnv('FLIWRIGHT_TDD_MODE', this.previousTddMode);
118
+ restoreEnv('FLIWRIGHT_SCREENSHOT_MODE', this.previousScreenshotMode);
119
+ restoreEnv('FLIWRIGHT_FAILURE_TIMEOUT_MS', this.previousFailureTimeoutMs);
120
+ restoreEnv(FLIWRIGHT_RUNS_ROOT_ENV, this.previousRunsRoot);
121
+ restoreEnv('FLIWRIGHT_RUN_ID', this.previousRunId);
122
+ restoreEnv('FLIWRIGHT_CONFIG', this.previousSharedConfig);
123
+ restoreEnv('FLIWRIGHT_PROJECT_ROOT', this.previousProjectRoot);
124
+ this.envApplied = false;
125
+ }
126
+ async applyRuntimeEnv(opts) {
127
+ this.snapshotPreviousEnv();
128
+ try {
129
+ process.env.FLIWRIGHT_TDD_MODE = '1';
130
+ process.env.FLIWRIGHT_SCENARIO_MODE = opts.scenarioMode ?? 'attach';
131
+ if (opts.defaultScenario)
132
+ process.env.FLIWRIGHT_DEFAULT_SCENARIO = opts.defaultScenario;
133
+ if (opts.vmServiceUrl) {
134
+ process.env.FLIWRIGHT_VM_SERVICE_URL = opts.vmServiceUrl;
135
+ process.env.FLIWRIGHT_VM_URL = opts.vmServiceUrl;
136
+ }
137
+ const projectRoot = looksLikeConfigFile(opts.configRoot) ? resolve(opts.configRoot, '..') : resolve(opts.configRoot);
138
+ const config = mergeFliwrightConfig({ project: opts.sharedConfig, environment: readFliwrightEnvironment(process.env), explicit: { runsRoot: opts.runsRoot } });
139
+ this.runsRoot = resolveFliwrightRunsRoot({ projectRoot, runsRoot: config.runsRoot, env: {} });
140
+ await mkdir(this.runsRoot, { recursive: true });
141
+ if (opts.sharedConfig) {
142
+ config.cacheRoot = resolveFliwrightCacheRoot({ projectRoot, cacheRoot: config.cacheRoot });
143
+ config.runsRoot = this.runsRoot;
144
+ process.env.FLIWRIGHT_CONFIG = JSON.stringify(config);
145
+ }
146
+ process.env.FLIWRIGHT_PROJECT_ROOT = projectRoot;
147
+ if (config.runsRoot)
148
+ process.env[FLIWRIGHT_RUNS_ROOT_ENV] = this.runsRoot;
149
+ process.env.FLIWRIGHT_SCREENSHOT_MODE = process.env.FLIWRIGHT_SCREENSHOT_MODE ?? 'base64';
150
+ process.env.FLIWRIGHT_FAILURE_TIMEOUT_MS = process.env.FLIWRIGHT_FAILURE_TIMEOUT_MS ?? '5000';
151
+ this.envApplied = true;
152
+ }
153
+ catch (error) {
154
+ // mkdir/writeFile can throw; restore anything we already wrote so we never leak partial env.
155
+ this.restoreRuntimeEnv();
156
+ throw error;
157
+ }
158
+ }
159
+ snapshotPreviousEnv() {
160
+ this.previousScenarioMode = process.env.FLIWRIGHT_SCENARIO_MODE;
161
+ this.previousDefaultScenario = process.env.FLIWRIGHT_DEFAULT_SCENARIO;
162
+ this.previousVmServiceUrl = process.env.FLIWRIGHT_VM_SERVICE_URL;
163
+ this.previousVmUrl = process.env.FLIWRIGHT_VM_URL;
164
+ this.previousTddMode = process.env.FLIWRIGHT_TDD_MODE;
165
+ this.previousScreenshotMode = process.env.FLIWRIGHT_SCREENSHOT_MODE;
166
+ this.previousFailureTimeoutMs = process.env.FLIWRIGHT_FAILURE_TIMEOUT_MS;
167
+ this.previousRunsRoot = process.env[FLIWRIGHT_RUNS_ROOT_ENV];
168
+ this.previousRunId = process.env.FLIWRIGHT_RUN_ID;
169
+ this.previousSharedConfig = process.env.FLIWRIGHT_CONFIG;
170
+ this.previousProjectRoot = process.env.FLIWRIGHT_PROJECT_ROOT;
171
+ }
172
+ attemptDirectory(result) {
173
+ const identity = result?.runIdentity;
174
+ if (!this.runsRoot || !identity)
175
+ return undefined;
176
+ return new RunArtifactStore({ runsRoot: this.runsRoot, runId: identity.runId })
177
+ .attemptDir(identity.testId, identity.attemptId);
178
+ }
179
+ async readFailureDetails(result) {
180
+ const directory = this.attemptDirectory(result);
181
+ if (!directory)
182
+ return undefined;
183
+ try {
184
+ const attempt = JSON.parse(await readFile(join(directory, 'result.json'), 'utf8'));
185
+ if (!attempt.failureContextPath)
186
+ return undefined;
187
+ const failureContextPath = join(directory, attempt.failureContextPath);
188
+ const entries = JSON.parse(await readFile(failureContextPath, 'utf8'));
189
+ const entry = entries.filter((candidate) => candidate.testName === result?.testName).at(-1);
190
+ if (!entry)
191
+ return undefined;
192
+ const screenshotBase64 = entry.screenshot?.path
193
+ ? (await readFile(join(directory, entry.screenshot.path))).toString('base64') : undefined;
194
+ return {
195
+ assertion: entry.assertion, source: entry.source,
196
+ artifacts: { failureContextPath, screenshotBase64, widgetTree: entry.widgetTree,
197
+ ...await this.readTimelineArtifacts(result) },
198
+ };
199
+ }
200
+ catch {
201
+ return undefined;
202
+ }
203
+ }
204
+ async readTimelineArtifacts(result) {
205
+ const directory = this.attemptDirectory(result);
206
+ if (!directory)
207
+ return {};
208
+ try {
209
+ const timelinePath = join(directory, 'timeline.json');
210
+ const timeline = parseTimelineData(await readFile(timelinePath, 'utf8'));
211
+ if (!timeline)
212
+ return {};
213
+ return { timelinePath, timelineNodeId: timeline.agentVisibleFailures?.[0]?.timelineNodeId };
214
+ }
215
+ catch {
216
+ return {};
217
+ }
218
+ }
219
+ }
220
+ function restoreEnv(name, value) {
221
+ if (value === undefined)
222
+ delete process.env[name];
223
+ else
224
+ process.env[name] = value;
225
+ }
226
+ export function defaultArtifactsRoot(configRoot) {
227
+ const root = looksLikeConfigFile(configRoot) ? resolve(configRoot, '..') : resolve(configRoot);
228
+ return join(root, '.fliwright', 'runs');
229
+ }
230
+ /**
231
+ * Default RuntimeSnapshot status-file path a read-only monitor (e.g. the VS Code TDD Loop panel)
232
+ * polls: `<projectRoot>/.fliwright/tdd-status.json`. The project root is derived from the same
233
+ * configRoot convention as {@link defaultArtifactsRoot}.
234
+ */
235
+ export function defaultStatusFilePath(configRoot) {
236
+ const root = looksLikeConfigFile(configRoot) ? resolve(configRoot, '..') : resolve(configRoot);
237
+ return join(root, '.fliwright', 'tdd-status.json');
238
+ }
239
+ function looksLikeConfigFile(configRoot) {
240
+ const name = basename(configRoot);
241
+ return /\.[cm]?[jt]s$/.test(name);
242
+ }
@@ -0,0 +1,23 @@
1
+ import type { Reporter, TestModule } from 'vitest/node';
2
+ export interface CollectedResult {
3
+ testName: string;
4
+ status: 'red' | 'green';
5
+ message?: string;
6
+ runIdentity?: {
7
+ runId: string;
8
+ testId: string;
9
+ attemptId: string;
10
+ };
11
+ }
12
+ export declare class ResultReporter implements Reporter {
13
+ private readonly finishedRuns;
14
+ private waiters;
15
+ /** Vitest 5 reports finished runs via onTestRunEnd instead of onFinished. */
16
+ onTestRunEnd(testModules: ReadonlyArray<TestModule>): void;
17
+ waitForNextRun(): Promise<TestModule[]>;
18
+ collectLatest(): CollectedResult[];
19
+ drain(): void;
20
+ }
21
+ export declare function collectResultsFromModules(modules: TestModule[]): CollectedResult[];
22
+ /** @deprecated Use {@link collectResultsFromModules}; kept for existing imports. */
23
+ export declare const collectResultsFromFiles: typeof collectResultsFromModules;
@@ -0,0 +1,50 @@
1
+ export class ResultReporter {
2
+ finishedRuns = [];
3
+ waiters = [];
4
+ /** Vitest 5 reports finished runs via onTestRunEnd instead of onFinished. */
5
+ onTestRunEnd(testModules) {
6
+ const modules = [...testModules];
7
+ // Vitest can emit an intermediate empty run while a persistent watcher
8
+ // refreshes its module specifications. It is not a completed focused run
9
+ // and must not resolve a rerun waiter with stale results.
10
+ if (modules.length === 0)
11
+ return;
12
+ this.finishedRuns.push(modules);
13
+ const waiters = this.waiters;
14
+ this.waiters = [];
15
+ for (const waiter of waiters)
16
+ waiter(modules);
17
+ }
18
+ waitForNextRun() {
19
+ return new Promise((resolve) => {
20
+ this.waiters.push(resolve);
21
+ });
22
+ }
23
+ collectLatest() {
24
+ const modules = this.finishedRuns.at(-1) ?? [];
25
+ return collectResultsFromModules(modules);
26
+ }
27
+ drain() {
28
+ this.finishedRuns.length = 0;
29
+ }
30
+ }
31
+ export function collectResultsFromModules(modules) {
32
+ const results = [];
33
+ for (const module of modules) {
34
+ for (const testCase of module.children.allTests()) {
35
+ const result = testCase.result();
36
+ if (result.state !== 'passed' && result.state !== 'failed')
37
+ continue;
38
+ const identity = testCase.meta().fliwrightRun;
39
+ results.push({
40
+ ...(identity ? { runIdentity: identity } : {}),
41
+ testName: testCase.name,
42
+ status: result.state === 'passed' ? 'green' : 'red',
43
+ message: result.errors?.map((error) => error.message).join('\n'),
44
+ });
45
+ }
46
+ }
47
+ return results;
48
+ }
49
+ /** @deprecated Use {@link collectResultsFromModules}; kept for existing imports. */
50
+ export const collectResultsFromFiles = collectResultsFromModules;
@@ -0,0 +1,32 @@
1
+ import type { InteractionSpec } from '../spec/InteractionSpec.js';
2
+ import type { SelectorSynthesisResult, WidgetCandidate } from '../selectors/SelectorSynthesizer.js';
3
+ export interface RedFirstTestGeneratorOptions {
4
+ flowId?: string;
5
+ testName?: string;
6
+ homeRoute?: string;
7
+ resetToHomeBeforeEach?: boolean;
8
+ widgets?: WidgetCandidate[];
9
+ }
10
+ export interface RedFirstTestSuiteGeneratorOptions extends Omit<RedFirstTestGeneratorOptions, 'flowId' | 'testName'> {
11
+ flowIds?: string[];
12
+ testNamePrefix?: string;
13
+ }
14
+ export interface GenerateRedFirstTestResult {
15
+ testCode: string;
16
+ testName: string;
17
+ flowId?: string;
18
+ warnings: string[];
19
+ selectorDiagnostics: SelectorSynthesisResult[];
20
+ }
21
+ export interface GenerateRedFirstTestSuiteResult {
22
+ testCode: string;
23
+ tests: Array<{
24
+ testName: string;
25
+ flowId?: string;
26
+ warnings: string[];
27
+ }>;
28
+ warnings: string[];
29
+ selectorDiagnostics: SelectorSynthesisResult[];
30
+ }
31
+ export declare function generateRedFirstTest(spec: InteractionSpec, options?: RedFirstTestGeneratorOptions): GenerateRedFirstTestResult;
32
+ export declare function generateRedFirstTestSuite(spec: InteractionSpec, options?: RedFirstTestSuiteGeneratorOptions): GenerateRedFirstTestSuiteResult;
@@ -0,0 +1,189 @@
1
+ import { parseInteractionSpec } from '../spec/InteractionSpec.js';
2
+ import { bestLocatorHint, synthesizeSelectorsForElements } from '../selectors/SelectorSynthesizer.js';
3
+ export function generateRedFirstTest(spec, options = {}) {
4
+ spec = parseInteractionSpec(spec);
5
+ const warnings = [];
6
+ const flow = selectFlow(spec, options.flowId);
7
+ if (!flow)
8
+ throw new Error('InteractionSpec must include at least one flow.');
9
+ const elements = new Map(spec.elements.map((element) => [element.id, element]));
10
+ const testName = options.testName ?? flow.name;
11
+ const resetToHomeBeforeEach = options.resetToHomeBeforeEach ?? true;
12
+ const homeRoute = options.homeRoute ?? spec.initialState?.route ?? spec.app?.route ?? '/';
13
+ const assertions = [...(flow.expectedOutcome ?? []), ...(spec.assertions ?? [])];
14
+ const needsMock = assertions.some((assertion) => assertion.kind === 'mockCalled');
15
+ const widgets = options.widgets ?? [];
16
+ const selectorDiagnostics = synthesizeSelectorsForElements(spec.elements, widgets);
17
+ const lines = [];
18
+ const imports = resetToHomeBeforeEach ? 'test, expect, beforeEach' : 'test, expect';
19
+ lines.push(`import { ${imports} } from '@fliwright/vitest';`);
20
+ lines.push('');
21
+ if (resetToHomeBeforeEach) {
22
+ lines.push('beforeEach(async ({ page }) => {');
23
+ lines.push(` await page.resetToHome({ homeRoute: ${stringLiteral(homeRoute)} });`);
24
+ lines.push('});');
25
+ lines.push('');
26
+ }
27
+ lines.push(`test(${stringLiteral(testName)}, async ({ ${needsMock ? 'page, mock' : 'page'} }) => {`);
28
+ for (const step of flow.steps)
29
+ appendStep(lines, step, elements, widgets, warnings);
30
+ for (const assertion of assertions)
31
+ appendAssertion(lines, assertion, elements, widgets, warnings);
32
+ if (flow.steps.length === 0 && assertions.length === 0) {
33
+ warnings.push(`Flow '${flow.id}' has no steps or assertions.`);
34
+ }
35
+ lines.push('});');
36
+ return {
37
+ testCode: lines.join('\n'),
38
+ testName,
39
+ flowId: flow.id,
40
+ warnings,
41
+ selectorDiagnostics,
42
+ };
43
+ }
44
+ export function generateRedFirstTestSuite(spec, options = {}) {
45
+ spec = parseInteractionSpec(spec);
46
+ const warnings = [];
47
+ const flows = selectFlows(spec, options.flowIds);
48
+ const elements = new Map(spec.elements.map((element) => [element.id, element]));
49
+ const resetToHomeBeforeEach = options.resetToHomeBeforeEach ?? true;
50
+ const homeRoute = options.homeRoute ?? spec.initialState?.route ?? spec.app?.route ?? '/';
51
+ const widgets = options.widgets ?? [];
52
+ const selectorDiagnostics = synthesizeSelectorsForElements(spec.elements, widgets);
53
+ const lines = testFilePreamble({ resetToHomeBeforeEach, homeRoute });
54
+ const tests = [];
55
+ for (const flow of flows) {
56
+ const flowWarnings = [];
57
+ const testName = options.testNamePrefix ? `${options.testNamePrefix}: ${flow.name}` : flow.name;
58
+ appendTest(lines, flow, testName, elements, spec.assertions ?? [], widgets, flowWarnings);
59
+ tests.push({ testName, flowId: flow.id, warnings: flowWarnings });
60
+ warnings.push(...flowWarnings.map((warning) => `[${flow.id}] ${warning}`));
61
+ }
62
+ return {
63
+ testCode: lines.join('\n'),
64
+ tests,
65
+ warnings,
66
+ selectorDiagnostics,
67
+ };
68
+ }
69
+ function selectFlow(spec, flowId) {
70
+ if (!flowId)
71
+ return spec.flows[0];
72
+ const flow = spec.flows.find((candidate) => candidate.id === flowId);
73
+ if (!flow)
74
+ throw new Error(`Flow '${flowId}' was not found in InteractionSpec.flows.`);
75
+ return flow;
76
+ }
77
+ function selectFlows(spec, flowIds) {
78
+ if (!flowIds?.length)
79
+ return spec.flows;
80
+ const flows = flowIds.map((flowId) => {
81
+ const flow = spec.flows.find((candidate) => candidate.id === flowId);
82
+ if (!flow)
83
+ throw new Error(`Flow '${flowId}' was not found in InteractionSpec.flows.`);
84
+ return flow;
85
+ });
86
+ return flows;
87
+ }
88
+ function testFilePreamble(opts) {
89
+ const lines = [];
90
+ const imports = opts.resetToHomeBeforeEach ? 'test, expect, beforeEach' : 'test, expect';
91
+ lines.push(`import { ${imports} } from '@fliwright/vitest';`);
92
+ lines.push('');
93
+ if (opts.resetToHomeBeforeEach) {
94
+ lines.push('beforeEach(async ({ page }) => {');
95
+ lines.push(` await page.resetToHome({ homeRoute: ${stringLiteral(opts.homeRoute)} });`);
96
+ lines.push('});');
97
+ lines.push('');
98
+ }
99
+ return lines;
100
+ }
101
+ function appendTest(lines, flow, testName, elements, globalAssertions, widgets, warnings) {
102
+ const assertions = [...(flow.expectedOutcome ?? []), ...globalAssertions];
103
+ const needsMock = assertions.some((assertion) => assertion.kind === 'mockCalled');
104
+ lines.push(`test(${stringLiteral(testName)}, async ({ ${needsMock ? 'page, mock' : 'page'} }) => {`);
105
+ for (const step of flow.steps)
106
+ appendStep(lines, step, elements, widgets, warnings);
107
+ for (const assertion of assertions)
108
+ appendAssertion(lines, assertion, elements, widgets, warnings);
109
+ if (flow.steps.length === 0 && assertions.length === 0) {
110
+ warnings.push(`Flow '${flow.id}' has no steps or assertions.`);
111
+ }
112
+ lines.push('});');
113
+ lines.push('');
114
+ }
115
+ function appendStep(lines, step, elements, widgets, warnings) {
116
+ const element = elements.get(step.target);
117
+ if (!element) {
118
+ warnings.push(`Step target '${step.target}' was not found in spec.elements.`);
119
+ return;
120
+ }
121
+ const locator = locatorExpression(element, widgets);
122
+ if (step.action === 'tap') {
123
+ lines.push(` await ${locator}.click();`);
124
+ return;
125
+ }
126
+ if (step.action === 'type') {
127
+ lines.push(` await ${locator}.fill(${stringLiteral(step.value)});`);
128
+ return;
129
+ }
130
+ if (step.action === 'select') {
131
+ lines.push(` await ${locator}.selectOption(${stringLiteral(step.value)});`);
132
+ return;
133
+ }
134
+ if (step.action === 'waitFor' || step.action === 'assertVisible') {
135
+ lines.push(` await expect(${locator}).toBeVisible();`);
136
+ }
137
+ }
138
+ function appendAssertion(lines, assertion, elements, widgets, warnings) {
139
+ if (assertion.kind === 'mockCalled') {
140
+ const matcher = assertion.method
141
+ ? `{ path: ${stringLiteral(assertion.endpoint)}, method: ${stringLiteral(assertion.method)} }`
142
+ : stringLiteral(assertion.endpoint);
143
+ lines.push(` await mock.waitForCall(${matcher});`);
144
+ return;
145
+ }
146
+ if (assertion.kind === 'route') {
147
+ lines.push(` await expect(await page.currentRoute()).toBe(${stringLiteral(assertion.equals)});`);
148
+ return;
149
+ }
150
+ if (assertion.kind === 'state') {
151
+ warnings.push(`State assertion '${assertion.path}' requires a custom state adapter and was not emitted.`);
152
+ return;
153
+ }
154
+ const element = elements.get(assertion.target);
155
+ if (!element) {
156
+ warnings.push(`Assertion target '${assertion.target}' was not found in spec.elements.`);
157
+ return;
158
+ }
159
+ const locator = locatorExpression(element, widgets);
160
+ if (assertion.kind === 'visible') {
161
+ lines.push(` await expect(${locator}).toBeVisible();`);
162
+ return;
163
+ }
164
+ if (assertion.equals !== undefined) {
165
+ lines.push(` await expect(${locator}).toHaveText(${stringLiteral(assertion.equals)});`);
166
+ }
167
+ else if (assertion.contains !== undefined) {
168
+ lines.push(` await expect(${locator}).toContainText(${stringLiteral(assertion.contains)});`);
169
+ }
170
+ else {
171
+ lines.push(` await expect(${locator}).toBeVisible();`);
172
+ }
173
+ }
174
+ function locatorExpression(element, widgets) {
175
+ const hint = bestLocatorHint(element, widgets);
176
+ return `page.locator(${locatorInputExpression(hint)})`;
177
+ }
178
+ function locatorInputExpression(hint) {
179
+ if (hint.strategy === 'key')
180
+ return `{ key: ${stringLiteral(hint.value)} }`;
181
+ if (hint.strategy === 'semantics')
182
+ return `{ semantics: { label: ${stringLiteral(hint.value)} } }`;
183
+ if (hint.strategy === 'type')
184
+ return `{ type: ${stringLiteral(hint.value)} }`;
185
+ return `{ text: ${stringLiteral(hint.value)} }`;
186
+ }
187
+ function stringLiteral(value) {
188
+ return JSON.stringify(value);
189
+ }