@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.
@@ -0,0 +1,239 @@
1
+ import { CliQrPayload, CliRuntimeResult, CliStatusUpdate, parseCliArgs, runCli as main, startCli as start } from "@open-wa/wa-automate";
2
+ import { z } from "zod";
3
+ import { EventEmitter } from "node:events";
4
+ import { OpenWAEventMap } from "@open-wa/core";
5
+
6
+ //#region src/config/cli-flags-schema.d.ts
7
+ declare const CliLocalFlagsSchema: z.ZodObject<{
8
+ outputMode: z.ZodOptional<z.ZodEnum<{
9
+ interactive: "interactive";
10
+ plain: "plain";
11
+ }>>;
12
+ }, z.core.$strip>;
13
+ type CliLocalFlags = z.infer<typeof CliLocalFlagsSchema>;
14
+ interface ParsedCliLocalFlags {
15
+ flags: CliLocalFlags;
16
+ forwardedArgs: string[];
17
+ }
18
+ declare function parseCliLocalFlags(argv: string[]): ParsedCliLocalFlags;
19
+ //#endregion
20
+ //#region src/runtime/output-broker.d.ts
21
+ type BrokerLevel = 'debug' | 'info' | 'warn' | 'error';
22
+ type BrokerSource = 'console' | 'stdout' | 'stderr' | 'runtime';
23
+ interface BrokerEntry {
24
+ level: BrokerLevel;
25
+ message: string;
26
+ source: BrokerSource;
27
+ timestamp: number;
28
+ }
29
+ interface OutputBrokerOptions {
30
+ interactive: boolean;
31
+ maxEntries?: number;
32
+ passthrough?: boolean;
33
+ interceptStreams?: boolean;
34
+ }
35
+ type Subscriber = (entry: BrokerEntry) => void;
36
+ declare class OutputBroker {
37
+ private readonly interactive;
38
+ private readonly maxEntries;
39
+ private readonly passthrough;
40
+ private readonly interceptStreams;
41
+ private readonly entries;
42
+ private readonly subscribers;
43
+ private installed;
44
+ private originalConsole?;
45
+ private originalWrites?;
46
+ constructor(options: OutputBrokerOptions);
47
+ install(): void;
48
+ dispose(): void;
49
+ subscribe(listener: Subscriber): () => void;
50
+ getEntries(): BrokerEntry[];
51
+ writeRawStdout(message: string): void;
52
+ writeRawStderr(message: string): void;
53
+ write(level: BrokerLevel, message: string, source?: BrokerSource): void;
54
+ private forward;
55
+ }
56
+ declare function createOutputBroker(options: OutputBrokerOptions): OutputBroker;
57
+ //#endregion
58
+ //#region ../logger/dist/index.d.cts
59
+ //#endregion
60
+ //#region src/core/context.d.ts
61
+ interface LogContext {
62
+ sessionId?: string;
63
+ driver?: 'puppeteer' | 'playwright' | 'remote';
64
+ requestId?: string;
65
+ schemaId?: string;
66
+ 'http.method'?: string;
67
+ 'http.path'?: string;
68
+ 'http.statusCode'?: number;
69
+ 'http.latencyMs'?: number;
70
+ traceId?: string;
71
+ spanId?: string;
72
+ isolateId?: string;
73
+ colo?: string;
74
+ doId?: string;
75
+ [key: string]: unknown;
76
+ }
77
+ //#endregion
78
+ //#region src/core/levels.d.ts
79
+ type LogLevel = 'debug' | 'info' | 'warn' | 'error' | 'fatal'; //#endregion
80
+ //#region src/core/logger.d.ts
81
+ interface LoggerInterface {
82
+ debug(message: string, meta?: LogContext): void;
83
+ info(message: string, meta?: LogContext): void;
84
+ warn(message: string, meta?: LogContext): void;
85
+ error(message: string, meta?: LogContext & {
86
+ error?: unknown;
87
+ }): void;
88
+ fatal(message: string, meta?: LogContext & {
89
+ error?: unknown;
90
+ }): void;
91
+ child(context: LogContext): LoggerInterface;
92
+ withContext(context: LogContext): LoggerInterface;
93
+ setLevel(level: LogLevel): void;
94
+ }
95
+ type Logger = LoggerInterface; //#endregion
96
+ //#region src/security/rules.d.ts
97
+ //#endregion
98
+ //#region ../hyperemitter/dist/index.d.cts
99
+ interface ListenerOptions {
100
+ signal?: AbortSignal;
101
+ weak?: object;
102
+ captureRejections?: boolean;
103
+ }
104
+ interface HyperEmitterOptions {
105
+ delimiter?: string;
106
+ captureRejections?: boolean;
107
+ onError?: (error: unknown) => void;
108
+ debug?: boolean;
109
+ logger?: Logger;
110
+ loggerContext?: LogContext;
111
+ } //#endregion
112
+ //#region src/core/HyperEmitter.d.ts
113
+ declare class HyperEmitter<TMap extends object = Record<string, unknown>> {
114
+ private readonly delimiter;
115
+ private readonly captureRejections;
116
+ private readonly onError?;
117
+ private readonly finalizer?;
118
+ private readonly logger?;
119
+ private readonly debugEnabled;
120
+ private readonly baseLogContext;
121
+ private exactListeners;
122
+ private wildcardTree;
123
+ private wildcardIndex;
124
+ private hasWildcards;
125
+ private anyListeners;
126
+ constructor(options?: HyperEmitterOptions);
127
+ on<K extends keyof TMap & string>(event: K, listener: (payload: TMap[K]) => void | Promise<void>, options?: ListenerOptions): this;
128
+ once<K extends keyof TMap & string>(event: K, listener: (payload: TMap[K]) => void | Promise<void>, options?: ListenerOptions): this;
129
+ off<K extends keyof TMap & string>(event: K, listener: (payload: TMap[K]) => void | Promise<void>): this;
130
+ emit<K extends keyof TMap & string>(event: K, payload: TMap[K]): boolean;
131
+ onAny(listener: (event: string, payload: any) => void): this;
132
+ offAny(listener: (event: string, payload: any) => void): this;
133
+ listenerCount(event?: keyof TMap & string): number;
134
+ removeAllListeners(event?: keyof TMap & string): this;
135
+ fromNodeEmitter(emitter: EventEmitter, event: string): () => void;
136
+ toNodeEmitter(target: EventEmitter): () => void;
137
+ onEventTarget(target: EventTarget, type: string, eventName: keyof TMap & string): () => void;
138
+ private add;
139
+ private dispatch;
140
+ private invoke;
141
+ private offListener;
142
+ private handleRejection;
143
+ private removeWildcard;
144
+ private logDebug;
145
+ } //#endregion
146
+ //#endregion
147
+ //#region src/state/event-projection-store.d.ts
148
+ interface ProjectionSnapshot {
149
+ phase: string;
150
+ sessionId?: string;
151
+ detail?: string;
152
+ qr?: CliQrPayload;
153
+ recentLogs: BrokerEntry[];
154
+ messageCount: number;
155
+ ackCount: number;
156
+ ready: boolean;
157
+ lastEventAt?: number;
158
+ }
159
+ interface EventProjectionStoreOptions {
160
+ maxLogs?: number;
161
+ eventDebounceMs?: number;
162
+ }
163
+ type ProjectionListener = (snapshot: ProjectionSnapshot) => void;
164
+ declare class EventProjectionStore {
165
+ private readonly maxLogs;
166
+ private readonly eventDebounceMs;
167
+ private readonly listeners;
168
+ private readonly state;
169
+ private pendingMessageCount;
170
+ private pendingAckCount;
171
+ private flushTimer?;
172
+ constructor(options?: EventProjectionStoreOptions);
173
+ subscribe(listener: ProjectionListener): () => void;
174
+ getSnapshot(): ProjectionSnapshot;
175
+ projectLog(entry: BrokerEntry): void;
176
+ projectStatus(update: CliStatusUpdate): void;
177
+ projectQr(payload: CliQrPayload): void;
178
+ attachEmitter(emitter: HyperEmitter<OpenWAEventMap>): () => void;
179
+ private scheduleFlush;
180
+ private emit;
181
+ }
182
+ declare function createEventProjectionStore(options?: EventProjectionStoreOptions): EventProjectionStore;
183
+ //#endregion
184
+ //#region src/runtime/cli-termination.d.ts
185
+ interface ShutdownRuntimeState {
186
+ runtime?: CliRuntimeResult;
187
+ tunnelClient?: {
188
+ disconnect(): void;
189
+ };
190
+ store?: EventProjectionStore;
191
+ }
192
+ declare class CliShutdownError extends AggregateError {
193
+ constructor(errors: Error[], signal: NodeJS.Signals);
194
+ }
195
+ declare function performGracefulShutdown(state: ShutdownRuntimeState, signal: NodeJS.Signals): Promise<void>;
196
+ declare function writeVisibleFatalError(message: string, writeRawStderr: (message: string) => void): void;
197
+ //#endregion
198
+ //#region src/runtime/output-mode.d.ts
199
+ type OutputModeKind = 'interactive' | 'plain';
200
+ interface OutputModeContract {
201
+ kind: OutputModeKind;
202
+ interactive: boolean;
203
+ reason: 'flag.interactive' | 'flag.plain' | 'stdin-not-tty' | 'stdout-not-tty' | 'stderr-not-tty' | 'term-dumb' | 'ci' | 'no-color' | 'env.non-interactive' | 'tty-ready';
204
+ }
205
+ interface DetectOutputModeOptions {
206
+ flags?: CliLocalFlags;
207
+ env?: NodeJS.ProcessEnv;
208
+ stdin?: Pick<NodeJS.ReadStream, 'isTTY'>;
209
+ stdout?: Pick<NodeJS.WriteStream, 'isTTY'>;
210
+ stderr?: Pick<NodeJS.WriteStream, 'isTTY'>;
211
+ }
212
+ declare function detectOutputMode(options?: DetectOutputModeOptions): OutputModeContract;
213
+ //#endregion
214
+ //#region src/runtime/shutdown-controller.d.ts
215
+ interface ShutdownControllerOptions {
216
+ timeoutMs?: number;
217
+ gracefulShutdown: (signal: NodeJS.Signals) => Promise<void>;
218
+ cleanup?: () => void | Promise<void>;
219
+ exit?: (code: number) => never | void;
220
+ }
221
+ declare class ShutdownController {
222
+ private readonly timeoutMs;
223
+ private readonly gracefulShutdown;
224
+ private readonly cleanup?;
225
+ private readonly exit;
226
+ private installed;
227
+ private shuttingDown;
228
+ private cleanupStarted;
229
+ private readonly boundSignals;
230
+ constructor(options: ShutdownControllerOptions);
231
+ install(signals?: NodeJS.Signals[]): void;
232
+ dispose(): void;
233
+ handleSignal(signal: NodeJS.Signals): Promise<void>;
234
+ private runCleanup;
235
+ }
236
+ declare function createShutdownController(options: ShutdownControllerOptions): ShutdownController;
237
+ //#endregion
238
+ export { CliShutdownError, EventProjectionStore, OutputBroker, ShutdownController, createEventProjectionStore, createOutputBroker, createShutdownController, detectOutputMode, main, parseCliArgs, parseCliLocalFlags, performGracefulShutdown, start, writeVisibleFatalError };
239
+ //# sourceMappingURL=index.d.cts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.cts","names":["winston","z","Transport","TransportConfigSchema","ZodLiteral","ZodEnum","ZodOptional","core","$strip","ZodObject","ZodString","ZodNumber","ZodDiscriminatedUnion","type","format","json","pretty","simple","path","maxSize","maxFiles","url","username","password","indexPrefix","bufferSize","flushInterval","brokerUrl","queue","LoggerConfigSchema","ZodArray","ZodBoolean","ZodDefault","level","debug","info","warn","error","fatal","transports","includeStack","TransportConfig","infer","LoggerConfig","LogContext","sessionId","driver","requestId","schemaId","traceId","spanId","isolateId","colo","doId","key","LogEvent","timestamp","message","component","name","stack","code","context","LogLevel","rootLogger","Logger","instance","LoggerInterface","meta","child","withContext","setLevel","createLogger","defaultContext","SanitizationRule","RegExp","pattern","strategy","options","keepChars","replacement","Sanitizer","rules","constructor","customRules","sanitize","findRule","applyRule","hash","sanitizeLogContext","createSanitizer","censorEmail","email","censorPhone","phone","censorWid","wid","censorToken","token","visibleChars","censorMessageBody","body","maxLength","censorObject","T","Record","obj","fields","GET_MATCH_RESULT","ParamIndexMap","ParamStash","Params","Result","RequestHeader","ResponseHeader","CustomHeader","InfoStatusCode","SuccessStatusCode","DeprecatedStatusCode","RedirectStatusCode","ClientErrorStatusCode","ServerErrorStatusCode","UnofficialStatusCode","StatusCode","ContentlessStatusCode","ContentfulStatusCode","Exclude","UnionToIntersection","U","k","I","JSONPrimitive","JSONArray","JSONObject","InvalidJSONValue","args","InvalidToNull","IsInvalid","OmitSymbolKeys","K","JSONValue","JSONParsed","TError","ReadonlyArray","J","Set","Map","toJSON","Simplify","KeyType","IsAny","Bindings","Variables","Env","Next","Promise","Input","ResponseFormat","in","out","outputFormat","BlankInput","RouterRoute","H","basePath","method","handler","HandlerResponse","O","Response","TypedResponse","Handler","E","P","R","Context","c","next","MiddlewareHandler","NotFoundResponse","NotFoundHandler","KnownResponseFormat","F","_data","_status","_format","FormValue","Blob","ParsedFormValue","File","ValidationTargets","form","query","param","_","header","cookie","ParamKey","Component","Name","NameWithPattern","Rest","_Pattern","ParamKeys","Path","ParamKeyToRecord","InputToDataByTarget","Target","RemoveQuestion","FetchEventLike","Request","request","respondWith","promise","passThroughOnException","waitUntil","BodyDataValueDot","x","BodyDataValueDotAll","SimplifyBodyData","BodyDataValueComponent","all","BodyDataValueObject","BodyDataValue","dot","BodyData","ParseBodyOptions","Partial","Body","ArrayBuffer","FormData","text","arrayBuffer","blob","formData","BodyCache","HonoRequest","P2","Options","raw","routeIndex","bodyCache","matchResult","queries","parseBody","addValidatedData","target","data","valid","matchedRoutes","routePath","BaseMime","_baseMimes","aac","avi","avif","av1","bin","bmp","css","csv","eot","epub","gif","gz","htm","html","ico","ics","jpeg","jpg","js","jsonld","map","mid","midi","mjs","mp3","mp4","mpeg","oga","ogv","ogx","opus","otf","pdf","png","rtf","svg","tif","tiff","ts","ttf","txt","wasm","webm","weba","webmanifest","webp","woff","woff2","xhtml","xml","zip","gltf","glb","HeaderRecord","Data","ReadableStream","Uint8Array","ExecutionContext","props","exports","ContextVariableMap","ContextRenderer","DefaultRenderer","content","Renderer","Function","PropsForRenderer","Parameters","Required","Props","Layout","Get","Key","Set$1","value","NewResponse","ResponseOrInit","status","headers","init","BodyRespond","TextRespond","JSONRespond","JSONRespondReturn","object","HTMLRespond","ContextOptions","env","executionCtx","notFoundHandler","SetHeadersOptions","append","SetHeaders","ResponseHeadersInit","Headers","ResponseInit","statusText","Error","Readonly","URL","ReturnType","finalized","req","event","res","_res","render","setLayout","layout","getLayout","setRenderer","renderer","set","get","var","newResponse","redirect","location","notFound","honoLogger","banner_d_exports","BannerOptions","show","showProjectBanner","version","subtitle","color","title","spinner_d_exports","fail","start","stop","succeed","update","animated_d_exports","ProgressLogger","ProgressOptions","total","label","current","done","index_d_exports","animated","banner","spinner","createConsoleTransport","Extract","transport","config","createFileTransport","createElasticsearchTransport","createMQTransport","createCloudflareTransport","index_d_exports$1","createTransport","cloudflare","console","elasticsearch","file","mq","terminal","EventEmitter","_$_open_wa_logger0","EventMap","key","EventListener","T","Promise","payload","ListenerOptions","AbortSignal","signal","weak","captureRejections","HyperEmitterOptions","Logger","LogContext","delimiter","onError","error","debug","logger","loggerContext","HyperEmitter","K","TMap","Record","EventTarget","finalizer","debugEnabled","baseLogContext","exactListeners","wildcardTree","wildcardIndex","hasWildcards","anyListeners","constructor","options","on","event","listener","once","off","emit","onAny","offAny","listenerCount","removeAllListeners","fromNodeEmitter","emitter","toNodeEmitter","target","onEventTarget","type","eventName","add","dispatch","invoke","offListener","handleRejection","removeWildcard","logDebug"],"sources":["../src/config/cli-flags-schema.ts","../src/runtime/output-broker.ts","../../logger/dist/index.d.cts","../../hyperemitter/dist/index.d.cts","../src/state/event-projection-store.ts","../src/runtime/cli-termination.ts","../src/runtime/output-mode.ts","../src/runtime/shutdown-controller.ts"],"mappings":";;;;;;cAIa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AAA,CAAO,WAAA;EACrB,MAAA,GAAS,IAAA,CAAK,MAAA,CAAO,WAAA;AAAA;AAAA,iBAGP,gBAAA,CAAiB,OAAA,GAAS,uBAAA,GAA+B,kBAAA;;;UC5BxD,yBAAA;EACf,SAAA;EACA,gBAAA,GAAmB,MAAA,EAAQ,MAAA,CAAO,OAAA,KAAY,OAAA;EAC9C,OAAA,gBAAuB,OAAA;EACvB,IAAA,IAAQ,IAAA;AAAA;AAAA,cAGG,kBAAA;EAAA,iBACM,SAAA;EAAA,iBACA,gBAAA;EAAA,iBACA,OAAA;EAAA,iBACA,IAAA;EAAA,QACT,SAAA;EAAA,QACA,YAAA;EAAA,QACA,cAAA;EAAA,iBACS,YAAA;cAEL,OAAA,EAAS,yBAAA;EAOrB,OAAA,CAAQ,OAAA,GAAS,MAAA,CAAO,OAAA;EAgBxB,OAAA,CAAA;EAQM,YAAA,CAAa,MAAA,EAAQ,MAAA,CAAO,OAAA,GAAU,OAAA;EAAA,QAyB9B,UAAA;AAAA;AAAA,iBAUA,wBAAA,CAAyB,OAAA,EAAS,yBAAA,GAA4B,kBAAA"}
package/package.json ADDED
@@ -0,0 +1,52 @@
1
+ {
2
+ "name": "@open-wa/cli",
3
+ "version": "5.0.0-alpha.0",
4
+ "description": "CLI for @open-wa WhatsApp automation - Easy API mode",
5
+ "main": "./dist/index.cjs",
6
+ "module": "./dist/index.cjs",
7
+ "types": "./dist/index.d.cts",
8
+ "bin": {
9
+ "wa": "./dist/bin.cjs",
10
+ "wa-automate": "./dist/bin.cjs",
11
+ "openwa": "./dist/bin.cjs"
12
+ },
13
+ "exports": {
14
+ ".": {
15
+ "import": "./dist/index.cjs",
16
+ "require": "./dist/index.cjs",
17
+ "types": "./dist/index.d.cts"
18
+ }
19
+ },
20
+ "dependencies": {
21
+ "ink": "^5.2.1",
22
+ "qrcode": "^1.5.4",
23
+ "react": "^18.3.1",
24
+ "ws": "^8.20.0",
25
+ "zod": "^4.2.1",
26
+ "@open-wa/core": "5.0.0-alpha.0",
27
+ "@open-wa/wa-automate": "5.0.0-alpha.0"
28
+ },
29
+ "devDependencies": {
30
+ "@types/node": "^25.9.1",
31
+ "@types/react": "^18.3.12",
32
+ "@types/ws": "^8.18.1",
33
+ "typescript": "^6.0.3",
34
+ "vitest": "4.1.2"
35
+ },
36
+ "publishConfig": {
37
+ "access": "public"
38
+ },
39
+ "type": "module",
40
+ "repository": {
41
+ "type": "git",
42
+ "url": "https://github.com/open-wa/wa-automate-nodejs.git"
43
+ },
44
+ "scripts": {
45
+ "build": "tsdown src/index.ts src/bin.ts --format cjs",
46
+ "dev": "tsdown src/index.ts src/bin.ts --format cjs --watch",
47
+ "start": "node dist/bin.cjs",
48
+ "test": "vitest run",
49
+ "lint": "oxlint src",
50
+ "clean": "rimraf dist"
51
+ }
52
+ }
@@ -0,0 +1,50 @@
1
+ import { describe, expect, it, vi } from 'vitest';
2
+ import { CliShutdownError, performGracefulShutdown, writeVisibleFatalError } from '../runtime/cli-termination';
3
+
4
+ describe('CLI termination helpers', () => {
5
+ it('attempts all teardown steps even when one rejects', async () => {
6
+ const order: string[] = [];
7
+ const store = {
8
+ projectStatus: vi.fn((update: { phase: string }) => {
9
+ order.push(`status:${update.phase}`);
10
+ }),
11
+ };
12
+ const runtime = {
13
+ server: {
14
+ stop: vi.fn(async () => {
15
+ order.push('server.stop');
16
+ throw new Error('server breach');
17
+ }),
18
+ },
19
+ client: {
20
+ stop: vi.fn(async () => {
21
+ order.push('client.stop');
22
+ }),
23
+ },
24
+ } as any;
25
+ const tunnelClient = {
26
+ disconnect: vi.fn(() => {
27
+ order.push('tunnel.disconnect');
28
+ }),
29
+ };
30
+
31
+ const result = performGracefulShutdown({ runtime, tunnelClient, store: store as any }, 'SIGTERM');
32
+
33
+ await expect(result).rejects.toBeInstanceOf(CliShutdownError);
34
+ expect(order).toEqual([
35
+ 'status:shutdown.starting',
36
+ 'server.stop',
37
+ 'tunnel.disconnect',
38
+ 'client.stop',
39
+ 'status:shutdown.complete',
40
+ ]);
41
+ });
42
+
43
+ it('writes fatal errors directly to raw stderr for visibility', () => {
44
+ const writeRawStderr = vi.fn();
45
+
46
+ writeVisibleFatalError('reactor offline', writeRawStderr);
47
+
48
+ expect(writeRawStderr).toHaveBeenCalledWith('\nFatal error: reactor offline\n');
49
+ });
50
+ });
@@ -0,0 +1,64 @@
1
+ import { describe, expect, it, vi } from 'vitest';
2
+ import { createEventProjectionStore } from '../state/event-projection-store';
3
+
4
+ class FakeEmitter {
5
+ private handlers = new Map<string, Set<(payload: unknown) => void>>();
6
+
7
+ on(event: string, handler: (payload: unknown) => void) {
8
+ const handlers = this.handlers.get(event) ?? new Set();
9
+ handlers.add(handler);
10
+ this.handlers.set(event, handlers);
11
+ return this;
12
+ }
13
+
14
+ off(event: string, handler: (payload: unknown) => void) {
15
+ this.handlers.get(event)?.delete(handler);
16
+ return this;
17
+ }
18
+
19
+ emit(event: string, payload: unknown) {
20
+ for (const handler of this.handlers.get(event) ?? []) {
21
+ handler(payload);
22
+ }
23
+ }
24
+
25
+ listenerCount(event: string): number {
26
+ return this.handlers.get(event)?.size ?? 0;
27
+ }
28
+ }
29
+
30
+ describe('EventProjectionStore', () => {
31
+ it('retains only a bounded number of log entries', () => {
32
+ const store = createEventProjectionStore({ maxLogs: 2 });
33
+
34
+ store.projectLog({ level: 'info', message: 'one', source: 'runtime', timestamp: 1 });
35
+ store.projectLog({ level: 'info', message: 'two', source: 'runtime', timestamp: 2 });
36
+ store.projectLog({ level: 'info', message: 'three', source: 'runtime', timestamp: 3 });
37
+
38
+ expect(store.getSnapshot().recentLogs.map((entry) => entry.message)).toEqual(['two', 'three']);
39
+ });
40
+
41
+ it('coalesces bursty runtime events before exposing them to the snapshot', async () => {
42
+ vi.useFakeTimers();
43
+ const store = createEventProjectionStore({ eventDebounceMs: 100 });
44
+ const emitter = new FakeEmitter();
45
+ const detach = store.attachEmitter(emitter as any);
46
+
47
+ emitter.emit('message.received', {});
48
+ emitter.emit('message.received', {});
49
+ emitter.emit('ack.changed', {});
50
+
51
+ expect(store.getSnapshot().messageCount).toBe(0);
52
+ expect(store.getSnapshot().ackCount).toBe(0);
53
+
54
+ await vi.advanceTimersByTimeAsync(100);
55
+
56
+ expect(store.getSnapshot().messageCount).toBe(2);
57
+ expect(store.getSnapshot().ackCount).toBe(1);
58
+
59
+ detach();
60
+ expect(emitter.listenerCount('message.received')).toBe(0);
61
+ expect(emitter.listenerCount('ack.changed')).toBe(0);
62
+ vi.useRealTimers();
63
+ });
64
+ });
@@ -0,0 +1,84 @@
1
+ import { describe, expect, it, vi } from 'vitest';
2
+
3
+ describe('createInteractiveCliSession', () => {
4
+ it('uses a broker configuration that leaves stdio streams untouched for Ink', async () => {
5
+ const install = vi.fn();
6
+ const dispose = vi.fn();
7
+ const subscribe = vi.fn(() => vi.fn());
8
+ const write = vi.fn();
9
+
10
+ const createOutputBroker = vi.fn(() => ({
11
+ install,
12
+ dispose,
13
+ subscribe,
14
+ write,
15
+ }));
16
+
17
+ vi.doMock('../runtime/output-broker', async () => {
18
+ const actual = await vi.importActual<typeof import('../runtime/output-broker')>('../runtime/output-broker');
19
+ return {
20
+ ...actual,
21
+ createOutputBroker,
22
+ };
23
+ });
24
+ vi.doMock('../presenter/interactive-terminal', () => ({
25
+ InteractiveTerminalPresenter: class MockInteractiveTerminalPresenter {
26
+ async start() {}
27
+ stop() {}
28
+ },
29
+ }));
30
+
31
+ const module = await import('../runtime/interactive-session');
32
+ const session = await module.createInteractiveCliSession();
33
+
34
+ expect(createOutputBroker).toHaveBeenCalledWith(
35
+ expect.objectContaining({
36
+ interactive: true,
37
+ interceptStreams: false,
38
+ })
39
+ );
40
+
41
+ session.cleanup();
42
+ vi.resetModules();
43
+ vi.doUnmock('../runtime/output-broker');
44
+ vi.doUnmock('../presenter/interactive-terminal');
45
+ });
46
+
47
+ it('awaits presenter startup before resolving the interactive session', async () => {
48
+ let resolveStart: (() => void) | undefined;
49
+ const start = vi.fn(
50
+ () =>
51
+ new Promise<void>((resolve) => {
52
+ resolveStart = resolve;
53
+ })
54
+ );
55
+ const stop = vi.fn();
56
+
57
+ vi.doMock('../presenter/interactive-terminal', () => ({
58
+ InteractiveTerminalPresenter: class MockInteractiveTerminalPresenter {
59
+ start = start;
60
+ stop = stop;
61
+ },
62
+ }));
63
+
64
+ const module = await import('../runtime/interactive-session');
65
+ let resolved = false;
66
+ const sessionPromise = module.createInteractiveCliSession().then((session) => {
67
+ resolved = true;
68
+ return session;
69
+ });
70
+
71
+ await Promise.resolve();
72
+
73
+ expect(start).toHaveBeenCalledTimes(1);
74
+ expect(resolved).toBe(false);
75
+
76
+ resolveStart?.();
77
+ const session = await sessionPromise;
78
+
79
+ expect(resolved).toBe(true);
80
+ session.cleanup();
81
+ vi.resetModules();
82
+ vi.doUnmock('../presenter/interactive-terminal');
83
+ });
84
+ });
@@ -0,0 +1,80 @@
1
+ import { describe, expect, it, vi } from 'vitest';
2
+
3
+ describe('InteractiveTerminalPresenter', () => {
4
+ it('subscribes externally and rerenders Ink without React hooks in the presenter', async () => {
5
+ const rerender = vi.fn();
6
+ const clear = vi.fn();
7
+ const unmount = vi.fn();
8
+ const render = vi.fn(() => ({ rerender, clear, unmount }));
9
+ const createElement = vi.fn((type: unknown, props?: Record<string, unknown>, ...children: unknown[]) => ({
10
+ type,
11
+ props: { ...(props ?? {}), children },
12
+ }));
13
+ const subscribe = vi.fn((listener: (snapshot: unknown) => void) => {
14
+ subscribe.listener = listener;
15
+ listener({
16
+ phase: 'auth.qr',
17
+ sessionId: 'demo',
18
+ qr: { sessionId: 'demo', qr: 'qr-token' },
19
+ recentLogs: [],
20
+ messageCount: 0,
21
+ ackCount: 0,
22
+ ready: false,
23
+ });
24
+ return () => undefined;
25
+ }) as ReturnType<typeof vi.fn> & { listener?: () => void };
26
+ const getSnapshot = vi
27
+ .fn()
28
+ .mockReturnValueOnce({ phase: 'boot', recentLogs: [], messageCount: 0, ackCount: 0, ready: false })
29
+ .mockReturnValue({
30
+ phase: 'auth.qr',
31
+ sessionId: 'demo',
32
+ qr: { sessionId: 'demo', qr: 'qr-token' },
33
+ recentLogs: [],
34
+ messageCount: 0,
35
+ ackCount: 0,
36
+ ready: false,
37
+ });
38
+
39
+ vi.doMock('react', () => ({ createElement }));
40
+ vi.doMock('ink', () => ({
41
+ render,
42
+ Box: 'Box',
43
+ Text: 'Text',
44
+ }));
45
+ vi.doMock('qrcode', () => ({
46
+ default: {
47
+ toString: vi.fn(async () => 'QR ASCII'),
48
+ },
49
+ }));
50
+
51
+ const { InteractiveTerminalPresenter } = await import('../presenter/interactive-terminal');
52
+ const presenter = new InteractiveTerminalPresenter({
53
+ store: {
54
+ subscribe,
55
+ getSnapshot,
56
+ } as any,
57
+ stdout: { columns: 200 } as any,
58
+ stderr: {} as any,
59
+ });
60
+
61
+ await presenter.start();
62
+ await Promise.resolve();
63
+
64
+ expect(render).toHaveBeenCalledTimes(1);
65
+ expect(rerender).toHaveBeenCalled();
66
+
67
+ const rerenderedTree = rerender.mock.calls.at(-1)?.[0] as { props?: { qrAscii?: string } } | undefined;
68
+ expect(rerenderedTree?.props?.qrAscii).toBe('QR ASCII');
69
+ expect(
70
+ createElement.mock.calls.some((call) => call.includes('Terminal window too small to render QR Code visually. Please expand.'))
71
+ ).toBe(false);
72
+
73
+ presenter.stop();
74
+
75
+ vi.resetModules();
76
+ vi.doUnmock('react');
77
+ vi.doUnmock('ink');
78
+ vi.doUnmock('qrcode');
79
+ });
80
+ });
@@ -0,0 +1,66 @@
1
+ import { afterEach, describe, expect, it, vi } from 'vitest';
2
+ import { createOutputBroker } from '../runtime/output-broker';
3
+
4
+ describe('OutputBroker', () => {
5
+ afterEach(() => {
6
+ vi.restoreAllMocks();
7
+ });
8
+
9
+ it('intercepts console output and keeps a bounded buffer', () => {
10
+ const broker = createOutputBroker({ interactive: true, maxEntries: 2, passthrough: false });
11
+ broker.install();
12
+ const interceptedLog = console.log;
13
+
14
+ console.log('alpha');
15
+ console.warn('beta');
16
+ console.error('gamma');
17
+
18
+ const entries = broker.getEntries();
19
+ expect(entries).toHaveLength(2);
20
+ expect(entries.map((entry) => entry.message)).toEqual(['beta', 'gamma']);
21
+
22
+ broker.dispose();
23
+ expect(console.log).not.toBe(interceptedLog);
24
+ });
25
+
26
+ it('passes through to the original console in plain mode', () => {
27
+ const forwarded: string[] = [];
28
+ const originalLog = console.log;
29
+ console.log = ((...args: unknown[]) => {
30
+ forwarded.push(args.join(' '));
31
+ }) as typeof console.log;
32
+
33
+ const broker = createOutputBroker({ interactive: false, maxEntries: 5, passthrough: true });
34
+ broker.install();
35
+
36
+ console.log('plain-text');
37
+
38
+ broker.dispose();
39
+ console.log = originalLog;
40
+
41
+ expect(forwarded).toEqual(['plain-text']);
42
+ expect(broker.getEntries()).toHaveLength(1);
43
+ });
44
+
45
+ it('restores stdout writes after cleanup', () => {
46
+ const broker = createOutputBroker({ interactive: true, passthrough: false });
47
+ broker.install();
48
+ const interceptedWrite = process.stdout.write;
49
+ broker.dispose();
50
+
51
+ expect(process.stdout.write).not.toBe(interceptedWrite);
52
+ });
53
+
54
+ it('can leave stdout and stderr untouched for Ink rendering compatibility', () => {
55
+ const originalStdoutWrite = process.stdout.write;
56
+ const originalStderrWrite = process.stderr.write;
57
+ const broker = createOutputBroker({ interactive: true, passthrough: false, interceptStreams: false });
58
+
59
+ broker.install();
60
+
61
+ expect(process.stdout.write).toBe(originalStdoutWrite);
62
+ expect(process.stderr.write).toBe(originalStderrWrite);
63
+
64
+ broker.dispose();
65
+ });
66
+ });