@suchipi/run-main
Version:
CLI app entrypoint function runner
52 lines (51 loc) • 1.86 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.runMain = void 0;
const format_error_1 = require("./format-error");
const defer_1 = __importDefault(require("@suchipi/defer"));
/**
* A helper function suitable for use in command-line applications. Runs the
* provided "main" function (which can be sync or async), and if it errors,
* format the error message, print it to stderr, and call `process.exit(1)`
*
* The Promise returned by this function resolves when `mainFunction` succeeds
* and rejects when it errors.
*/
function runMain(
/**
* The function to run. If it's async, it'll be `await`ed.
*/
mainFunction, runOptions = {}) {
var _a, _b, _c;
const inspect = (_a = runOptions.inspect) !== null && _a !== void 0 ? _a : require("util").inspect;
const printError = (_b = runOptions.printError) !== null && _b !== void 0 ? _b : console.error;
const exit = (_c = runOptions.exit) !== null && _c !== void 0 ? _c : process.exit.bind(process);
const defer = new defer_1.default();
try {
const result = mainFunction();
if (typeof result === "object" &&
result != null &&
typeof result.then === "function") {
result.then(() => {
defer.resolve();
}, (err) => {
printError((0, format_error_1.formatError)(err, inspect));
defer.reject(err);
exit(1);
});
}
else {
defer.resolve();
}
}
catch (err) {
printError((0, format_error_1.formatError)(err, inspect));
defer.reject(err);
exit(1);
}
return defer.promise;
}
exports.runMain = runMain;