@goldstack/utils-cli
Version:
Utilities for building command line interfaces.
95 lines • 3.28 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.wrapCli = void 0;
exports.configureLogger = configureLogger;
exports.logger = logger;
const pino_1 = __importDefault(require("pino"));
const pino_pretty_1 = __importDefault(require("pino-pretty"));
const isDebug = process.env.GOLDSTACK_DEBUG || process.env.DEBUG;
const isLambda = !!process.env.AWS_LAMBDA_FUNCTION_NAME;
let loggerInstance;
const defaultLogger = (0, pino_1.default)({
level: isDebug ? 'debug' : 'info',
...(isLambda && {
timestamp: () => `,"time":"${new Date(Date.now()).toISOString()}"`,
formatters: {
level: (label) => ({ level: label }),
log: (obj) => {
if (obj.err) {
const err = obj.err;
return {
...obj,
error: {
type: err.name,
stack: err.stack,
message: err.message,
},
};
}
return obj;
},
},
base: {
aws_request_id: process.env.AWS_LAMBDA_REQUEST_ID || undefined,
function_name: process.env.AWS_LAMBDA_FUNCTION_NAME,
function_version: process.env.AWS_LAMBDA_FUNCTION_VERSION,
},
}),
}, isLambda
? undefined // Use default JSON transport for Lambda
: (0, pino_pretty_1.default)({
colorize: true,
hideObject: false,
colorizeObjects: true,
translateTime: 'HH:MM:ss',
ignore: 'pid,hostname',
singleLine: false,
sync: true, // required for work in Jest see https://github.com/pinojs/pino-pretty?tab=readme-ov-file#usage-with-jest
}));
/**
* Configure the logger instance
* @param config - Configuration options for the logger
*/
function configureLogger(config) {
loggerInstance = config.instance;
}
/**
* Get the current logger instance
* @returns The configured logger instance or the default pino logger
*/
function logger() {
return loggerInstance || defaultLogger;
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const wrapCli = async (func) => {
try {
await func();
process.exit(0);
}
catch (e) {
if (isDebug) {
logger().error({}, `Error while executing CLI command: ${e.error || e.errorMessage || e.message}`);
console.error(e);
throw e;
}
else {
logger().info({}, '❌ Error while executing CLI command:' +
e.message +
'\n For more information about this error, run this command with the environment variable GOLDSTACK_DEBUG set to true');
process.exit(1);
}
}
};
exports.wrapCli = wrapCli;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
process.on('unhandledRejection', (e) => {
if (isDebug) {
console.log(e);
}
console.log('❌ Unhandled error in asynchronous method:', e.message);
process.exit(1);
});
//# sourceMappingURL=utilsCli.js.map