import { randomUUID } from 'node:crypto' import process from 'node:process' import { createInterface } from 'node:readline' import { toError } from '@internals/utils' import { type Result, x } from 'tinyexec' import { host } from '../host.ts' import type { Hookable } from '../hookable.ts' import type { KubbHooks } from '../types.ts' /** * Outcome of one spawned command, also carried by the `kubb:command:end` event it emits. */ export type CommandResult = { success: true; error: null } | { success: false; error: Error; stdout?: string; stderr?: string } export type RunCommandOptions = { hooks: Hookable /** Executable to run, resolved on `PATH` and in every `node_modules/.bin` above `cwd`. */ command: string args?: ReadonlyArray /** Label shown instead of the command line, for example a `postGenerate` step name. */ name?: string /** Working directory for the command. Defaults to the current process directory. */ cwd?: string signal?: AbortSignal } const KILL_GRACE_MS = 2_000 type LineRelayOptions = { proc: Result; hooks: Hookable; id: string } // Each line fires `kubb:command:line`, then the deprecated `kubb:hook:line`. class LineRelay { #lines: Promise = Promise.resolve() #error: Error | null = null constructor({ proc, hooks, id }: LineRelayOptions) { for (const input of [proc.process?.stdout, proc.process?.stderr]) { if (!input) continue createInterface({ input }).on('line', (line) => { this.#lines = this.#lines .then(() => hooks.callHook('kubb:command:line', { id, line })) .catch((error) => this.#keep(error)) .then(() => hooks.callHook('kubb:hook:line', { id, line })) .catch((error) => this.#keep(error)) }) } } #keep(error: unknown): void { this.#error ??= toError(error) } get error(): Error | null { return this.#error } settled(): Promise { return this.#lines } } // Lines are only read when a logger listens, so a quiet host does not pay to iterate them. function createLineRelay({ proc, hooks, id }: LineRelayOptions): LineRelay | undefined { if (hooks.listenerCount('kubb:command:line') === 0 && hooks.listenerCount('kubb:hook:line') === 0) return undefined return new LineRelay({ proc, hooks, id }) } async function settle(proc: Result, hooks: Hookable, id: string, commandWithArgs: string): Promise { let childError: Error | null = null let killTimer: NodeJS.Timeout | undefined proc.process?.once('error', (error) => { childError = error // An abort only asks the child to stop; one that swallows SIGTERM would otherwise hang the run. killTimer = setTimeout(() => proc.kill('SIGKILL'), KILL_GRACE_MS).unref() }) const relay = createLineRelay({ proc, hooks, id }) const output = await Promise.resolve(proc).catch(() => null) clearTimeout(killTimer) await relay?.settled() const error = childError ?? relay?.error if (error) return { success: false, error } if (output?.exitCode === 0) return { success: true, error: null } return { success: false, error: new Error(`Hook execute failed: ${commandWithArgs}`), stdout: output?.stdout, stderr: output?.stderr } } /** * Spawns a command and announces it through `kubb:command:start`, `kubb:command:line` and `kubb:command:end`. * A failure returns `success: false` instead of throwing, so the caller reports it once. */ export async function runCommand({ hooks, command, args = [], name, cwd = host.cwd(), signal }: RunCommandOptions): Promise { const id = randomUUID() const start = { id, command, name, args } await hooks.callHook('kubb:command:start', start) await hooks.callHook('kubb:hook:start', start) const proc = x(command, [...args], { signal, throwOnError: false, nodeOptions: { cwd, windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'], detached: process.platform !== 'win32' }, }) const result = await settle(proc, hooks, id, [command, ...args].join(' ')) const end = { id, command, name, args, ...result } await hooks.callHook('kubb:command:end', end) await hooks.callHook('kubb:hook:end', end) return result }