(
argv: string[],
responderOrOptions: CliCaptureResponder | CliCaptureOptions = {},
extraOptions: CliCaptureOptions = {},
)
| 46 | ) => Promise<DaemonResponse>; |
| 47 | |
| 48 | export async function runCliCapture( |
| 49 | argv: string[], |
| 50 | responderOrOptions: CliCaptureResponder | CliCaptureOptions = {}, |
| 51 | extraOptions: CliCaptureOptions = {}, |
| 52 | ): Promise<CapturedCliRun> { |
| 53 | const options = |
| 54 | typeof responderOrOptions === 'function' |
| 55 | ? { ...extraOptions, sendToDaemon: responderOrOptions } |
| 56 | : { ...extraOptions, ...(responderOrOptions ?? {}) }; |
| 57 | let stdout = ''; |
| 58 | let stderr = ''; |
| 59 | let code: number | null = null; |
| 60 | const calls: CapturedDaemonRequest[] = []; |
| 61 | const stateDir = options.stateDirPrefix |
| 62 | ? fs.mkdtempSync(path.join(os.tmpdir(), options.stateDirPrefix)) |
| 63 | : undefined; |
| 64 | |
| 65 | const originalExit = process.exit; |
| 66 | const originalStdoutWrite = process.stdout.write.bind(process.stdout); |
| 67 | const originalStderrWrite = process.stderr.write.bind(process.stderr); |
| 68 | const originalCwd = process.cwd(); |
| 69 | const restoreEnv = installIsolatedCliTestEnv({ |
| 70 | ...(options.env ?? {}), |
| 71 | ...(stateDir ? { AGENT_DEVICE_STATE_DIR: stateDir } : {}), |
| 72 | }); |
| 73 | |
| 74 | if (options.cwd) { |
| 75 | process.chdir(options.cwd); |
| 76 | } |
| 77 | |
| 78 | (process as any).exit = ((nextCode?: number) => { |
| 79 | throw new ExitSignal(nextCode ?? 0); |
| 80 | }) as typeof process.exit; |
| 81 | (process.stdout as any).write = ((chunk: unknown, ...args: unknown[]) => { |
| 82 | if (options.passthroughBufferWrites && Buffer.isBuffer(chunk)) { |
| 83 | return originalStdoutWrite(chunk, ...(args as [any])); |
| 84 | } |
| 85 | stdout += String(chunk); |
| 86 | return true; |
| 87 | }) as typeof process.stdout.write; |
| 88 | (process.stderr as any).write = ((chunk: unknown, ...args: unknown[]) => { |
| 89 | if (options.passthroughBufferWrites && Buffer.isBuffer(chunk)) { |
| 90 | return originalStderrWrite(chunk, ...(args as [any])); |
| 91 | } |
| 92 | stderr += String(chunk); |
| 93 | return true; |
| 94 | }) as typeof process.stderr.write; |
| 95 | |
| 96 | const sendToDaemon = async ( |
| 97 | req: CapturedDaemonRequest, |
| 98 | daemonOptions?: DaemonTransportOptions, |
| 99 | ): Promise<DaemonResponse> => { |
| 100 | calls.push(req); |
| 101 | if (options.sendToDaemon) { |
| 102 | return await options.sendToDaemon(req, daemonOptions); |
| 103 | } |
| 104 | return options.defaultResponse ?? { ok: true, data: {} }; |
| 105 | }; |
no test coverage detected