@open-wa/cli 5.0.0-alpha.8 → 5.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.
@@ -1,66 +0,0 @@
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
- }
@@ -1,64 +0,0 @@
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
- }
@@ -1,193 +0,0 @@
1
- export type BrokerLevel = 'debug' | 'info' | 'warn' | 'error';
2
- export type BrokerSource = 'console' | 'stdout' | 'stderr' | 'runtime';
3
-
4
- export interface BrokerEntry {
5
- level: BrokerLevel;
6
- message: string;
7
- source: BrokerSource;
8
- timestamp: number;
9
- }
10
-
11
- export interface OutputBrokerOptions {
12
- interactive: boolean;
13
- maxEntries?: number;
14
- passthrough?: boolean;
15
- interceptStreams?: boolean;
16
- }
17
-
18
- type Subscriber = (entry: BrokerEntry) => void;
19
- type ConsoleMethod = (...args: unknown[]) => void;
20
- type StreamWrite = (chunk: any, encoding?: BufferEncoding | ((error?: Error | null) => void), callback?: (error?: Error | null) => void) => boolean;
21
-
22
- function stringifyArgs(args: unknown[]): string {
23
- return args
24
- .map((arg) => {
25
- if (typeof arg === 'string') {
26
- return arg;
27
- }
28
-
29
- if (arg instanceof Error) {
30
- return arg.stack ?? arg.message;
31
- }
32
-
33
- if (typeof arg === 'object' && arg !== null) {
34
- try {
35
- return JSON.stringify(arg);
36
- } catch {
37
- return String(arg);
38
- }
39
- }
40
-
41
- return String(arg);
42
- })
43
- .join(' ');
44
- }
45
-
46
- export class OutputBroker {
47
- private readonly interactive: boolean;
48
- private readonly maxEntries: number;
49
- private readonly passthrough: boolean;
50
- private readonly interceptStreams: boolean;
51
- private readonly entries: BrokerEntry[] = [];
52
- private readonly subscribers = new Set<Subscriber>();
53
- private installed = false;
54
- private originalConsole?: {
55
- log: ConsoleMethod;
56
- warn: ConsoleMethod;
57
- error: ConsoleMethod;
58
- };
59
- private originalWrites?: {
60
- stdout: StreamWrite;
61
- stderr: StreamWrite;
62
- };
63
-
64
- constructor(options: OutputBrokerOptions) {
65
- this.interactive = options.interactive;
66
- this.maxEntries = options.maxEntries ?? 200;
67
- this.passthrough = options.passthrough ?? !options.interactive;
68
- this.interceptStreams = options.interceptStreams ?? true;
69
- }
70
-
71
- install(): void {
72
- if (this.installed) {
73
- return;
74
- }
75
-
76
- this.installed = true;
77
- this.originalConsole = {
78
- log: console.log.bind(console),
79
- warn: console.warn.bind(console),
80
- error: console.error.bind(console),
81
- };
82
- this.originalWrites = {
83
- stdout: process.stdout.write.bind(process.stdout),
84
- stderr: process.stderr.write.bind(process.stderr),
85
- };
86
-
87
- console.log = (...args: unknown[]) => {
88
- this.forward('info', 'console', stringifyArgs(args), () => this.originalConsole?.log(...args));
89
- };
90
- console.warn = (...args: unknown[]) => {
91
- this.forward('warn', 'console', stringifyArgs(args), () => this.originalConsole?.warn(...args));
92
- };
93
- console.error = (...args: unknown[]) => {
94
- this.forward('error', 'console', stringifyArgs(args), () => this.originalConsole?.error(...args));
95
- };
96
-
97
- if (this.interceptStreams) {
98
- process.stdout.write = ((chunk: any, encoding?: BufferEncoding | ((error?: Error | null) => void), callback?: (error?: Error | null) => void) => {
99
- const message = Buffer.isBuffer(chunk) ? chunk.toString('utf8') : String(chunk);
100
- this.forward('info', 'stdout', message, () => this.originalWrites?.stdout(chunk, encoding as any, callback));
101
- if (this.interactive && !this.passthrough) {
102
- if (typeof encoding === 'function') {
103
- encoding(undefined);
104
- } else {
105
- callback?.(undefined);
106
- }
107
- }
108
- return true;
109
- }) as StreamWrite;
110
-
111
- process.stderr.write = ((chunk: any, encoding?: BufferEncoding | ((error?: Error | null) => void), callback?: (error?: Error | null) => void) => {
112
- const message = Buffer.isBuffer(chunk) ? chunk.toString('utf8') : String(chunk);
113
- this.forward('error', 'stderr', message, () => this.originalWrites?.stderr(chunk, encoding as any, callback));
114
- if (this.interactive && !this.passthrough) {
115
- if (typeof encoding === 'function') {
116
- encoding(undefined);
117
- } else {
118
- callback?.(undefined);
119
- }
120
- }
121
- return true;
122
- }) as StreamWrite;
123
- }
124
- }
125
-
126
- dispose(): void {
127
- if (!this.installed) {
128
- return;
129
- }
130
-
131
- if (this.originalConsole) {
132
- console.log = this.originalConsole.log;
133
- console.warn = this.originalConsole.warn;
134
- console.error = this.originalConsole.error;
135
- }
136
-
137
- if (this.originalWrites && this.interceptStreams) {
138
- process.stdout.write = this.originalWrites.stdout as typeof process.stdout.write;
139
- process.stderr.write = this.originalWrites.stderr as typeof process.stderr.write;
140
- }
141
-
142
- this.installed = false;
143
- }
144
-
145
- subscribe(listener: Subscriber): () => void {
146
- this.subscribers.add(listener);
147
- return () => {
148
- this.subscribers.delete(listener);
149
- };
150
- }
151
-
152
- getEntries(): BrokerEntry[] {
153
- return [...this.entries];
154
- }
155
-
156
- writeRawStdout(message: string): void {
157
- this.originalWrites?.stdout(message);
158
- }
159
-
160
- writeRawStderr(message: string): void {
161
- this.originalWrites?.stderr(message);
162
- }
163
-
164
- write(level: BrokerLevel, message: string, source: BrokerSource = 'runtime'): void {
165
- this.forward(level, source, message);
166
- }
167
-
168
- private forward(level: BrokerLevel, source: BrokerSource, message: string, passthroughWriter?: () => void): void {
169
- const entry: BrokerEntry = {
170
- level,
171
- source,
172
- message,
173
- timestamp: Date.now(),
174
- };
175
-
176
- this.entries.push(entry);
177
- if (this.entries.length > this.maxEntries) {
178
- this.entries.splice(0, this.entries.length - this.maxEntries);
179
- }
180
-
181
- for (const subscriber of this.subscribers) {
182
- subscriber(entry);
183
- }
184
-
185
- if (!this.interactive || this.passthrough) {
186
- passthroughWriter?.();
187
- }
188
- }
189
- }
190
-
191
- export function createOutputBroker(options: OutputBrokerOptions): OutputBroker {
192
- return new OutputBroker(options);
193
- }
@@ -1,73 +0,0 @@
1
- import type { CliLocalFlags } from '../config/cli-flags-schema';
2
-
3
- export type OutputModeKind = 'interactive' | 'plain';
4
-
5
- export interface OutputModeContract {
6
- kind: OutputModeKind;
7
- interactive: boolean;
8
- reason:
9
- | 'flag.interactive'
10
- | 'flag.plain'
11
- | 'stdin-not-tty'
12
- | 'stdout-not-tty'
13
- | 'stderr-not-tty'
14
- | 'term-dumb'
15
- | 'ci'
16
- | 'no-color'
17
- | 'env.non-interactive'
18
- | 'tty-ready';
19
- }
20
-
21
- export interface DetectOutputModeOptions {
22
- flags?: CliLocalFlags;
23
- env?: NodeJS.ProcessEnv;
24
- stdin?: Pick<NodeJS.ReadStream, 'isTTY'>;
25
- stdout?: Pick<NodeJS.WriteStream, 'isTTY'>;
26
- stderr?: Pick<NodeJS.WriteStream, 'isTTY'>;
27
- }
28
-
29
- export function detectOutputMode(options: DetectOutputModeOptions = {}): OutputModeContract {
30
- const env = options.env ?? process.env;
31
- const stdin = options.stdin ?? process.stdin;
32
- const stdout = options.stdout ?? process.stdout;
33
- const stderr = options.stderr ?? process.stderr;
34
- const forcedMode = options.flags?.outputMode;
35
-
36
- if (forcedMode === 'plain') {
37
- return { kind: 'plain', interactive: false, reason: 'flag.plain' };
38
- }
39
-
40
- if (!stdin.isTTY) {
41
- return { kind: 'plain', interactive: false, reason: 'stdin-not-tty' };
42
- }
43
-
44
- if (!stdout.isTTY) {
45
- return { kind: 'plain', interactive: false, reason: 'stdout-not-tty' };
46
- }
47
-
48
- if (!stderr.isTTY) {
49
- return { kind: 'plain', interactive: false, reason: 'stderr-not-tty' };
50
- }
51
-
52
- if (env.TERM === 'dumb') {
53
- return { kind: 'plain', interactive: false, reason: 'term-dumb' };
54
- }
55
-
56
- if (env.OPEN_WA_NON_INTERACTIVE === '1') {
57
- return { kind: 'plain', interactive: false, reason: 'env.non-interactive' };
58
- }
59
-
60
- if (env.CI) {
61
- return { kind: 'plain', interactive: false, reason: 'ci' };
62
- }
63
-
64
- if (env.NO_COLOR) {
65
- return { kind: 'plain', interactive: false, reason: 'no-color' };
66
- }
67
-
68
- if (forcedMode === 'interactive') {
69
- return { kind: 'interactive', interactive: true, reason: 'flag.interactive' };
70
- }
71
-
72
- return { kind: 'interactive', interactive: true, reason: 'tty-ready' };
73
- }
@@ -1,86 +0,0 @@
1
- export interface ShutdownControllerOptions {
2
- timeoutMs?: number;
3
- gracefulShutdown: (signal: NodeJS.Signals) => Promise<void>;
4
- cleanup?: () => void | Promise<void>;
5
- exit?: (code: number) => never | void;
6
- }
7
-
8
- export class ShutdownController {
9
- private readonly timeoutMs: number;
10
- private readonly gracefulShutdown: (signal: NodeJS.Signals) => Promise<void>;
11
- private readonly cleanup?: () => void | Promise<void>;
12
- private readonly exit: (code: number) => never | void;
13
- private installed = false;
14
- private shuttingDown = false;
15
- private cleanupStarted = false;
16
- private readonly boundSignals = new Map<NodeJS.Signals, () => void>();
17
-
18
- constructor(options: ShutdownControllerOptions) {
19
- this.timeoutMs = options.timeoutMs ?? 10_000;
20
- this.gracefulShutdown = options.gracefulShutdown;
21
- this.cleanup = options.cleanup;
22
- this.exit = options.exit ?? ((code: number) => process.exit(code));
23
- }
24
-
25
- install(signals: NodeJS.Signals[] = ['SIGINT', 'SIGTERM']): void {
26
- if (this.installed) {
27
- return;
28
- }
29
-
30
- for (const signal of signals) {
31
- const handler = () => {
32
- void this.handleSignal(signal);
33
- };
34
- this.boundSignals.set(signal, handler);
35
- process.on(signal, handler);
36
- }
37
-
38
- this.installed = true;
39
- }
40
-
41
- dispose(): void {
42
- for (const [signal, handler] of this.boundSignals.entries()) {
43
- process.off(signal, handler);
44
- }
45
- this.boundSignals.clear();
46
- this.installed = false;
47
- }
48
-
49
- async handleSignal(signal: NodeJS.Signals): Promise<void> {
50
- if (this.shuttingDown) {
51
- await this.runCleanup();
52
- this.exit(1);
53
- return;
54
- }
55
-
56
- this.shuttingDown = true;
57
-
58
- try {
59
- await Promise.race([
60
- this.gracefulShutdown(signal),
61
- new Promise<never>((_, reject) => {
62
- setTimeout(() => reject(new Error(`Graceful shutdown timed out after ${this.timeoutMs}ms`)), this.timeoutMs);
63
- }),
64
- ]);
65
-
66
- await this.runCleanup();
67
- this.exit(0);
68
- } catch {
69
- await this.runCleanup();
70
- this.exit(1);
71
- }
72
- }
73
-
74
- private async runCleanup(): Promise<void> {
75
- if (this.cleanupStarted) {
76
- return;
77
- }
78
-
79
- this.cleanupStarted = true;
80
- await this.cleanup?.();
81
- }
82
- }
83
-
84
- export function createShutdownController(options: ShutdownControllerOptions): ShutdownController {
85
- return new ShutdownController(options);
86
- }
@@ -1,166 +0,0 @@
1
- import type { HyperEmitter } from '@open-wa/hyperemitter';
2
- import type { OpenWAEventMap } from '@open-wa/core';
3
- import type { BrokerEntry } from '../runtime/output-broker';
4
- import type { CliQrPayload, CliStatusUpdate } from '@open-wa/wa-automate';
5
-
6
- export interface ProjectionSnapshot {
7
- phase: string;
8
- sessionId?: string;
9
- detail?: string;
10
- qr?: CliQrPayload;
11
- recentLogs: BrokerEntry[];
12
- messageCount: number;
13
- ackCount: number;
14
- ready: boolean;
15
- lastEventAt?: number;
16
- }
17
-
18
- export interface EventProjectionStoreOptions {
19
- maxLogs?: number;
20
- eventDebounceMs?: number;
21
- }
22
-
23
- type ProjectionListener = (snapshot: ProjectionSnapshot) => void;
24
- type RuntimeEventName = 'message.received' | 'ack.changed' | 'core.starting' | 'core.stopping' | 'core.stopped' | 'client.ready' | 'launch.auth.qr.generated';
25
-
26
- export class EventProjectionStore {
27
- private readonly maxLogs: number;
28
- private readonly eventDebounceMs: number;
29
- private readonly listeners = new Set<ProjectionListener>();
30
- private readonly state: ProjectionSnapshot = {
31
- phase: 'boot',
32
- recentLogs: [],
33
- messageCount: 0,
34
- ackCount: 0,
35
- ready: false,
36
- };
37
- private pendingMessageCount = 0;
38
- private pendingAckCount = 0;
39
- private flushTimer?: NodeJS.Timeout;
40
-
41
- constructor(options: EventProjectionStoreOptions = {}) {
42
- this.maxLogs = options.maxLogs ?? 200;
43
- this.eventDebounceMs = options.eventDebounceMs ?? 100;
44
- }
45
-
46
- subscribe(listener: ProjectionListener): () => void {
47
- this.listeners.add(listener);
48
- listener(this.getSnapshot());
49
- return () => {
50
- this.listeners.delete(listener);
51
- };
52
- }
53
-
54
- getSnapshot(): ProjectionSnapshot {
55
- return {
56
- ...this.state,
57
- recentLogs: [...this.state.recentLogs],
58
- };
59
- }
60
-
61
- projectLog(entry: BrokerEntry): void {
62
- this.state.recentLogs.push(entry);
63
- if (this.state.recentLogs.length > this.maxLogs) {
64
- this.state.recentLogs.splice(0, this.state.recentLogs.length - this.maxLogs);
65
- }
66
- this.emit();
67
- }
68
-
69
- projectStatus(update: CliStatusUpdate): void {
70
- this.state.phase = update.phase;
71
- this.state.sessionId = update.sessionId ?? this.state.sessionId;
72
- this.state.detail = update.detail;
73
- if (update.phase === 'client.ready') {
74
- this.state.ready = true;
75
- }
76
- if (update.phase === 'shutdown.starting') {
77
- this.state.ready = false;
78
- }
79
- this.emit();
80
- }
81
-
82
- projectQr(payload: CliQrPayload): void {
83
- this.state.phase = 'auth.qr';
84
- this.state.qr = payload;
85
- this.state.sessionId = payload.sessionId;
86
- this.emit();
87
- }
88
-
89
- attachEmitter(emitter: HyperEmitter<OpenWAEventMap>): () => void {
90
- const handlers: Array<[RuntimeEventName, (payload: any) => void]> = [
91
- ['core.starting', () => {
92
- this.state.phase = 'boot';
93
- this.state.lastEventAt = Date.now();
94
- this.emit();
95
- }],
96
- ['core.stopping', () => {
97
- this.state.phase = 'shutdown.starting';
98
- this.state.ready = false;
99
- this.state.lastEventAt = Date.now();
100
- this.emit();
101
- }],
102
- ['core.stopped', () => {
103
- this.state.phase = 'shutdown.complete';
104
- this.state.lastEventAt = Date.now();
105
- this.emit();
106
- }],
107
- ['client.ready', () => {
108
- this.state.phase = 'client.ready';
109
- this.state.ready = true;
110
- this.state.lastEventAt = Date.now();
111
- this.emit();
112
- }],
113
- ['launch.auth.qr.generated', (payload) => {
114
- const qr = payload?.details?.qr;
115
- if (typeof qr === 'string' && this.state.sessionId) {
116
- this.projectQr({ qr, sessionId: this.state.sessionId });
117
- }
118
- }],
119
- ['message.received', () => {
120
- this.pendingMessageCount += 1;
121
- this.scheduleFlush();
122
- }],
123
- ['ack.changed', () => {
124
- this.pendingAckCount += 1;
125
- this.scheduleFlush();
126
- }],
127
- ];
128
-
129
- for (const [event, handler] of handlers) {
130
- emitter.on(event, handler as never);
131
- }
132
-
133
- return () => {
134
- for (const [event, handler] of handlers) {
135
- emitter.off(event, handler as never);
136
- }
137
- };
138
- }
139
-
140
- private scheduleFlush(): void {
141
- if (this.flushTimer) {
142
- return;
143
- }
144
-
145
- this.flushTimer = setTimeout(() => {
146
- this.flushTimer = undefined;
147
- this.state.messageCount += this.pendingMessageCount;
148
- this.state.ackCount += this.pendingAckCount;
149
- this.pendingMessageCount = 0;
150
- this.pendingAckCount = 0;
151
- this.state.lastEventAt = Date.now();
152
- this.emit();
153
- }, this.eventDebounceMs);
154
- }
155
-
156
- private emit(): void {
157
- const snapshot = this.getSnapshot();
158
- for (const listener of this.listeners) {
159
- listener(snapshot);
160
- }
161
- }
162
- }
163
-
164
- export function createEventProjectionStore(options: EventProjectionStoreOptions = {}): EventProjectionStore {
165
- return new EventProjectionStore(options);
166
- }