|
| 1 | +import { execaSync } from 'execa' |
| 2 | +import path from 'node:path' |
| 3 | +import { fileURLToPath } from 'node:url' |
| 4 | +import stripAnsi from 'strip-ansi' |
| 5 | +import { createLogsMatcher, type LogsMatcher } from './matchers.js' |
| 6 | + |
| 7 | +const __dirname = path.dirname(fileURLToPath(import.meta.url)) |
| 8 | + |
| 9 | +// Path to the built CLI binary |
| 10 | +const CLI_PATH = path.resolve(__dirname, '../../../cli/dist/index.js') |
| 11 | + |
| 12 | +export interface OxnodeCLI { |
| 13 | + invoke: (args: string[]) => [number, LogsMatcher] |
| 14 | + setCwd: (cwd: string) => OxnodeCLI |
| 15 | +} |
| 16 | + |
| 17 | +export function OxnodeCLI(): OxnodeCLI { |
| 18 | + let workingDirectory = process.cwd() |
| 19 | + |
| 20 | + const setCwd = (cwd: string): OxnodeCLI => { |
| 21 | + workingDirectory = cwd |
| 22 | + return api |
| 23 | + } |
| 24 | + |
| 25 | + const invoke = (args: string[]): [number, LogsMatcher] => { |
| 26 | + try { |
| 27 | + const result = execaSync('node', [CLI_PATH, ...args], { |
| 28 | + cwd: workingDirectory, |
| 29 | + env: { |
| 30 | + ...process.env, |
| 31 | + NODE_ENV: 'production', |
| 32 | + }, |
| 33 | + all: true, |
| 34 | + reject: false, |
| 35 | + }) |
| 36 | + |
| 37 | + const output = stripAnsi(result.all || '') |
| 38 | + const exitCode = result.exitCode |
| 39 | + |
| 40 | + return [exitCode, createLogsMatcher(output)] |
| 41 | + } catch (error) { |
| 42 | + // If execa throws an error, capture it |
| 43 | + const err = error as { all?: string; exitCode?: number } |
| 44 | + const output = stripAnsi(err.all || '') |
| 45 | + const exitCode = err.exitCode || 1 |
| 46 | + |
| 47 | + return [exitCode, createLogsMatcher(output)] |
| 48 | + } |
| 49 | + } |
| 50 | + |
| 51 | + const api: OxnodeCLI = { |
| 52 | + invoke, |
| 53 | + setCwd, |
| 54 | + } |
| 55 | + |
| 56 | + return api |
| 57 | +} |
0 commit comments