@fliwright/cli 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/LICENSE +21 -0
- package/README.md +59 -2
- package/dist/ArtifactReferences.d.ts +7 -0
- package/dist/ArtifactReferences.js +82 -0
- package/dist/CommandRegistry.d.ts +40 -0
- package/dist/CommandRegistry.js +177 -0
- package/dist/InspectionOutput.d.ts +5 -0
- package/dist/InspectionOutput.js +11 -0
- package/dist/RecordingReplay.d.ts +24 -0
- package/dist/RecordingReplay.js +79 -0
- package/dist/WorkflowContext.d.ts +20 -0
- package/dist/WorkflowContext.js +1 -0
- package/dist/capabilities/form.d.ts +13 -0
- package/dist/capabilities/form.js +9 -0
- package/dist/capabilities/interaction.d.ts +226 -0
- package/dist/capabilities/interaction.js +447 -0
- package/dist/capabilities/session.d.ts +18 -0
- package/dist/capabilities/session.js +55 -0
- package/dist/catalog.d.ts +36 -0
- package/dist/catalog.js +69 -0
- package/dist/commands/app-inspect.d.ts +96 -0
- package/dist/commands/app-inspect.js +70 -0
- package/dist/commands/app.d.ts +53 -0
- package/dist/commands/app.js +104 -0
- package/dist/commands/artifact-query.d.ts +138 -0
- package/dist/commands/artifact-query.js +81 -0
- package/dist/commands/artifacts.d.ts +40 -0
- package/dist/commands/artifacts.js +311 -0
- package/dist/commands/doctor.d.ts +11 -0
- package/dist/commands/doctor.js +285 -0
- package/dist/commands/flow-runtime.d.ts +40 -0
- package/dist/commands/flow-runtime.js +37 -0
- package/dist/commands/flow.d.ts +122 -0
- package/dist/commands/flow.js +236 -0
- package/dist/commands/generate-test.d.ts +46 -0
- package/dist/commands/generate-test.js +233 -0
- package/dist/commands/init.d.ts +22 -0
- package/dist/commands/init.js +262 -0
- package/dist/commands/mock-management.d.ts +53 -0
- package/dist/commands/mock-management.js +65 -0
- package/dist/commands/mock.d.ts +8 -0
- package/dist/commands/mock.js +27 -0
- package/dist/commands/record.d.ts +55 -0
- package/dist/commands/record.js +216 -0
- package/dist/commands/run.d.ts +93 -0
- package/dist/commands/run.js +707 -0
- package/dist/commands/scenario.d.ts +26 -0
- package/dist/commands/scenario.js +39 -0
- package/dist/commands/tdd.d.ts +72 -0
- package/dist/commands/tdd.js +218 -0
- package/dist/config.d.ts +20 -0
- package/dist/config.js +40 -0
- package/dist/index.d.ts +10 -0
- package/dist/index.js +139 -0
- package/dist/registry/devices.d.ts +2 -0
- package/dist/registry/devices.js +12 -0
- package/dist/registry/finite.d.ts +38 -0
- package/dist/registry/finite.js +121 -0
- package/dist/registry/flow-schemas.d.ts +405 -0
- package/dist/registry/flow-schemas.js +98 -0
- package/dist/registry/flow.d.ts +3 -0
- package/dist/registry/flow.js +56 -0
- package/dist/registry/generation-schema.d.ts +112 -0
- package/dist/registry/generation-schema.js +36 -0
- package/dist/registry/session.d.ts +2 -0
- package/dist/registry/session.js +24 -0
- package/dist/registry/tdd.d.ts +3 -0
- package/dist/registry/tdd.js +118 -0
- package/dist/reporter.d.ts +95 -0
- package/dist/reporter.js +61 -0
- package/dist/run.d.ts +6 -0
- package/dist/run.js +5 -0
- package/dist/session/ConnectionHost.d.ts +43 -0
- package/dist/session/ConnectionHost.js +129 -0
- package/dist/session/client.d.ts +38 -0
- package/dist/session/client.js +120 -0
- package/dist/session/worker.d.ts +1 -0
- package/dist/session/worker.js +161 -0
- package/dist/vm-discovery.d.ts +14 -0
- package/dist/vm-discovery.js +85 -0
- package/package.json +78 -3
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
import { mkdirSync, writeFileSync } from 'node:fs';
|
|
2
|
+
import { join } from 'node:path';
|
|
3
|
+
import { TddRuntime } from '@fliwright/tdd';
|
|
4
|
+
import { CommandRegistry, CliError } from '../CommandRegistry.js';
|
|
5
|
+
import { registerFinite } from '../registry/finite.js';
|
|
6
|
+
import { registerFlow } from '../registry/flow.js';
|
|
7
|
+
import { connectAppSession } from '../capabilities/session.js';
|
|
8
|
+
/** Owns persistent objects only; run evidence, artifacts and endpoint leases keep their existing owners. */
|
|
9
|
+
export class ConnectionHost {
|
|
10
|
+
options;
|
|
11
|
+
session;
|
|
12
|
+
runtime;
|
|
13
|
+
workflow;
|
|
14
|
+
queue = Promise.resolve();
|
|
15
|
+
closed = false;
|
|
16
|
+
closing = false;
|
|
17
|
+
constructor(options) {
|
|
18
|
+
this.options = options;
|
|
19
|
+
}
|
|
20
|
+
async open(signal) {
|
|
21
|
+
if (this.closed)
|
|
22
|
+
throw new CliError('SESSION_CLOSED', 'Session is closed.', 4);
|
|
23
|
+
if (!this.session)
|
|
24
|
+
this.session = await connectAppSession({ ...this.options, signal }, this.options);
|
|
25
|
+
return { connected: true };
|
|
26
|
+
}
|
|
27
|
+
async whenIdle() { await this.queue; }
|
|
28
|
+
async refreshEndpoint() {
|
|
29
|
+
const endpoint = this.runtime?.endpoint ?? this.options.vmUrl;
|
|
30
|
+
await this.session?.driver.dispose();
|
|
31
|
+
this.session = undefined;
|
|
32
|
+
this.session = await connectAppSession({ cwd: this.options.cwd, vmUrl: endpoint }, this.options);
|
|
33
|
+
}
|
|
34
|
+
async reconnectRuntime() {
|
|
35
|
+
const result = await this.getRuntime().reconnect();
|
|
36
|
+
await this.refreshEndpoint();
|
|
37
|
+
return result;
|
|
38
|
+
}
|
|
39
|
+
async reconnect() {
|
|
40
|
+
await this.queue;
|
|
41
|
+
await this.refreshEndpoint();
|
|
42
|
+
}
|
|
43
|
+
status() { return { connected: Boolean(this.session), endpoint: this.session?.vmServiceUrl, tdd: this.runtime?.snapshot(), workflow: this.workflow, closed: this.closed }; }
|
|
44
|
+
getRuntime() {
|
|
45
|
+
if (!this.runtime)
|
|
46
|
+
throw new CliError('TDD_NOT_STARTED', 'Start the TDD runtime before this command.', 4);
|
|
47
|
+
return this.runtime;
|
|
48
|
+
}
|
|
49
|
+
async startRuntime(input) {
|
|
50
|
+
if (this.runtime)
|
|
51
|
+
throw new CliError('TDD_ALREADY_STARTED', 'Stop the current runtime before starting another.', 4);
|
|
52
|
+
const runtime = this.options.runtimeFactory?.() ?? new TddRuntime();
|
|
53
|
+
this.runtime = runtime;
|
|
54
|
+
let result;
|
|
55
|
+
try {
|
|
56
|
+
result = await runtime.start(input);
|
|
57
|
+
}
|
|
58
|
+
catch (error) {
|
|
59
|
+
this.runtime = undefined;
|
|
60
|
+
throw error;
|
|
61
|
+
}
|
|
62
|
+
if (runtime.endpoint && this.session?.vmServiceUrl !== runtime.endpoint) {
|
|
63
|
+
await this.session?.driver.dispose();
|
|
64
|
+
this.session = await connectAppSession({ cwd: this.options.cwd, vmUrl: runtime.endpoint }, this.options);
|
|
65
|
+
}
|
|
66
|
+
return result;
|
|
67
|
+
}
|
|
68
|
+
async stopRuntime(keepAppAlive = false) {
|
|
69
|
+
const runtime = this.getRuntime();
|
|
70
|
+
await runtime.stop({ keepAppAlive });
|
|
71
|
+
this.runtime = undefined;
|
|
72
|
+
return runtime.snapshot();
|
|
73
|
+
}
|
|
74
|
+
setWorkflow(context) {
|
|
75
|
+
this.workflow = context;
|
|
76
|
+
const directory = join(this.options.cwd, '.fliwright', 'sessions', this.options.id ?? 'local');
|
|
77
|
+
mkdirSync(directory, { recursive: true, mode: 0o700 });
|
|
78
|
+
writeFileSync(join(directory, 'workflow.json'), JSON.stringify(context), { mode: 0o600 });
|
|
79
|
+
}
|
|
80
|
+
getWorkflow() { return this.workflow; }
|
|
81
|
+
async execute(command, input, context) {
|
|
82
|
+
if (this.closing || this.closed)
|
|
83
|
+
throw new CliError('SESSION_CLOSED', 'Session is closing.', 4);
|
|
84
|
+
const abort = () => { if (command.startsWith('tdd.') || command.startsWith('devassist.'))
|
|
85
|
+
void this.runtime?.cancel(); };
|
|
86
|
+
const run = this.queue.then(async () => {
|
|
87
|
+
context?.signal?.throwIfAborted();
|
|
88
|
+
context?.signal?.addEventListener('abort', abort, { once: true });
|
|
89
|
+
await context?.onStart?.();
|
|
90
|
+
if (this.closed)
|
|
91
|
+
throw new CliError('SESSION_CLOSED', 'Session is closed.', 4);
|
|
92
|
+
const registry = new CommandRegistry();
|
|
93
|
+
registerFinite(registry, { app: { sessionProvider: async () => { await this.open(); return this.session; } } });
|
|
94
|
+
registerFlow(registry, { sessionProvider: async () => { await this.open(); return this.session; } });
|
|
95
|
+
const { registerTdd } = await import('../registry/tdd.js');
|
|
96
|
+
registerTdd(registry, this);
|
|
97
|
+
const definition = registry.definitions.get(command);
|
|
98
|
+
if (!definition || command === 'mock.start' || (!command.startsWith('tdd.') && !command.startsWith('devassist.') && !command.startsWith('app.') && !command.startsWith('scenario.') && !command.startsWith('mock.') && !command.startsWith('flow.review-') && command !== 'generate-test'))
|
|
99
|
+
throw new CliError('INVALID_INPUT', `Command cannot execute in a connection session: ${command}`, 2);
|
|
100
|
+
const parsed = definition.input.strict().parse(input);
|
|
101
|
+
const result = await definition.execute(parsed, { cwd: this.options.cwd, requestId: context?.requestId ?? 'local', signal: context?.signal ?? new AbortController().signal });
|
|
102
|
+
context?.signal?.throwIfAborted();
|
|
103
|
+
return result;
|
|
104
|
+
});
|
|
105
|
+
// Runtime cycle timeouts can return before the executor settles; retain host ownership until idle.
|
|
106
|
+
this.queue = run.catch(() => { }).then(async () => {
|
|
107
|
+
await this.runtime?.whenIdle();
|
|
108
|
+
context?.signal?.removeEventListener('abort', abort);
|
|
109
|
+
if (context?.signal?.aborted && this.session) {
|
|
110
|
+
await this.session.driver.dispose({ signal: AbortSignal.abort() });
|
|
111
|
+
this.session = undefined;
|
|
112
|
+
}
|
|
113
|
+
});
|
|
114
|
+
return run;
|
|
115
|
+
}
|
|
116
|
+
async close(keepAppAlive = false) {
|
|
117
|
+
this.closing = true;
|
|
118
|
+
await this.queue;
|
|
119
|
+
this.closed = true;
|
|
120
|
+
try {
|
|
121
|
+
if (this.runtime)
|
|
122
|
+
await this.stopRuntime(keepAppAlive);
|
|
123
|
+
}
|
|
124
|
+
finally {
|
|
125
|
+
await this.session?.driver.dispose();
|
|
126
|
+
this.session = undefined;
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
export declare const SESSION_VERSION = 1;
|
|
2
|
+
export declare const SESSION_PACKAGE_VERSION: string;
|
|
3
|
+
export interface SessionControl {
|
|
4
|
+
id: string;
|
|
5
|
+
generation: string;
|
|
6
|
+
pid: number;
|
|
7
|
+
version: number;
|
|
8
|
+
packageVersion: string;
|
|
9
|
+
socket: string;
|
|
10
|
+
cwd: string;
|
|
11
|
+
}
|
|
12
|
+
export declare function sessionDirectory(cwd: string, id: string): string;
|
|
13
|
+
export declare function sessionSocket(cwd: string, id: string): string;
|
|
14
|
+
export declare function readSession(cwd: string, id: string): Promise<SessionControl>;
|
|
15
|
+
export declare function sessionRequest(cwd: string, id: string, request: Record<string, unknown>, signal?: AbortSignal): Promise<unknown>;
|
|
16
|
+
export declare function sessionOpenCommand(options: {
|
|
17
|
+
cwd: string;
|
|
18
|
+
vmUrl?: string;
|
|
19
|
+
deviceId?: string;
|
|
20
|
+
target?: string;
|
|
21
|
+
config?: string;
|
|
22
|
+
projectId?: string;
|
|
23
|
+
flutterArgs?: string[];
|
|
24
|
+
scenario?: string;
|
|
25
|
+
}, signal?: AbortSignal): Promise<{
|
|
26
|
+
sessionId: `${string}-${string}-${string}-${string}-${string}`;
|
|
27
|
+
}>;
|
|
28
|
+
export declare function sessionListCommand(cwd: string): Promise<{
|
|
29
|
+
sessions: ({
|
|
30
|
+
sessionId: string;
|
|
31
|
+
connected?: undefined;
|
|
32
|
+
status?: undefined;
|
|
33
|
+
} | {
|
|
34
|
+
sessionId: string;
|
|
35
|
+
connected: boolean;
|
|
36
|
+
status: string;
|
|
37
|
+
})[];
|
|
38
|
+
}>;
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
import { createConnection } from 'node:net';
|
|
2
|
+
import { setTimeout as delay } from 'node:timers/promises';
|
|
3
|
+
import { spawn } from 'node:child_process';
|
|
4
|
+
import { readFileSync } from 'node:fs';
|
|
5
|
+
import { mkdir, readFile, readdir, writeFile } from 'node:fs/promises';
|
|
6
|
+
import { join, resolve } from 'node:path';
|
|
7
|
+
import { fileURLToPath } from 'node:url';
|
|
8
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
9
|
+
import { tmpdir } from 'node:os';
|
|
10
|
+
import { CliError } from '../CommandRegistry.js';
|
|
11
|
+
export const SESSION_VERSION = 1;
|
|
12
|
+
export const SESSION_PACKAGE_VERSION = JSON.parse(readFileSync(new URL('../../package.json', import.meta.url), 'utf8')).version;
|
|
13
|
+
export function sessionDirectory(cwd, id) {
|
|
14
|
+
if (!/^[a-zA-Z0-9-]{1,64}$/.test(id))
|
|
15
|
+
throw new CliError('INVALID_INPUT', 'Invalid session ID.', 2);
|
|
16
|
+
return join(resolve(cwd), '.fliwright', 'sessions', id);
|
|
17
|
+
}
|
|
18
|
+
export function sessionSocket(cwd, id) {
|
|
19
|
+
const hash = createHash('sha256').update(`${resolve(cwd)}:${id}`).digest('hex').slice(0, 24);
|
|
20
|
+
return process.platform === 'win32' ? `\\\\.\\pipe\\fliwright-${hash}` : join(tmpdir(), `fliwright-${hash}.sock`);
|
|
21
|
+
}
|
|
22
|
+
export async function readSession(cwd, id) {
|
|
23
|
+
try {
|
|
24
|
+
const data = JSON.parse(await readFile(join(sessionDirectory(cwd, id), 'control.json'), 'utf8'));
|
|
25
|
+
if (data.version !== SESSION_VERSION || data.packageVersion !== SESSION_PACKAGE_VERSION || data.cwd !== resolve(cwd))
|
|
26
|
+
throw new CliError('SESSION_VERSION_MISMATCH', 'Session version/project mismatch. Close and reopen the session.', 4);
|
|
27
|
+
return data;
|
|
28
|
+
}
|
|
29
|
+
catch (error) {
|
|
30
|
+
if (error instanceof CliError)
|
|
31
|
+
throw error;
|
|
32
|
+
throw new CliError('SESSION_UNAVAILABLE', `Session ${id} is unavailable.`, 3);
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
export async function sessionRequest(cwd, id, request, signal) {
|
|
36
|
+
signal?.throwIfAborted();
|
|
37
|
+
const control = await readSession(cwd, id);
|
|
38
|
+
return new Promise((resolve, reject) => {
|
|
39
|
+
const socket = createConnection(control.socket);
|
|
40
|
+
let body = '';
|
|
41
|
+
const abort = () => { socket.destroy(); reject(signal?.reason); };
|
|
42
|
+
socket.once('connect', () => socket.write(JSON.stringify({ ...request, generation: control.generation, version: SESSION_VERSION, packageVersion: SESSION_PACKAGE_VERSION }) + '\n'));
|
|
43
|
+
socket.on('data', (chunk) => {
|
|
44
|
+
body += String(chunk);
|
|
45
|
+
if (!body.includes('\n'))
|
|
46
|
+
return;
|
|
47
|
+
socket.end();
|
|
48
|
+
try {
|
|
49
|
+
const response = JSON.parse(body.split('\n')[0]);
|
|
50
|
+
if (response.error)
|
|
51
|
+
reject(new CliError(response.error.code, response.error.message, response.error.exitCode, response.data));
|
|
52
|
+
else
|
|
53
|
+
resolve(response.data);
|
|
54
|
+
}
|
|
55
|
+
catch (error) {
|
|
56
|
+
reject(error);
|
|
57
|
+
}
|
|
58
|
+
});
|
|
59
|
+
socket.once('error', () => reject(new CliError('SESSION_UNAVAILABLE', 'Session worker is not reachable; open a new session.', 3)));
|
|
60
|
+
socket.once('close', () => { signal?.removeEventListener('abort', abort); if (!body.includes('\n') && !signal?.aborted)
|
|
61
|
+
reject(new CliError('SESSION_DISCONNECTED', 'Worker disconnected; inspect operation status before retrying.', 3)); });
|
|
62
|
+
if (signal?.aborted)
|
|
63
|
+
abort();
|
|
64
|
+
else
|
|
65
|
+
signal?.addEventListener('abort', abort, { once: true });
|
|
66
|
+
});
|
|
67
|
+
}
|
|
68
|
+
export async function sessionOpenCommand(options, signal) {
|
|
69
|
+
const id = randomUUID();
|
|
70
|
+
const directory = sessionDirectory(options.cwd, id);
|
|
71
|
+
await mkdir(directory, { recursive: true, mode: 0o700 });
|
|
72
|
+
const startup = join(directory, 'startup.json');
|
|
73
|
+
await writeFile(startup, JSON.stringify({ ...options, cwd: resolve(options.cwd), id }), { mode: 0o600 });
|
|
74
|
+
const child = spawn(process.execPath, [fileURLToPath(new URL('./worker.js', import.meta.url)), startup], { cwd: options.cwd, detached: true, stdio: 'ignore' });
|
|
75
|
+
let spawnError;
|
|
76
|
+
child.once('error', (error) => { spawnError = error; });
|
|
77
|
+
child.unref();
|
|
78
|
+
const startupSignal = AbortSignal.any([signal ?? new AbortController().signal, AbortSignal.timeout(options.deviceId ? 180000 : 30000)]);
|
|
79
|
+
let ready = false;
|
|
80
|
+
try {
|
|
81
|
+
while (!startupSignal.aborted) {
|
|
82
|
+
if (spawnError || child.exitCode !== null || child.signalCode !== null)
|
|
83
|
+
throw new CliError('SESSION_START_FAILED', spawnError?.message ?? 'Session worker exited during startup.', 3);
|
|
84
|
+
try {
|
|
85
|
+
const error = await readFile(join(directory, 'startup-error.json'), 'utf8').catch(() => undefined);
|
|
86
|
+
if (error)
|
|
87
|
+
throw new CliError('SESSION_START_FAILED', JSON.parse(error).message, 3);
|
|
88
|
+
const data = await sessionRequest(options.cwd, id, { type: 'status' }, startupSignal);
|
|
89
|
+
ready = true;
|
|
90
|
+
return { sessionId: id, ...data };
|
|
91
|
+
}
|
|
92
|
+
catch (error) {
|
|
93
|
+
if (error instanceof CliError && error.code === 'SESSION_START_FAILED')
|
|
94
|
+
throw error;
|
|
95
|
+
await delay(30, undefined, { signal: startupSignal }).catch(() => { });
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
throw startupSignal.reason;
|
|
99
|
+
}
|
|
100
|
+
finally {
|
|
101
|
+
if (!ready && child.pid) {
|
|
102
|
+
try {
|
|
103
|
+
process.kill(child.pid, 'SIGTERM');
|
|
104
|
+
}
|
|
105
|
+
catch { }
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
export async function sessionListCommand(cwd) {
|
|
110
|
+
const root = join(resolve(cwd), '.fliwright', 'sessions');
|
|
111
|
+
const ids = await readdir(root).catch(() => []);
|
|
112
|
+
return { sessions: await Promise.all(ids.map(async (id) => {
|
|
113
|
+
try {
|
|
114
|
+
return { sessionId: id, ...await sessionRequest(cwd, id, { type: 'status' }, AbortSignal.timeout(1000)) };
|
|
115
|
+
}
|
|
116
|
+
catch {
|
|
117
|
+
return { sessionId: id, connected: false, status: 'unreachable' };
|
|
118
|
+
}
|
|
119
|
+
})) };
|
|
120
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
import { createServer } from 'node:net';
|
|
2
|
+
import { chmod, mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises';
|
|
3
|
+
import { join } from 'node:path';
|
|
4
|
+
import { randomUUID } from 'node:crypto';
|
|
5
|
+
import { ConnectionHost } from './ConnectionHost.js';
|
|
6
|
+
import { SESSION_VERSION, SESSION_PACKAGE_VERSION, sessionDirectory, sessionSocket } from './client.js';
|
|
7
|
+
import { classifyError } from '../CommandRegistry.js';
|
|
8
|
+
async function main(startup) {
|
|
9
|
+
const options = JSON.parse(await readFile(startup, 'utf8'));
|
|
10
|
+
const directory = sessionDirectory(options.cwd, options.id);
|
|
11
|
+
const socketPath = sessionSocket(options.cwd, options.id);
|
|
12
|
+
const generation = randomUUID();
|
|
13
|
+
const host = new ConnectionHost(options);
|
|
14
|
+
const active = new Map();
|
|
15
|
+
const claimed = new Set();
|
|
16
|
+
let closing = false;
|
|
17
|
+
let idleTimer;
|
|
18
|
+
const touch = () => { clearTimeout(idleTimer); idleTimer = setTimeout(() => { if (!active.size)
|
|
19
|
+
void close();
|
|
20
|
+
else
|
|
21
|
+
touch(); }, 30 * 60 * 1000); };
|
|
22
|
+
async function persist(id, value) {
|
|
23
|
+
const path = join(directory, 'operations', `${id}.json`);
|
|
24
|
+
await mkdir(join(directory, 'operations'), { recursive: true, mode: 0o700 });
|
|
25
|
+
await writeFile(`${path}.tmp`, JSON.stringify(value), { mode: 0o600 });
|
|
26
|
+
await rename(`${path}.tmp`, path);
|
|
27
|
+
}
|
|
28
|
+
async function close(keepAppAlive = false) {
|
|
29
|
+
if (closing)
|
|
30
|
+
return;
|
|
31
|
+
closing = true;
|
|
32
|
+
clearTimeout(idleTimer);
|
|
33
|
+
for (const controller of active.values())
|
|
34
|
+
controller.abort(new DOMException('Session closing.', 'AbortError'));
|
|
35
|
+
try {
|
|
36
|
+
await host.close(keepAppAlive);
|
|
37
|
+
}
|
|
38
|
+
finally {
|
|
39
|
+
if (server.listening)
|
|
40
|
+
server.close();
|
|
41
|
+
if (process.platform !== 'win32')
|
|
42
|
+
await rm(socketPath, { force: true });
|
|
43
|
+
await rm(join(directory, 'control.json'), { force: true });
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
const server = createServer((socket) => {
|
|
47
|
+
let body = '';
|
|
48
|
+
socket.setEncoding('utf8');
|
|
49
|
+
socket.on('error', () => { });
|
|
50
|
+
socket.on('data', (chunk) => {
|
|
51
|
+
body += chunk;
|
|
52
|
+
if (body.length > 4 * 1024 * 1024) {
|
|
53
|
+
socket.destroy();
|
|
54
|
+
return;
|
|
55
|
+
}
|
|
56
|
+
if (!body.includes('\n'))
|
|
57
|
+
return;
|
|
58
|
+
socket.removeAllListeners('data');
|
|
59
|
+
void (async () => {
|
|
60
|
+
let request;
|
|
61
|
+
try {
|
|
62
|
+
request = JSON.parse(body.split('\n')[0]);
|
|
63
|
+
if (request.generation !== generation || request.version !== SESSION_VERSION || request.packageVersion !== SESSION_PACKAGE_VERSION)
|
|
64
|
+
throw new Error('Session generation/version mismatch.');
|
|
65
|
+
touch();
|
|
66
|
+
let data;
|
|
67
|
+
if (request.type === 'status') {
|
|
68
|
+
if (request.operationId) {
|
|
69
|
+
if (!/^[a-zA-Z0-9-]{1,64}$/.test(request.operationId))
|
|
70
|
+
throw new Error('Invalid operationId.');
|
|
71
|
+
data = JSON.parse(await readFile(join(directory, 'operations', `${request.operationId}.json`), 'utf8'));
|
|
72
|
+
}
|
|
73
|
+
else
|
|
74
|
+
data = { ...host.status(), sessionId: options.id, pid: process.pid, generation, version: SESSION_VERSION, operations: [...active.keys()] };
|
|
75
|
+
}
|
|
76
|
+
else if (request.type === 'cancel') {
|
|
77
|
+
active.get(request.operationId)?.abort(new DOMException('Operation cancelled.', 'AbortError'));
|
|
78
|
+
data = { operationId: request.operationId, cancellationRequested: active.has(request.operationId) };
|
|
79
|
+
}
|
|
80
|
+
else if (request.type === 'close') {
|
|
81
|
+
await close(request.keepAppAlive);
|
|
82
|
+
data = { closed: true };
|
|
83
|
+
}
|
|
84
|
+
else if (request.type === 'reconnect') {
|
|
85
|
+
await host.reconnect();
|
|
86
|
+
data = host.status();
|
|
87
|
+
}
|
|
88
|
+
else if (request.type === 'execute' && !closing) {
|
|
89
|
+
const operationId = request.operationId;
|
|
90
|
+
if (!/^[a-zA-Z0-9-]{1,64}$/.test(operationId))
|
|
91
|
+
throw new Error('Invalid operationId.');
|
|
92
|
+
// Never replay an operation after a lost response.
|
|
93
|
+
if (claimed.has(operationId)) {
|
|
94
|
+
socket.end(JSON.stringify({ data: { operationId, state: active.has(operationId) ? 'running' : 'unknown', statusCommand: 'session.status' } }) + '\n');
|
|
95
|
+
return;
|
|
96
|
+
}
|
|
97
|
+
claimed.add(operationId);
|
|
98
|
+
const existing = await readFile(join(directory, 'operations', `${operationId}.json`), 'utf8').catch(() => undefined);
|
|
99
|
+
if (existing) {
|
|
100
|
+
data = JSON.parse(existing);
|
|
101
|
+
socket.end(JSON.stringify({ data }) + '\n');
|
|
102
|
+
return;
|
|
103
|
+
}
|
|
104
|
+
const controller = new AbortController();
|
|
105
|
+
active.set(operationId, controller);
|
|
106
|
+
await persist(operationId, { operationId, state: 'queued', command: request.command });
|
|
107
|
+
try {
|
|
108
|
+
data = await host.execute(request.command, request.input, { requestId: operationId, signal: controller.signal, onStart: () => persist(operationId, { operationId, state: 'running', command: request.command }) });
|
|
109
|
+
socket.end(JSON.stringify({ data }) + '\n');
|
|
110
|
+
await host.whenIdle();
|
|
111
|
+
await persist(operationId, { operationId, state: 'succeeded', data });
|
|
112
|
+
}
|
|
113
|
+
catch (error) {
|
|
114
|
+
const failure = classifyError(controller.signal.aborted ? controller.signal.reason : error);
|
|
115
|
+
socket.end(JSON.stringify({ error: { code: failure.code, message: failure.message, exitCode: failure.exitCode }, data: failure.data }) + '\n');
|
|
116
|
+
await host.whenIdle();
|
|
117
|
+
await persist(operationId, { operationId, state: controller.signal.aborted ? 'cancelled' : 'failed', error: { code: failure.code, message: failure.message, exitCode: failure.exitCode }, data: failure.data });
|
|
118
|
+
}
|
|
119
|
+
finally {
|
|
120
|
+
active.delete(operationId);
|
|
121
|
+
}
|
|
122
|
+
return;
|
|
123
|
+
}
|
|
124
|
+
else
|
|
125
|
+
throw new Error('Unsupported session control request.');
|
|
126
|
+
socket.end(JSON.stringify({ data }) + '\n');
|
|
127
|
+
}
|
|
128
|
+
catch (error) {
|
|
129
|
+
socket.end(JSON.stringify({ error: (() => { const failure = classifyError(error); return { code: failure.code, message: failure.message, exitCode: failure.exitCode }; })() }) + '\n');
|
|
130
|
+
}
|
|
131
|
+
})();
|
|
132
|
+
});
|
|
133
|
+
});
|
|
134
|
+
const startupController = new AbortController();
|
|
135
|
+
active.set(generation, startupController);
|
|
136
|
+
process.once('SIGINT', () => void close());
|
|
137
|
+
process.once('SIGTERM', () => void close());
|
|
138
|
+
try {
|
|
139
|
+
startupController.signal.throwIfAborted();
|
|
140
|
+
if (options.deviceId) {
|
|
141
|
+
const { id: _id, cwd: _cwd, ...input } = options;
|
|
142
|
+
await host.execute('tdd.start', input, { requestId: generation, signal: startupController.signal });
|
|
143
|
+
}
|
|
144
|
+
startupController.signal.throwIfAborted();
|
|
145
|
+
await host.open(startupController.signal);
|
|
146
|
+
startupController.signal.throwIfAborted();
|
|
147
|
+
await new Promise((resolve, reject) => { server.once('error', reject); server.listen(socketPath, resolve); });
|
|
148
|
+
if (process.platform !== 'win32')
|
|
149
|
+
await chmod(socketPath, 0o600);
|
|
150
|
+
await writeFile(join(directory, 'control.json'), JSON.stringify({ id: options.id, cwd: options.cwd, socket: socketPath, generation, version: SESSION_VERSION, packageVersion: SESSION_PACKAGE_VERSION, pid: process.pid }), { mode: 0o600 });
|
|
151
|
+
await rm(startup, { force: true });
|
|
152
|
+
active.delete(generation);
|
|
153
|
+
touch();
|
|
154
|
+
}
|
|
155
|
+
catch (error) {
|
|
156
|
+
await writeFile(join(directory, 'startup-error.json'), JSON.stringify({ message: error instanceof Error ? error.message : String(error) }));
|
|
157
|
+
await close();
|
|
158
|
+
process.exitCode = 3;
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
void main(process.argv[2]).catch((error) => { console.error(error); process.exitCode = 3; });
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { normalizeVmServiceUrl } from '@fliwright/core';
|
|
2
|
+
export interface ResolveOptions {
|
|
3
|
+
cliFlag?: string;
|
|
4
|
+
configUrl?: string;
|
|
5
|
+
cwd?: string;
|
|
6
|
+
verify?: boolean;
|
|
7
|
+
env?: Record<string, string | undefined>;
|
|
8
|
+
}
|
|
9
|
+
export declare function resolveVmUrl(options?: ResolveOptions): Promise<string | null>;
|
|
10
|
+
export declare function discoverVmServiceUrl(options?: {
|
|
11
|
+
ports?: number[];
|
|
12
|
+
verify?: boolean;
|
|
13
|
+
} | number[]): Promise<string | null>;
|
|
14
|
+
export { normalizeVmServiceUrl };
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import { VmServiceEndpointResolver, explicitEndpointSource, normalizeVmServiceUrl, verifyVmServiceEndpoint, workspaceEndpointSource, } from '@fliwright/core';
|
|
2
|
+
const SCAN_PORTS = [8181, 9189, 54321];
|
|
3
|
+
export async function resolveVmUrl(options = {}) {
|
|
4
|
+
const env = options.env ?? process.env;
|
|
5
|
+
// Preserve the attach facade's synchronous precedence; managed commands opt into
|
|
6
|
+
// the Core verifier below with `verify: true`.
|
|
7
|
+
if (!options.verify) {
|
|
8
|
+
if (options.cliFlag)
|
|
9
|
+
return options.cliFlag;
|
|
10
|
+
const directEnvUrl = env.FLIWRIGHT_VM_URL ?? env.FLIWRIGHT_VM_SERVICE_URL;
|
|
11
|
+
if (directEnvUrl)
|
|
12
|
+
return directEnvUrl;
|
|
13
|
+
if (options.configUrl)
|
|
14
|
+
return options.configUrl;
|
|
15
|
+
}
|
|
16
|
+
const sources = [];
|
|
17
|
+
if (options.cliFlag)
|
|
18
|
+
sources.push(explicitEndpointSource(options.cliFlag, { source: 'argument' }));
|
|
19
|
+
const envUrl = env.FLIWRIGHT_VM_URL ?? env.FLIWRIGHT_VM_SERVICE_URL;
|
|
20
|
+
if (envUrl)
|
|
21
|
+
sources.push(explicitEndpointSource(envUrl, { source: 'environment' }));
|
|
22
|
+
if (options.configUrl)
|
|
23
|
+
sources.push(explicitEndpointSource(options.configUrl, { source: 'project-config' }));
|
|
24
|
+
sources.push(workspaceEndpointSource({ cwd: options.cwd }));
|
|
25
|
+
sources.push(portScanEndpointSource());
|
|
26
|
+
const verify = options.verify ? verifyVmServiceEndpoint : acceptEndpoint;
|
|
27
|
+
try {
|
|
28
|
+
const lease = await new VmServiceEndpointResolver(sources, {
|
|
29
|
+
cwd: options.cwd,
|
|
30
|
+
verify,
|
|
31
|
+
persistWorkspaceCache: options.verify,
|
|
32
|
+
}).acquire();
|
|
33
|
+
return lease.url;
|
|
34
|
+
}
|
|
35
|
+
catch {
|
|
36
|
+
return null;
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
export async function discoverVmServiceUrl(options = {}) {
|
|
40
|
+
const ports = Array.isArray(options) ? options : options.ports;
|
|
41
|
+
try {
|
|
42
|
+
const lease = await new VmServiceEndpointResolver([portScanEndpointSource(ports)], {
|
|
43
|
+
verify: options && !Array.isArray(options) && options.verify ? verifyVmServiceEndpoint : acceptEndpoint,
|
|
44
|
+
persistWorkspaceCache: false,
|
|
45
|
+
}).acquire();
|
|
46
|
+
return lease.url;
|
|
47
|
+
}
|
|
48
|
+
catch {
|
|
49
|
+
return null;
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
function portScanEndpointSource(ports = SCAN_PORTS) {
|
|
53
|
+
return {
|
|
54
|
+
name: 'port-scan',
|
|
55
|
+
async acquire() {
|
|
56
|
+
const endpoints = [];
|
|
57
|
+
for (const port of ports) {
|
|
58
|
+
try {
|
|
59
|
+
const response = await fetch(`http://127.0.0.1:${port}/json/version`, { signal: AbortSignal.timeout(1000) });
|
|
60
|
+
if (!response.ok)
|
|
61
|
+
continue;
|
|
62
|
+
const body = await response.json();
|
|
63
|
+
const url = normalizeVmServiceUrl(body.webSocketDebuggerUrl ?? `ws://127.0.0.1:${port}/ws`);
|
|
64
|
+
if (url)
|
|
65
|
+
endpoints.push({
|
|
66
|
+
url,
|
|
67
|
+
kind: 'direct-vm',
|
|
68
|
+
source: `port-scan:${port}`,
|
|
69
|
+
scope: 'developer-workspace',
|
|
70
|
+
acquiredAt: new Date().toISOString(),
|
|
71
|
+
});
|
|
72
|
+
}
|
|
73
|
+
catch {
|
|
74
|
+
// Port unreachable; continue with the next local candidate.
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
return endpoints;
|
|
78
|
+
},
|
|
79
|
+
};
|
|
80
|
+
}
|
|
81
|
+
const acceptEndpoint = async (_endpoint) => ({
|
|
82
|
+
status: 'ok',
|
|
83
|
+
checkedAt: new Date().toISOString(),
|
|
84
|
+
});
|
|
85
|
+
export { normalizeVmServiceUrl };
|
package/package.json
CHANGED
|
@@ -1,6 +1,81 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@fliwright/cli",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Command-line runner, recorder, and diagnostics for Fliwright Flutter E2E tests.",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"repository": {
|
|
7
|
+
"type": "git",
|
|
8
|
+
"url": "https://github.com/0x01lab/fliwright.git",
|
|
9
|
+
"directory": "packages/fliwright-cli"
|
|
10
|
+
},
|
|
11
|
+
"bugs": {
|
|
12
|
+
"url": "https://github.com/0x01lab/fliwright/issues"
|
|
13
|
+
},
|
|
14
|
+
"homepage": "https://github.com/0x01lab/fliwright#readme",
|
|
15
|
+
"type": "module",
|
|
16
|
+
"main": "dist/config.js",
|
|
17
|
+
"types": "dist/config.d.ts",
|
|
18
|
+
"files": [
|
|
19
|
+
"dist",
|
|
20
|
+
"README.md",
|
|
21
|
+
"LICENSE"
|
|
22
|
+
],
|
|
23
|
+
"engines": {
|
|
24
|
+
"node": "^22.12.0 || ^24.0.0 || >=26.0.0"
|
|
25
|
+
},
|
|
26
|
+
"publishConfig": {
|
|
27
|
+
"access": "public"
|
|
28
|
+
},
|
|
29
|
+
"bin": {
|
|
30
|
+
"fliwright": "dist/index.js"
|
|
31
|
+
},
|
|
32
|
+
"exports": {
|
|
33
|
+
".": {
|
|
34
|
+
"types": "./dist/config.d.ts",
|
|
35
|
+
"import": "./dist/config.js"
|
|
36
|
+
},
|
|
37
|
+
"./run": {
|
|
38
|
+
"import": "./dist/run.js",
|
|
39
|
+
"types": "./dist/run.d.ts"
|
|
40
|
+
},
|
|
41
|
+
"./capabilities/interaction": {
|
|
42
|
+
"import": "./dist/capabilities/interaction.js",
|
|
43
|
+
"types": "./dist/capabilities/interaction.d.ts"
|
|
44
|
+
},
|
|
45
|
+
"./capabilities/form": {
|
|
46
|
+
"import": "./dist/capabilities/form.js",
|
|
47
|
+
"types": "./dist/capabilities/form.d.ts"
|
|
48
|
+
}
|
|
49
|
+
},
|
|
50
|
+
"dependencies": {
|
|
51
|
+
"commander": "^12.0.0",
|
|
52
|
+
"chalk": "^5.3.0",
|
|
53
|
+
"jiti": "^2.0.0",
|
|
54
|
+
"zod": "^3.25.76",
|
|
55
|
+
"zod-to-json-schema": "^3.25.2",
|
|
56
|
+
"@fliwright/core": "0.1.0",
|
|
57
|
+
"@fliwright/tdd": "0.1.0",
|
|
58
|
+
"@fliwright/devices": "0.1.0"
|
|
59
|
+
},
|
|
60
|
+
"peerDependencies": {
|
|
61
|
+
"vitest": "5.0.5",
|
|
62
|
+
"@fliwright/vitest": "0.1.0"
|
|
63
|
+
},
|
|
64
|
+
"peerDependenciesMeta": {
|
|
65
|
+
"@fliwright/vitest": {
|
|
66
|
+
"optional": true
|
|
67
|
+
}
|
|
68
|
+
},
|
|
69
|
+
"devDependencies": {
|
|
70
|
+
"@types/node": "^25.9.1",
|
|
71
|
+
"typescript": "^5.5.0",
|
|
72
|
+
"vitest": "5.0.5",
|
|
73
|
+
"ws": "^8.17.0",
|
|
74
|
+
"@types/ws": "^8.5.10"
|
|
75
|
+
},
|
|
76
|
+
"scripts": {
|
|
77
|
+
"build": "tsc",
|
|
78
|
+
"test": "vitest run",
|
|
79
|
+
"lint": "tsc --noEmit"
|
|
80
|
+
}
|
|
6
81
|
}
|