@open-wa/cli 5.0.0-alpha.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/.open-wa/chrome-executable-path.json +4 -0
- package/.turbo/turbo-build.log +20 -0
- package/.turbo/turbo-test.log +20 -0
- package/CHANGELOG.md +23 -0
- package/LICENSE.md +67 -0
- package/README.md +31 -0
- package/dist/bin.cjs +398 -0
- package/dist/bin.d.cts +1 -0
- package/dist/event-projection-store-BM9eOQXx.cjs +497 -0
- package/dist/index.cjs +33 -0
- package/dist/index.d.cts +239 -0
- package/dist/index.d.cts.map +1 -0
- package/package.json +52 -0
- package/src/__tests__/cli-termination.test.ts +50 -0
- package/src/__tests__/event-projection-store.test.ts +64 -0
- package/src/__tests__/interactive-session.test.ts +84 -0
- package/src/__tests__/interactive-terminal.test.ts +80 -0
- package/src/__tests__/output-broker.test.ts +66 -0
- package/src/__tests__/output-mode.test.ts +68 -0
- package/src/__tests__/shutdown-controller.test.ts +73 -0
- package/src/bin.ts +115 -0
- package/src/config/cli-flags-schema.ts +53 -0
- package/src/index.ts +7 -0
- package/src/presenter/interactive-terminal.ts +178 -0
- package/src/runtime/cli-termination.ts +66 -0
- package/src/runtime/interactive-session.ts +64 -0
- package/src/runtime/output-broker.ts +193 -0
- package/src/runtime/output-mode.ts +73 -0
- package/src/runtime/shutdown-controller.ts +86 -0
- package/src/state/event-projection-store.ts +166 -0
- package/src/tunnel-client.ts +169 -0
- package/tsconfig.json +23 -0
- package/tsconfig.tsbuildinfo +1 -0
- package/tsdown.config.ts +8 -0
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest';
|
|
2
|
+
import { detectOutputMode } from '../runtime/output-mode';
|
|
3
|
+
|
|
4
|
+
describe('detectOutputMode', () => {
|
|
5
|
+
it('selects interactive mode when stdio is fully tty-capable', () => {
|
|
6
|
+
const result = detectOutputMode({
|
|
7
|
+
env: {},
|
|
8
|
+
stdin: { isTTY: true },
|
|
9
|
+
stdout: { isTTY: true },
|
|
10
|
+
stderr: { isTTY: true },
|
|
11
|
+
});
|
|
12
|
+
|
|
13
|
+
expect(result).toEqual({
|
|
14
|
+
kind: 'interactive',
|
|
15
|
+
interactive: true,
|
|
16
|
+
reason: 'tty-ready',
|
|
17
|
+
});
|
|
18
|
+
});
|
|
19
|
+
|
|
20
|
+
it('refuses interactive mode when stdout is not a tty', () => {
|
|
21
|
+
const result = detectOutputMode({
|
|
22
|
+
env: {},
|
|
23
|
+
stdin: { isTTY: true },
|
|
24
|
+
stdout: { isTTY: false },
|
|
25
|
+
stderr: { isTTY: true },
|
|
26
|
+
});
|
|
27
|
+
|
|
28
|
+
expect(result.reason).toBe('stdout-not-tty');
|
|
29
|
+
expect(result.interactive).toBe(false);
|
|
30
|
+
});
|
|
31
|
+
|
|
32
|
+
it('refuses interactive mode when TERM is dumb', () => {
|
|
33
|
+
const result = detectOutputMode({
|
|
34
|
+
env: { TERM: 'dumb' },
|
|
35
|
+
stdin: { isTTY: true },
|
|
36
|
+
stdout: { isTTY: true },
|
|
37
|
+
stderr: { isTTY: true },
|
|
38
|
+
});
|
|
39
|
+
|
|
40
|
+
expect(result.reason).toBe('term-dumb');
|
|
41
|
+
expect(result.kind).toBe('plain');
|
|
42
|
+
});
|
|
43
|
+
|
|
44
|
+
it('honors explicit non-interactive overrides', () => {
|
|
45
|
+
const result = detectOutputMode({
|
|
46
|
+
env: { OPEN_WA_NON_INTERACTIVE: '1' },
|
|
47
|
+
stdin: { isTTY: true },
|
|
48
|
+
stdout: { isTTY: true },
|
|
49
|
+
stderr: { isTTY: true },
|
|
50
|
+
});
|
|
51
|
+
|
|
52
|
+
expect(result.reason).toBe('env.non-interactive');
|
|
53
|
+
expect(result.kind).toBe('plain');
|
|
54
|
+
});
|
|
55
|
+
|
|
56
|
+
it('honors explicit interactive flag when tty checks pass', () => {
|
|
57
|
+
const result = detectOutputMode({
|
|
58
|
+
flags: { outputMode: 'interactive' },
|
|
59
|
+
env: {},
|
|
60
|
+
stdin: { isTTY: true },
|
|
61
|
+
stdout: { isTTY: true },
|
|
62
|
+
stderr: { isTTY: true },
|
|
63
|
+
});
|
|
64
|
+
|
|
65
|
+
expect(result.reason).toBe('flag.interactive');
|
|
66
|
+
expect(result.kind).toBe('interactive');
|
|
67
|
+
});
|
|
68
|
+
});
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
import { describe, expect, it, vi } from 'vitest';
|
|
2
|
+
import { createShutdownController } from '../runtime/shutdown-controller';
|
|
3
|
+
|
|
4
|
+
describe('ShutdownController', () => {
|
|
5
|
+
it('runs graceful shutdown before cleanup on the first signal', async () => {
|
|
6
|
+
const order: string[] = [];
|
|
7
|
+
const controller = createShutdownController({
|
|
8
|
+
gracefulShutdown: async (signal) => {
|
|
9
|
+
order.push(`graceful:${signal}`);
|
|
10
|
+
},
|
|
11
|
+
cleanup: async () => {
|
|
12
|
+
order.push('cleanup');
|
|
13
|
+
},
|
|
14
|
+
exit: (code) => {
|
|
15
|
+
order.push(`exit:${code}`);
|
|
16
|
+
},
|
|
17
|
+
});
|
|
18
|
+
|
|
19
|
+
await controller.handleSignal('SIGINT');
|
|
20
|
+
|
|
21
|
+
expect(order).toEqual(['graceful:SIGINT', 'cleanup', 'exit:0']);
|
|
22
|
+
});
|
|
23
|
+
|
|
24
|
+
it('escalates to a failing exit when graceful shutdown times out', async () => {
|
|
25
|
+
vi.useFakeTimers();
|
|
26
|
+
const order: string[] = [];
|
|
27
|
+
const controller = createShutdownController({
|
|
28
|
+
timeoutMs: 25,
|
|
29
|
+
gracefulShutdown: async () => {
|
|
30
|
+
await new Promise(() => undefined);
|
|
31
|
+
},
|
|
32
|
+
cleanup: async () => {
|
|
33
|
+
order.push('cleanup');
|
|
34
|
+
},
|
|
35
|
+
exit: (code) => {
|
|
36
|
+
order.push(`exit:${code}`);
|
|
37
|
+
},
|
|
38
|
+
});
|
|
39
|
+
|
|
40
|
+
const promise = controller.handleSignal('SIGTERM');
|
|
41
|
+
await vi.advanceTimersByTimeAsync(25);
|
|
42
|
+
await promise;
|
|
43
|
+
|
|
44
|
+
expect(order).toEqual(['cleanup', 'exit:1']);
|
|
45
|
+
vi.useRealTimers();
|
|
46
|
+
});
|
|
47
|
+
|
|
48
|
+
it('forces immediate exit on a second signal', async () => {
|
|
49
|
+
vi.useFakeTimers();
|
|
50
|
+
const order: string[] = [];
|
|
51
|
+
const controller = createShutdownController({
|
|
52
|
+
timeoutMs: 1_000,
|
|
53
|
+
gracefulShutdown: async () => {
|
|
54
|
+
order.push('graceful');
|
|
55
|
+
await new Promise(() => undefined);
|
|
56
|
+
},
|
|
57
|
+
cleanup: async () => {
|
|
58
|
+
order.push('cleanup');
|
|
59
|
+
},
|
|
60
|
+
exit: (code) => {
|
|
61
|
+
order.push(`exit:${code}`);
|
|
62
|
+
},
|
|
63
|
+
});
|
|
64
|
+
|
|
65
|
+
const first = controller.handleSignal('SIGINT');
|
|
66
|
+
await controller.handleSignal('SIGINT');
|
|
67
|
+
|
|
68
|
+
expect(order).toEqual(['graceful', 'cleanup', 'exit:1']);
|
|
69
|
+
vi.runOnlyPendingTimers();
|
|
70
|
+
vi.useRealTimers();
|
|
71
|
+
void first;
|
|
72
|
+
});
|
|
73
|
+
});
|
package/src/bin.ts
ADDED
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { resetCliOutputSink, runCli, setCliOutputSink, type CliRuntimeResult } from '@open-wa/wa-automate';
|
|
3
|
+
import { TunnelClient } from './tunnel-client';
|
|
4
|
+
import { parseCliLocalFlags } from './config/cli-flags-schema';
|
|
5
|
+
import { performGracefulShutdown, writeVisibleFatalError } from './runtime/cli-termination';
|
|
6
|
+
import type { OutputBroker } from './runtime/output-broker';
|
|
7
|
+
import { detectOutputMode } from './runtime/output-mode';
|
|
8
|
+
import { createInteractiveCliSession } from './runtime/interactive-session';
|
|
9
|
+
import { createShutdownController } from './runtime/shutdown-controller';
|
|
10
|
+
import type { EventProjectionStore } from './state/event-projection-store';
|
|
11
|
+
|
|
12
|
+
async function main() {
|
|
13
|
+
const parsedLocalFlags = parseCliLocalFlags(process.argv.slice(2));
|
|
14
|
+
const outputMode = detectOutputMode({ flags: parsedLocalFlags.flags });
|
|
15
|
+
|
|
16
|
+
let broker: OutputBroker | undefined;
|
|
17
|
+
let store: EventProjectionStore | undefined;
|
|
18
|
+
let detachEvents: (() => void) | undefined;
|
|
19
|
+
let interactiveCleanup: ((options?: { clearPresenter?: boolean }) => void) | undefined;
|
|
20
|
+
|
|
21
|
+
const cleanupCliResources = (options: { clearPresenter?: boolean } = {}) => {
|
|
22
|
+
const clearPresenter = options.clearPresenter ?? true;
|
|
23
|
+
detachEvents?.();
|
|
24
|
+
detachEvents = undefined;
|
|
25
|
+
resetCliOutputSink();
|
|
26
|
+
interactiveCleanup?.({ clearPresenter });
|
|
27
|
+
interactiveCleanup = undefined;
|
|
28
|
+
broker = undefined;
|
|
29
|
+
store = undefined;
|
|
30
|
+
};
|
|
31
|
+
|
|
32
|
+
if (outputMode.interactive) {
|
|
33
|
+
const session = await createInteractiveCliSession();
|
|
34
|
+
broker = session.broker;
|
|
35
|
+
store = session.store;
|
|
36
|
+
interactiveCleanup = session.cleanup;
|
|
37
|
+
setCliOutputSink(session.sink);
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
let runtime: CliRuntimeResult | undefined;
|
|
41
|
+
let tunnelClient: TunnelClient | undefined;
|
|
42
|
+
|
|
43
|
+
const shutdownController = createShutdownController({
|
|
44
|
+
timeoutMs: 10_000,
|
|
45
|
+
gracefulShutdown: async (signal) => {
|
|
46
|
+
await performGracefulShutdown({ runtime, tunnelClient, store }, signal);
|
|
47
|
+
},
|
|
48
|
+
cleanup: async () => {
|
|
49
|
+
cleanupCliResources();
|
|
50
|
+
},
|
|
51
|
+
});
|
|
52
|
+
|
|
53
|
+
shutdownController.install();
|
|
54
|
+
|
|
55
|
+
try {
|
|
56
|
+
const result = await runCli(parsedLocalFlags.forwardedArgs);
|
|
57
|
+
runtime = result as CliRuntimeResult | undefined;
|
|
58
|
+
|
|
59
|
+
if (!runtime) {
|
|
60
|
+
shutdownController.dispose();
|
|
61
|
+
cleanupCliResources();
|
|
62
|
+
return;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
if (store) {
|
|
66
|
+
detachEvents = store.attachEmitter(runtime.events);
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
// If pm2 is used, result is void
|
|
70
|
+
if (runtime?.config.proxyHost && runtime.config.proxyToken) {
|
|
71
|
+
const log = (level: 'info' | 'warn' | 'error', message: string) => {
|
|
72
|
+
if (broker) {
|
|
73
|
+
broker.write(level, message);
|
|
74
|
+
return;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
if (level === 'warn') {
|
|
78
|
+
console.warn(message);
|
|
79
|
+
return;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
if (level === 'error') {
|
|
83
|
+
console.error(message);
|
|
84
|
+
return;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
console.log(message);
|
|
88
|
+
};
|
|
89
|
+
|
|
90
|
+
log('info', `[CLI] Starting TunnelClient connecting to ${runtime.config.proxyHost}...`);
|
|
91
|
+
tunnelClient = new TunnelClient({
|
|
92
|
+
proxyHost: runtime.config.proxyHost,
|
|
93
|
+
proxyToken: runtime.config.proxyToken,
|
|
94
|
+
sessionId: runtime.config.sessionId,
|
|
95
|
+
localSessionPort: runtime.config.port,
|
|
96
|
+
log,
|
|
97
|
+
});
|
|
98
|
+
tunnelClient.connect();
|
|
99
|
+
}
|
|
100
|
+
} catch (err: unknown) {
|
|
101
|
+
const message = err instanceof Error ? `${err.message}${err.stack ? `\n${err.stack}` : ''}` : String(err);
|
|
102
|
+
store?.projectStatus({ phase: 'error', detail: message });
|
|
103
|
+
shutdownController.dispose();
|
|
104
|
+
if (broker) {
|
|
105
|
+
broker.write('error', `Fatal error: ${message}`);
|
|
106
|
+
writeVisibleFatalError(message, (rawMessage) => broker?.writeRawStderr(rawMessage));
|
|
107
|
+
cleanupCliResources({ clearPresenter: false });
|
|
108
|
+
} else {
|
|
109
|
+
console.error('Fatal error:', err);
|
|
110
|
+
}
|
|
111
|
+
process.exit(1);
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
main();
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
|
|
3
|
+
const OutputModeOverrideSchema = z.enum(['interactive', 'plain']);
|
|
4
|
+
|
|
5
|
+
export const CliLocalFlagsSchema = z.object({
|
|
6
|
+
outputMode: OutputModeOverrideSchema.optional(),
|
|
7
|
+
});
|
|
8
|
+
|
|
9
|
+
export type CliLocalFlags = z.infer<typeof CliLocalFlagsSchema>;
|
|
10
|
+
|
|
11
|
+
export interface ParsedCliLocalFlags {
|
|
12
|
+
flags: CliLocalFlags;
|
|
13
|
+
forwardedArgs: string[];
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export function parseCliLocalFlags(argv: string[]): ParsedCliLocalFlags {
|
|
17
|
+
const forwardedArgs: string[] = [];
|
|
18
|
+
let outputMode: CliLocalFlags['outputMode'];
|
|
19
|
+
|
|
20
|
+
for (let index = 0; index < argv.length; index += 1) {
|
|
21
|
+
const arg = argv[index];
|
|
22
|
+
|
|
23
|
+
if (arg === '--interactive') {
|
|
24
|
+
outputMode = 'interactive';
|
|
25
|
+
continue;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
if (arg === '--non-interactive') {
|
|
29
|
+
outputMode = 'plain';
|
|
30
|
+
continue;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
if (arg === '--output-mode') {
|
|
34
|
+
const value = argv[index + 1];
|
|
35
|
+
outputMode = OutputModeOverrideSchema.parse(value);
|
|
36
|
+
index += 1;
|
|
37
|
+
continue;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
const match = arg.match(/^--output-mode=(interactive|plain)$/);
|
|
41
|
+
if (match) {
|
|
42
|
+
outputMode = OutputModeOverrideSchema.parse(match[1]);
|
|
43
|
+
continue;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
forwardedArgs.push(arg);
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
return {
|
|
50
|
+
flags: CliLocalFlagsSchema.parse({ outputMode }),
|
|
51
|
+
forwardedArgs,
|
|
52
|
+
};
|
|
53
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
export { runCli as main, startCli as start, parseCliArgs } from '@open-wa/wa-automate';
|
|
2
|
+
export { parseCliLocalFlags } from './config/cli-flags-schema';
|
|
3
|
+
export { createOutputBroker, OutputBroker } from './runtime/output-broker';
|
|
4
|
+
export { CliShutdownError, performGracefulShutdown, writeVisibleFatalError } from './runtime/cli-termination';
|
|
5
|
+
export { detectOutputMode } from './runtime/output-mode';
|
|
6
|
+
export { createShutdownController, ShutdownController } from './runtime/shutdown-controller';
|
|
7
|
+
export { createEventProjectionStore, EventProjectionStore } from './state/event-projection-store';
|
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
import QRCode from 'qrcode';
|
|
2
|
+
import type { EventProjectionStore, ProjectionSnapshot } from '../state/event-projection-store';
|
|
3
|
+
|
|
4
|
+
export interface InteractiveTerminalPresenterOptions {
|
|
5
|
+
store: EventProjectionStore;
|
|
6
|
+
stdout?: NodeJS.WriteStream;
|
|
7
|
+
stderr?: NodeJS.WriteStream;
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
type InkInstance = {
|
|
11
|
+
clear?: () => void;
|
|
12
|
+
rerender?: (tree: unknown) => void;
|
|
13
|
+
unmount: () => void;
|
|
14
|
+
};
|
|
15
|
+
|
|
16
|
+
export class InteractiveTerminalPresenter {
|
|
17
|
+
private readonly store: EventProjectionStore;
|
|
18
|
+
private readonly stdout: NodeJS.WriteStream;
|
|
19
|
+
private readonly stderr: NodeJS.WriteStream;
|
|
20
|
+
private ink?: InkInstance;
|
|
21
|
+
private unsubscribe?: () => void;
|
|
22
|
+
private started = false;
|
|
23
|
+
private stopped = false;
|
|
24
|
+
private snapshot: ProjectionSnapshot;
|
|
25
|
+
private qrAscii?: string;
|
|
26
|
+
private qrValue?: string;
|
|
27
|
+
private renderTree?: () => unknown;
|
|
28
|
+
private qrSequence = 0;
|
|
29
|
+
|
|
30
|
+
constructor(options: InteractiveTerminalPresenterOptions) {
|
|
31
|
+
this.store = options.store;
|
|
32
|
+
this.stdout = options.stdout ?? process.stdout;
|
|
33
|
+
this.stderr = options.stderr ?? process.stderr;
|
|
34
|
+
this.snapshot = this.store.getSnapshot();
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
async start(): Promise<void> {
|
|
38
|
+
if (this.started) {
|
|
39
|
+
return;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
this.started = true;
|
|
43
|
+
|
|
44
|
+
const React = await import('react');
|
|
45
|
+
const ink = await import('ink');
|
|
46
|
+
|
|
47
|
+
await this.updateQrAscii(this.snapshot);
|
|
48
|
+
|
|
49
|
+
const LogStream = ({ snapshot }: { snapshot: ProjectionSnapshot }) => {
|
|
50
|
+
if (snapshot.recentLogs.length === 0) {
|
|
51
|
+
return null;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
return React.createElement(
|
|
55
|
+
ink.Box,
|
|
56
|
+
{ flexDirection: 'column', marginTop: 1 },
|
|
57
|
+
React.createElement(ink.Text, { color: 'cyan' }, 'Recent Logs'),
|
|
58
|
+
...snapshot.recentLogs.slice(-12).map((entry, index) =>
|
|
59
|
+
React.createElement(
|
|
60
|
+
ink.Text,
|
|
61
|
+
{
|
|
62
|
+
key: `${entry.timestamp}-${index}`,
|
|
63
|
+
color: entry.level === 'error' ? 'red' : entry.level === 'warn' ? 'yellow' : 'white',
|
|
64
|
+
},
|
|
65
|
+
`[${entry.level}] ${entry.message}`
|
|
66
|
+
)
|
|
67
|
+
)
|
|
68
|
+
);
|
|
69
|
+
};
|
|
70
|
+
|
|
71
|
+
const QrBlock = ({ snapshot, qrAscii }: { snapshot: ProjectionSnapshot; qrAscii?: string }) => {
|
|
72
|
+
if (!snapshot.qr) {
|
|
73
|
+
return null;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
if (!qrAscii) {
|
|
77
|
+
return React.createElement(ink.Text, { color: 'yellow' }, 'Generating QR view...');
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
const qrLines = qrAscii.split('\n');
|
|
81
|
+
|
|
82
|
+
return React.createElement(
|
|
83
|
+
ink.Box,
|
|
84
|
+
{ flexDirection: 'column', marginTop: 1 },
|
|
85
|
+
React.createElement(ink.Text, { color: 'green' }, 'QR Code'),
|
|
86
|
+
...qrLines.map((line, index) => React.createElement(ink.Text, { key: `qr-${index}` }, line))
|
|
87
|
+
);
|
|
88
|
+
};
|
|
89
|
+
|
|
90
|
+
const App = ({ snapshot, qrAscii }: { snapshot: ProjectionSnapshot; qrAscii?: string }) =>
|
|
91
|
+
React.createElement(
|
|
92
|
+
ink.Box,
|
|
93
|
+
{ flexDirection: 'column', paddingX: 1 },
|
|
94
|
+
React.createElement(ink.Text, { color: 'greenBright' }, '[VT-OS] OPEN-WA CLI'),
|
|
95
|
+
React.createElement(ink.Text, null, 'Mode: ink-interactive'),
|
|
96
|
+
React.createElement(ink.Text, null, `Phase: ${snapshot.phase}`),
|
|
97
|
+
React.createElement(ink.Text, null, `Session: ${snapshot.sessionId ?? 'pending'}`),
|
|
98
|
+
React.createElement(ink.Text, null, `Ready: ${snapshot.ready ? 'yes' : 'no'}`),
|
|
99
|
+
React.createElement(ink.Text, null, `Messages: ${snapshot.messageCount} | Ack updates: ${snapshot.ackCount}`),
|
|
100
|
+
snapshot.detail
|
|
101
|
+
? React.createElement(ink.Text, { color: snapshot.phase === 'error' ? 'red' : 'yellow' }, `Detail: ${snapshot.detail}`)
|
|
102
|
+
: null,
|
|
103
|
+
React.createElement(QrBlock, { snapshot, qrAscii }),
|
|
104
|
+
React.createElement(LogStream, { snapshot })
|
|
105
|
+
);
|
|
106
|
+
|
|
107
|
+
this.renderTree = () => React.createElement(App, { snapshot: this.snapshot, qrAscii: this.qrAscii });
|
|
108
|
+
|
|
109
|
+
this.ink = ink.render(this.renderTree(), {
|
|
110
|
+
stdout: this.stdout,
|
|
111
|
+
stderr: this.stderr,
|
|
112
|
+
patchConsole: false,
|
|
113
|
+
exitOnCtrlC: false,
|
|
114
|
+
}) as InkInstance;
|
|
115
|
+
|
|
116
|
+
this.unsubscribe = this.store.subscribe((snapshot) => {
|
|
117
|
+
void this.handleSnapshot(snapshot);
|
|
118
|
+
});
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
stop(options: { clear?: boolean } = {}): void {
|
|
122
|
+
if (this.stopped) {
|
|
123
|
+
return;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
this.stopped = true;
|
|
127
|
+
const clear = options.clear ?? true;
|
|
128
|
+
this.unsubscribe?.();
|
|
129
|
+
this.unsubscribe = undefined;
|
|
130
|
+
|
|
131
|
+
if (clear) {
|
|
132
|
+
this.ink?.clear?.();
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
this.ink?.unmount();
|
|
136
|
+
this.ink = undefined;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
private async handleSnapshot(snapshot: ProjectionSnapshot): Promise<void> {
|
|
140
|
+
if (this.stopped) {
|
|
141
|
+
return;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
this.snapshot = snapshot;
|
|
145
|
+
await this.updateQrAscii(snapshot);
|
|
146
|
+
this.rerender();
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
private rerender(): void {
|
|
150
|
+
if (this.stopped || !this.renderTree) {
|
|
151
|
+
return;
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
this.ink?.rerender?.(this.renderTree());
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
private async updateQrAscii(snapshot: ProjectionSnapshot): Promise<void> {
|
|
158
|
+
if (!snapshot.qr?.qr) {
|
|
159
|
+
this.qrValue = undefined;
|
|
160
|
+
this.qrAscii = undefined;
|
|
161
|
+
return;
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
if (snapshot.qr.qr === this.qrValue && this.qrAscii) {
|
|
165
|
+
return;
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
this.qrValue = snapshot.qr.qr;
|
|
169
|
+
const sequence = ++this.qrSequence;
|
|
170
|
+
const qrAscii = await QRCode.toString(snapshot.qr.qr, { type: 'terminal', small: true });
|
|
171
|
+
|
|
172
|
+
if (this.stopped || sequence !== this.qrSequence) {
|
|
173
|
+
return;
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
this.qrAscii = qrAscii;
|
|
177
|
+
}
|
|
178
|
+
}
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import type { CliRuntimeResult } from '@open-wa/wa-automate';
|
|
2
|
+
import type { EventProjectionStore } from '../state/event-projection-store';
|
|
3
|
+
|
|
4
|
+
export interface ShutdownRuntimeState {
|
|
5
|
+
runtime?: CliRuntimeResult;
|
|
6
|
+
tunnelClient?: {
|
|
7
|
+
disconnect(): void;
|
|
8
|
+
};
|
|
9
|
+
store?: EventProjectionStore;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export class CliShutdownError extends AggregateError {
|
|
13
|
+
constructor(errors: Error[], signal: NodeJS.Signals) {
|
|
14
|
+
super(errors, `Graceful shutdown completed with ${errors.length} teardown error(s) after ${signal}`);
|
|
15
|
+
this.name = 'CliShutdownError';
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
function normalizeError(error: unknown, fallback: string): Error {
|
|
20
|
+
if (error instanceof Error) {
|
|
21
|
+
return error;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
return new Error(`${fallback}: ${String(error)}`);
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export async function performGracefulShutdown(state: ShutdownRuntimeState, signal: NodeJS.Signals): Promise<void> {
|
|
28
|
+
const { runtime, tunnelClient, store } = state;
|
|
29
|
+
const errors: Error[] = [];
|
|
30
|
+
|
|
31
|
+
store?.projectStatus({ phase: 'shutdown.starting', detail: `Received ${signal}` });
|
|
32
|
+
|
|
33
|
+
if (runtime) {
|
|
34
|
+
try {
|
|
35
|
+
await runtime.server.stop();
|
|
36
|
+
} catch (error) {
|
|
37
|
+
errors.push(normalizeError(error, 'server.stop failed'));
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
if (tunnelClient) {
|
|
42
|
+
try {
|
|
43
|
+
tunnelClient.disconnect();
|
|
44
|
+
} catch (error) {
|
|
45
|
+
errors.push(normalizeError(error, 'tunnel.disconnect failed'));
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
if (runtime) {
|
|
50
|
+
try {
|
|
51
|
+
await runtime.client.stop(`signal:${signal}`);
|
|
52
|
+
} catch (error) {
|
|
53
|
+
errors.push(normalizeError(error, 'client.stop failed'));
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
store?.projectStatus({ phase: 'shutdown.complete', detail: `Shutdown completed after ${signal}` });
|
|
58
|
+
|
|
59
|
+
if (errors.length > 0) {
|
|
60
|
+
throw new CliShutdownError(errors, signal);
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export function writeVisibleFatalError(message: string, writeRawStderr: (message: string) => void): void {
|
|
65
|
+
writeRawStderr(`\nFatal error: ${message}\n`);
|
|
66
|
+
}
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import type { CliOutputEntry, CliOutputSink, CliQrPayload, CliStatusUpdate } from '@open-wa/wa-automate';
|
|
2
|
+
import type { OutputBroker } from './output-broker';
|
|
3
|
+
import { createOutputBroker } from './output-broker';
|
|
4
|
+
import type { EventProjectionStore } from '../state/event-projection-store';
|
|
5
|
+
import { createEventProjectionStore } from '../state/event-projection-store';
|
|
6
|
+
import { InteractiveTerminalPresenter } from '../presenter/interactive-terminal';
|
|
7
|
+
|
|
8
|
+
export interface InteractiveCliSession {
|
|
9
|
+
broker: OutputBroker;
|
|
10
|
+
store: EventProjectionStore;
|
|
11
|
+
presenter: InteractiveTerminalPresenter;
|
|
12
|
+
sink: CliOutputSink;
|
|
13
|
+
cleanup: (options?: { clearPresenter?: boolean }) => void;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
function createBrokeredSink(broker: OutputBroker, store: EventProjectionStore): CliOutputSink {
|
|
17
|
+
return {
|
|
18
|
+
write(entry: CliOutputEntry) {
|
|
19
|
+
broker.write(entry.level, entry.message);
|
|
20
|
+
},
|
|
21
|
+
status(update: CliStatusUpdate) {
|
|
22
|
+
store.projectStatus(update);
|
|
23
|
+
},
|
|
24
|
+
qr(payload: CliQrPayload) {
|
|
25
|
+
store.projectQr(payload);
|
|
26
|
+
broker.write('info', `QR code generated for session ${payload.sessionId}`);
|
|
27
|
+
},
|
|
28
|
+
};
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export async function createInteractiveCliSession(): Promise<InteractiveCliSession> {
|
|
32
|
+
const broker = createOutputBroker({
|
|
33
|
+
interactive: true,
|
|
34
|
+
maxEntries: 200,
|
|
35
|
+
passthrough: false,
|
|
36
|
+
interceptStreams: false,
|
|
37
|
+
});
|
|
38
|
+
broker.install();
|
|
39
|
+
|
|
40
|
+
const store = createEventProjectionStore({ maxLogs: 200, eventDebounceMs: 100 });
|
|
41
|
+
const detachLogs = broker.subscribe((entry) => {
|
|
42
|
+
store.projectLog(entry);
|
|
43
|
+
});
|
|
44
|
+
|
|
45
|
+
const presenter = new InteractiveTerminalPresenter({
|
|
46
|
+
store,
|
|
47
|
+
stdout: process.stdout,
|
|
48
|
+
stderr: process.stderr,
|
|
49
|
+
});
|
|
50
|
+
|
|
51
|
+
await presenter.start();
|
|
52
|
+
|
|
53
|
+
return {
|
|
54
|
+
broker,
|
|
55
|
+
store,
|
|
56
|
+
presenter,
|
|
57
|
+
sink: createBrokeredSink(broker, store),
|
|
58
|
+
cleanup: (options = {}) => {
|
|
59
|
+
detachLogs();
|
|
60
|
+
presenter.stop({ clear: options.clearPresenter ?? true });
|
|
61
|
+
broker.dispose();
|
|
62
|
+
},
|
|
63
|
+
};
|
|
64
|
+
}
|