@moostjs/event-cli
Version:
@moostjs/event-cli
264 lines (256 loc) • 9.26 kB
JavaScript
import { Controller, Description, Intercept, Moost, Optional, Param, Resolve, TInterceptorPriority, defineInterceptorFn, defineMoostEventHandler, getMoostMate, setInfactLoggingOptions, useControllerContext } from "moost";
import { WooksCli, createCliApp, useAutoHelp, useCliContext, useCliOption, useCommandLookupHelp } from "@wooksjs/event-cli";
//#region packages/event-cli/src/meta-types.ts
function getCliMate() {
return getMoostMate();
}
//#endregion
//#region packages/event-cli/src/decorators/cli.decorator.ts
function Cli(path) {
return getCliMate().decorate("handlers", {
path: path?.replace(/\s+/g, "/"),
type: "CLI"
}, true);
}
function CliAlias(alias) {
return getCliMate().decorate("cliAliases", alias, true);
}
function CliExample(cmd, description) {
return getCliMate().decorate("cliExamples", {
cmd,
description
}, true);
}
//#endregion
//#region packages/event-cli/src/utils.ts
function formatParams(keys) {
const names = [keys].flat();
return names.map((n) => n.length === 1 ? `-${n}` : `--${n}`);
}
//#endregion
//#region packages/event-cli/src/decorators/option.decorator.ts
function CliOption(...keys) {
const mate = getCliMate();
return mate.apply(mate.decorate("cliOptionsKeys", keys, false), Resolve(() => useCliOption(keys[0]), formatParams(keys).join(", ")));
}
function CliGlobalOption(option) {
const mate = getCliMate();
return mate.decorate("cliOptions", option, true);
}
//#endregion
//#region packages/event-cli/src/event-cli.ts
function _define_property$1(obj, key, value) {
if (key in obj) Object.defineProperty(obj, key, {
value,
enumerable: true,
configurable: true,
writable: true
});
else obj[key] = value;
return obj;
}
const LOGGER_TITLE = "moost-cli";
const CONTEXT_TYPE = "CLI";
var MoostCli = class {
async onNotFound() {
const pathParams = useCliContext().store("event").get("pathParams") || [];
const response = await defineMoostEventHandler({
loggerTitle: LOGGER_TITLE,
getIterceptorHandler: () => this.moost?.getGlobalInterceptorHandler(),
getControllerInstance: () => this.moost,
callControllerMethod: () => undefined,
logErrors: this.opts?.debug,
targetPath: "",
handlerType: "__SYSTEM__"
})();
if (response === undefined) this.cliApp.onUnknownCommand(pathParams);
return response;
}
onInit(moost) {
this.moost = moost;
const boolean = Object.entries(this.optionTypes).filter(([_key, val]) => val.length === 1 && val[0] === Boolean).map(([key, _val]) => key);
this.cliApp.run(undefined, { boolean });
}
bindHandler(opts) {
let fn;
for (const handler of opts.handlers) {
if (handler.type !== "CLI") continue;
const path = typeof handler.path === "string" ? handler.path : typeof opts.method === "string" ? opts.method : "";
const prefix = opts.prefix.replace(/\s+/g, "/") || "";
const makePath = (p) => `${prefix}/${p}`.replace(/\/\/+/g, "/").replace(/\/\\:/g, "\\:").replace(/^\/+/g, "");
const targetPath = makePath(path);
fn = defineMoostEventHandler({
contextType: CONTEXT_TYPE,
loggerTitle: LOGGER_TITLE,
getIterceptorHandler: opts.getIterceptorHandler,
getControllerInstance: opts.getInstance,
controllerMethod: opts.method,
resolveArgs: opts.resolveArgs,
logErrors: this.opts?.debug,
targetPath,
handlerType: handler.type
});
const meta = getCliMate().read(opts.fakeInstance, opts.method);
const classMeta = getCliMate().read(opts.fakeInstance);
const cliOptions = new Map();
[
...this.opts?.globalCliOptions?.length ? this.opts.globalCliOptions : [],
...classMeta?.cliOptions || [],
...meta?.params ? meta.params.filter((param) => param.cliOptionsKeys?.length).map((param) => ({
keys: param.cliOptionsKeys,
value: typeof param.value === "string" ? param.value : "",
description: param.description || "",
type: param.type
})) : []
].forEach((o) => cliOptions.set(o.keys[0], o));
const aliases = [];
if (meta?.cliAliases) for (const alias of meta.cliAliases) {
const targetPath$1 = makePath(alias);
aliases.push(targetPath$1);
}
const cliOptionsArray = Array.from(cliOptions.values());
cliOptionsArray.forEach((o) => {
for (const key of o.keys) {
if (!this.optionTypes[key]) this.optionTypes[key] = [];
if (!this.optionTypes[key].includes(o.type)) this.optionTypes[key].push(o.type);
}
});
const args = {};
meta?.params.filter((p) => p.paramSource === "ROUTE" && p.description).forEach((p) => args[p.paramName] = p.description);
const routerBinding = this.cliApp.cli(targetPath, {
description: meta?.description || "",
options: cliOptionsArray,
args,
aliases,
examples: meta?.cliExamples || [],
handler: fn,
onRegister: (path$1, aliasType, route) => {
opts.register(handler, path$1, route?.getArgs() || routerBinding.getArgs());
if (this.opts?.debug) opts.logHandler(`${"\x1B[36m"}(${aliasTypes[aliasType]})${"\x1B[32m"}${path$1}`);
}
});
opts.register(handler, targetPath, routerBinding.getArgs());
}
}
constructor(opts) {
_define_property$1(this, "opts", void 0);
_define_property$1(this, "name", void 0);
_define_property$1(this, "cliApp", void 0);
_define_property$1(this, "optionTypes", void 0);
_define_property$1(this, "moost", void 0);
this.opts = opts;
this.name = "cli";
this.optionTypes = {};
const cliAppOpts = opts?.wooksCli;
if (cliAppOpts && cliAppOpts instanceof WooksCli) this.cliApp = cliAppOpts;
else if (cliAppOpts) this.cliApp = createCliApp({
...cliAppOpts,
onNotFound: this.onNotFound.bind(this)
});
else this.cliApp = createCliApp({ onNotFound: this.onNotFound.bind(this) });
if (!opts?.debug) setInfactLoggingOptions({
newInstance: false,
error: false,
warn: false
});
}
};
const aliasTypes = [
"CLI",
"CLI-alias",
"CLI-alias*",
"CLI-alias*"
];
//#endregion
//#region packages/event-cli/src/interceptors/help.interceptor.ts
const cliHelpInterceptor = (opts) => defineInterceptorFn(() => {
try {
if (useAutoHelp(opts?.helpOptions, opts?.colors)) return "";
} catch (error) {}
if (opts?.lookupLevel) {
const { getMethod } = useControllerContext();
if (!getMethod()) useCommandLookupHelp(opts.lookupLevel);
}
}, TInterceptorPriority.BEFORE_ALL);
const CliHelpInterceptor = (...opts) => Intercept(cliHelpInterceptor(...opts));
//#endregion
//#region packages/event-cli/src/quick-cli.ts
function _define_property(obj, key, value) {
if (key in obj) Object.defineProperty(obj, key, {
value,
enumerable: true,
configurable: true,
writable: true
});
else obj[key] = value;
return obj;
}
var CliApp = class extends Moost {
/**
* Registers one or more CLI controllers.
*
* (Shortcut for `registerControllers` method.)
*
* @param {...(object|Function|[string, object|Function])} controllers - List of controllers.
* Each controller can be an object, a class, or a tuple with a name and the controller.
* @returns {this} The CliApp instance for method chaining.
*/ controllers(...controllers) {
return this.registerControllers(...controllers);
}
/**
* Configures the CLI help options.
*
* This method sets the help options for the CLI. It ensures that colored output is enabled
* (unless explicitly disabled) and that the lookup level defaults to 3 if not provided.
*
* @param {THelpOptions} helpOpts - Help options configuration.
* @param {boolean} helpOpts.colors - Enable colored output.
* @param {number} helpOpts.lookupLevel - Level for help lookup.
* @returns {this} The CliApp instance for method chaining.
*/ useHelp(helpOpts) {
this._helpOpts = helpOpts;
if (this._helpOpts.colors !== false) this._helpOpts.colors = true;
if (typeof this._helpOpts.lookupLevel !== "number") this._helpOpts.lookupLevel = 3;
return this;
}
/**
* Sets the global CLI options.
*
* @param {TMoostCliOpts['globalCliOptions']} globalOpts - Global options for the CLI.
* @returns {this} The CliApp instance for method chaining.
*/ useOptions(globalOpts) {
this._globalOpts = globalOpts;
return this;
}
/**
* Starts the CLI application.
*
* This method creates a MoostCli instance using the configured help and global options,
* attaches it via the adapter, applies the CLI help interceptor (if help options are set),
* and then initializes the application.
*
* @returns {any} The result of the initialization process.
*/ start() {
const cli = new MoostCli({
wooksCli: { cliHelp: this._helpOpts ? {
name: this._helpOpts.name,
title: this._helpOpts.title,
maxWidth: this._helpOpts.maxWidth,
maxLeft: this._helpOpts.maxLeft,
mark: this._helpOpts.mark
} : undefined },
globalCliOptions: this._globalOpts
});
this.adapter(cli);
if (this._helpOpts) this.applyGlobalInterceptors(cliHelpInterceptor({
colors: this._helpOpts.colors,
lookupLevel: this._helpOpts.lookupLevel
}));
return this.init();
}
constructor(...args) {
super(...args), _define_property(this, "_helpOpts", void 0), _define_property(this, "_globalOpts", void 0);
}
};
//#endregion
export { Cli, CliAlias, CliApp, CliExample, CliGlobalOption, CliHelpInterceptor, CliOption, Controller, Description, Intercept, MoostCli, Optional, Param, cliHelpInterceptor, useCliContext };