"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    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) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
const fs = require("mz/fs");
const pFilter = require("p-filter");
const path = require("path");
/**
 * Returns bins for a package in a standard object format. This normalizes
 * between npm's string and object formats.
 *
 * @example
 *    binify({ name: 'rimraf', bin: 'cmd.js' })
 *    => { rimraf: 'cmd.js' }
 *
 *    binify({ name: 'rmrf', bin: { rmrf: 'cmd.js' } })
 *    => { rmrf: 'cmd.js' }
 */
function binify(pkg, pkgPath) {
    return __awaiter(this, void 0, void 0, function* () {
        if (pkg.bin) {
            return commandsFromBin(pkg.bin, pkg.name, pkgPath);
        }
        if (pkg.directories && pkg.directories.bin) {
            const binDir = path.join(pkgPath, pkg.directories.bin);
            const files = yield findFiles(binDir);
            return pFilter(files.map((file) => ({
                name: file,
                path: path.join(binDir, file),
            })), (cmd) => __awaiter(this, void 0, void 0, function* () { return (yield fs.stat(cmd.path)).isFile(); }));
        }
        return [];
    });
}
exports.default = binify;
function findFiles(dir) {
    return __awaiter(this, void 0, void 0, function* () {
        try {
            return yield fs.readdir(dir);
        }
        catch (err) {
            if (err.code !== 'ENOENT') {
                throw err;
            }
            return [];
        }
    });
}
function commandsFromBin(bin, pkgName, pkgPath) {
    if (typeof bin === 'string') {
        return [
            {
                name: pkgName,
                path: path.join(pkgPath, bin),
            },
        ];
    }
    return Object.keys(bin)
        .map((commandName) => ({
        name: commandName,
        path: path.join(pkgPath, bin[commandName]),
    }));
}
//# sourceMappingURL=binify.js.map