"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.NEW_LINE_REGEX = void 0;
exports.asyncSpawn = asyncSpawn;
exports.syncSpawn = syncSpawn;
exports.syncExec = syncExec;
const child_process_1 = require("child_process");
const asyncUtil_1 = require("@mablhq-internal/runtime/util/asyncUtil");
exports.NEW_LINE_REGEX = /\r?\n/;
async function asyncSpawn(command, args, timeoutMillis) {
    const childProcess = (0, child_process_1.spawn)(command, args);
    const processOutputFuture = waitForProcessExitOrError(childProcess);
    if (!timeoutMillis || timeoutMillis < 0) {
        return processOutputFuture;
    }
    try {
        return (0, asyncUtil_1.promiseWithTimeout)(processOutputFuture, timeoutMillis, `${command} ${args.join(' ')}`, 'Spawn Process');
    }
    catch (error) {
        childProcess.kill();
        throw error;
    }
}
function waitForProcessExitOrError(process) {
    return new Promise((resolve, reject) => {
        try {
            let output = [];
            const error = [];
            if (process.stdout) {
                process.stdout.on('data', (data) => {
                    const split = data.toString('utf-8').split(exports.NEW_LINE_REGEX);
                    output = [...output, ...split];
                });
            }
            if (process.stderr) {
                process.stderr.on('data', (errorData) => error.push(errorData.toString()));
            }
            process.on('error', () => {
                reject(error);
            });
            process.on('close', () => {
                resolve(output);
            });
        }
        catch (error) {
            reject(error);
        }
    });
}
function syncSpawn(command, args) {
    return (0, child_process_1.spawnSync)(command, args, {
        encoding: 'utf8',
    }).output;
}
function syncExec(command, args, options) {
    return (0, child_process_1.execSync)(`${command} ${args.join(' ')}`, options)
        .toString()
        .split(exports.NEW_LINE_REGEX);
}
