|
| 1 | +import { execFile } from "node:child_process"; |
| 2 | +import { promisify } from "node:util"; |
| 3 | + |
| 4 | +const execFileAsync = promisify(execFile); |
| 5 | + |
| 6 | +export interface MgcExecResult { |
| 7 | + stdout: string; |
| 8 | + stderr: string; |
| 9 | + exitCode: number; |
| 10 | +} |
| 11 | + |
| 12 | +export class MgcClient { |
| 13 | + private mgcPath: string; |
| 14 | + |
| 15 | + constructor(mgcPath?: string) { |
| 16 | + this.mgcPath = mgcPath || process.env.MGC_CLI_PATH || "mgc"; |
| 17 | + } |
| 18 | + |
| 19 | + async execute( |
| 20 | + args: string[], |
| 21 | + options?: { timeout?: number } |
| 22 | + ): Promise<MgcExecResult> { |
| 23 | + const timeout = options?.timeout || 60000; |
| 24 | + |
| 25 | + try { |
| 26 | + const { stdout, stderr } = await execFileAsync(this.mgcPath, args, { |
| 27 | + timeout, |
| 28 | + maxBuffer: 10 * 1024 * 1024, |
| 29 | + env: { |
| 30 | + ...process.env, |
| 31 | + NO_COLOR: "1", |
| 32 | + }, |
| 33 | + }); |
| 34 | + |
| 35 | + return { stdout, stderr, exitCode: 0 }; |
| 36 | + } catch (error: unknown) { |
| 37 | + const execError = error as { |
| 38 | + stdout?: string; |
| 39 | + stderr?: string; |
| 40 | + code?: number | string; |
| 41 | + killed?: boolean; |
| 42 | + }; |
| 43 | + |
| 44 | + if (execError.killed) { |
| 45 | + return { |
| 46 | + stdout: execError.stdout || "", |
| 47 | + stderr: `Command timed out after ${timeout}ms`, |
| 48 | + exitCode: 124, |
| 49 | + }; |
| 50 | + } |
| 51 | + |
| 52 | + return { |
| 53 | + stdout: execError.stdout || "", |
| 54 | + stderr: execError.stderr || String(error), |
| 55 | + exitCode: typeof execError.code === "number" ? execError.code : 1, |
| 56 | + }; |
| 57 | + } |
| 58 | + } |
| 59 | + |
| 60 | + async executeCommand( |
| 61 | + command: string, |
| 62 | + outputFormat?: string |
| 63 | + ): Promise<MgcExecResult> { |
| 64 | + const args = command.split(/\s+/).filter(Boolean); |
| 65 | + |
| 66 | + if (outputFormat && !args.includes("-o") && !args.includes("--output")) { |
| 67 | + args.push("-o", outputFormat); |
| 68 | + } |
| 69 | + |
| 70 | + // Always add --no-confirm to avoid interactive prompts |
| 71 | + if (!args.includes("--no-confirm")) { |
| 72 | + args.push("--no-confirm"); |
| 73 | + } |
| 74 | + |
| 75 | + return this.execute(args); |
| 76 | + } |
| 77 | +} |
0 commit comments