"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
const path_1 = require("path");
const fs_1 = require("fs");
const util_1 = require("../util");
const mkdirp = require("mkdirp");
/**
 * The "cli" step detects the appropriate input. If no input options are passed,
 * the package.json#main file is used.
 * After all the build steps have run, the output (the executable) is written to a file or piped to stdout.
 *
 * Configuration:
 *
 * @param {*} compiler
 * @param {*} next
 */
function cli(compiler, next) {
    return __awaiter(this, void 0, void 0, function* () {
        yield next();
        const { log } = compiler, target = compiler.options.targets.shift(), deliverable = yield compiler.compileAsync(target), output = (0, path_1.normalize)(compiler.output);
        mkdirp.sync((0, path_1.dirname)(output));
        return new Promise((res, rej) => {
            const step = log.step('Writing result to file');
            deliverable
                .pipe((0, fs_1.createWriteStream)(output))
                .on('error', rej)
                .once('close', (e) => {
                if (e) {
                    rej(e);
                }
                else if (compiler.output) {
                    const output = compiler.output, mode = (0, fs_1.statSync)(output).mode | 0o111, inputFileLogOutput = (0, path_1.relative)(process.cwd(), (0, path_1.resolve)(compiler.options.cwd, compiler.entrypoint || compiler.options.input)), outputFileLogOutput = (0, path_1.relative)(process.cwd(), output);
                    (0, fs_1.chmodSync)(output, mode.toString(8).slice(-3));
                    step.log(`Entry: '${compiler.stdinUsed
                        ? compiler.options.mangle
                            ? util_1.STDIN_FLAG
                            : '[none]'
                        : inputFileLogOutput}' written to: ${outputFileLogOutput}`);
                    compiler.quit();
                    res(output);
                }
            });
        });
    });
}
exports.default = cli;
