@clerc/core
Version:
829 lines (821 loc) • 26.6 kB
JavaScript
import { format } from 'node:util';
import { camelCase, arrayStartsWith, toArray } from '@clerc/utils';
import { defu } from 'defu';
import { LiteEmit } from 'lite-emit';
import { typeFlag } from 'type-flag';
import { IS_NODE, IS_ELECTRON, IS_DENO } from 'is-platform';
const s = JSON.stringify;
class CommandExistsError extends Error {
constructor(commandName, t) {
super(t("core.commandExists", s(commandName)));
this.commandName = commandName;
}
}
class NoSuchCommandError extends Error {
constructor(commandName, t) {
super(t("core.noSuchCommand", s(commandName)));
this.commandName = commandName;
}
}
class NoCommandGivenError extends Error {
constructor(t) {
super(t("core.noCommandGiven"));
}
}
class CommandNameConflictError extends Error {
constructor(n1, n2, t) {
super(t("core.commandNameConflict", s(n1), s(n2)));
this.n1 = n1;
this.n2 = n2;
}
}
class ScriptNameNotSetError extends Error {
constructor(t) {
super(t("core.scriptNameNotSet"));
}
}
class DescriptionNotSetError extends Error {
constructor(t) {
super(t("core.descriptionNotSet"));
}
}
class VersionNotSetError extends Error {
constructor(t) {
super(t("core.versionNotSet"));
}
}
class InvalidCommandNameError extends Error {
constructor(commandName, t) {
super(t("core.badNameFormat", s(commandName)));
this.commandName = commandName;
}
}
class LocaleNotCalledFirstError extends Error {
constructor(t) {
super(t("core.localeMustBeCalledFirst"));
}
}
const locales = {
"en": {
"core.commandExists": 'Command "%s" exists.',
"core.noSuchCommand": "No such command: %s.",
"core.noCommandGiven": "No command given.",
"core.commandNameConflict": "Command name %s conflicts with %s. Maybe caused by alias.",
"core.scriptNameNotSet": "Name not set.",
"core.descriptionNotSet": "Description not set.",
"core.versionNotSet": "Version not set.",
"core.badNameFormat": "Bad name format: %s.",
"core.localeMustBeCalledFirst": "locale() or fallbackLocale() must be called at first.",
"core.cliParseMustBeCalled": "cli.parse() must be called.",
"core.spreadParameterMustBeLast": "Invalid Parameter: Spread parameter %s must be last.",
"core.requiredParameterCannotComeAfterOptionalParameter": "Invalid Parameter: Required parameter %s cannot come after optional parameter %s.",
"core.parameterMustBeWrappedInBrackets": "Invalid Parameter: Parameter %s must be wrapped in <> (required parameter) or [] (optional parameter).",
"core.parameterIsUsedMoreThanOnce": "Invalid Parameter: Parameter %s is used more than once.",
"core.missingRequiredParameter": "Missing required parameter %s."
},
"zh-CN": {
"core.commandExists": '\u547D\u4EE4 "%s" \u5DF2\u5B58\u5728\u3002',
"core.noSuchCommand": "\u627E\u4E0D\u5230\u547D\u4EE4: %s\u3002",
"core.noCommandGiven": "\u6CA1\u6709\u8F93\u5165\u547D\u4EE4\u3002",
"core.commandNameConflict": "\u547D\u4EE4\u540D\u79F0 %s \u548C %s \u51B2\u7A81\u3002 \u53EF\u80FD\u662F\u7531\u4E8E\u522B\u540D\u5BFC\u81F4\u7684\u3002",
"core.scriptNameNotSet": "\u672A\u8BBE\u7F6E CLI Script \u540D\u79F0\u3002",
"core.descriptionNotSet": "\u672A\u8BBE\u7F6E CLI \u63CF\u8FF0\u3002",
"core.versionNotSet": "\u672A\u8BBE\u7F6E CLI \u7248\u672C\u3002",
"core.badNameFormat": "\u9519\u8BEF\u7684\u547D\u4EE4\u540D\u5B57\u683C\u5F0F: %s\u3002",
"core.localeMustBeCalledFirst": "locale() \u6216 fallbackLocale() \u5FC5\u987B\u5728\u6700\u5F00\u59CB\u8C03\u7528\u3002",
"core.cliParseMustBeCalled": "cli.parse() \u5FC5\u987B\u88AB\u8C03\u7528\u3002",
"core.spreadParameterMustBeLast": "\u4E0D\u5408\u6CD5\u7684\u53C2\u6570: \u5C55\u5F00\u53C2\u6570 %s \u5FC5\u987B\u5728\u6700\u540E\u3002",
"core.requiredParameterCannotComeAfterOptionalParameter": "\u4E0D\u5408\u6CD5\u7684\u53C2\u6570: \u5FC5\u586B\u53C2\u6570 %s \u4E0D\u80FD\u5728\u53EF\u9009\u53C2\u6570 %s \u4E4B\u540E\u3002",
"core.parameterMustBeWrappedInBrackets": "\u4E0D\u5408\u6CD5\u7684\u53C2\u6570: \u53C2\u6570 %s \u5FC5\u987B\u88AB <> (\u5FC5\u586B\u53C2\u6570) \u6216 [] (\u53EF\u9009\u53C2\u6570) \u5305\u88F9\u3002",
"core.parameterIsUsedMoreThanOnce": "\u4E0D\u5408\u6CD5\u7684\u53C2\u6570: \u53C2\u6570 %s \u88AB\u4F7F\u7528\u4E86\u591A\u6B21\u3002",
"core.missingRequiredParameter": "\u7F3A\u5C11\u5FC5\u586B\u53C2\u6570 %s\u3002"
}
};
const { stringify } = JSON;
function parseParameters(parameters, t) {
const parsedParameters = [];
let hasOptional;
let hasSpread;
for (const parameter of parameters) {
if (hasSpread) {
throw new Error(
t("core.spreadParameterMustBeLast", stringify(hasSpread))
);
}
const firstCharacter = parameter[0];
const lastCharacter = parameter[parameter.length - 1];
let required;
if (firstCharacter === "<" && lastCharacter === ">") {
required = true;
if (hasOptional) {
throw new Error(
t(
"core.requiredParameterMustBeBeforeOptional",
stringify(parameter),
stringify(hasOptional)
)
);
}
}
if (firstCharacter === "[" && lastCharacter === "]") {
required = false;
hasOptional = parameter;
}
if (required === void 0) {
throw new Error(
t("core.parameterMustBeWrappedInBrackets", stringify(parameter))
);
}
let name = parameter.slice(1, -1);
const spread = name.slice(-3) === "...";
if (spread) {
hasSpread = parameter;
name = name.slice(0, -3);
}
parsedParameters.push({
name,
required,
spread
});
}
return parsedParameters;
}
function mapParametersToArguments(mapping, parameters, cliArguments, t) {
for (let i = 0; i < parameters.length; i += 1) {
const { name, required, spread } = parameters[i];
const camelCaseName = camelCase(name);
if (camelCaseName in mapping) {
throw new Error(t("core.parameterIsUsedMoreThanOnce", stringify(name)));
}
const value = spread ? cliArguments.slice(i) : cliArguments[i];
if (spread) {
i = parameters.length;
}
if (required && (!value || spread && value.length === 0)) {
throw new Error(t("core.missingRequiredParameter", stringify(name)));
}
mapping[camelCaseName] = value;
}
}
function setCommand(commandsMap, commands, command, t) {
if (command.alias) {
const aliases = toArray(command.alias);
for (const alias of aliases) {
if (alias in commands) {
throw new CommandNameConflictError(
commands[alias].name,
command.name,
t
);
}
commandsMap.set(typeof alias === "symbol" ? alias : alias.split(" "), {
...command,
__isAlias: true
});
}
}
}
function resolveFlattenCommands(commands, t) {
const commandsMap = /* @__PURE__ */ new Map();
if (commands[Root]) {
commandsMap.set(Root, commands[Root]);
setCommand(commandsMap, commands, commands[Root], t);
}
for (const command of Object.values(commands)) {
setCommand(commandsMap, commands, command, t);
commandsMap.set(command.name.split(" "), command);
}
return commandsMap;
}
function resolveCommand(commands, argv, t) {
var _a;
const commandsMap = resolveFlattenCommands(commands, t);
for (const [name, command] of commandsMap.entries()) {
const parsed = typeFlag((_a = command == null ? void 0 : command.flags) != null ? _a : /* @__PURE__ */ Object.create(null), [...argv]);
const { _: args } = parsed;
if (name === Root) {
continue;
}
if (arrayStartsWith(args, name)) {
return [command, name];
}
}
if (commandsMap.has(Root)) {
return [commandsMap.get(Root), Root];
}
return [void 0, void 0];
}
const resolveArgv = () => IS_NODE ? process.argv.slice(IS_ELECTRON ? 1 : 2) : IS_DENO ? (
// @ts-expect-error Ignore
Deno.args
) : [];
function compose(interceptors) {
const interceptorMap = {
pre: [],
normal: [],
post: []
};
for (const interceptor of interceptors) {
const objectInterceptor = typeof interceptor === "object" ? interceptor : { fn: interceptor };
const { enforce, fn } = objectInterceptor;
if (enforce === "post" || enforce === "pre") {
interceptorMap[enforce].push(fn);
} else {
interceptorMap.normal.push(fn);
}
}
const mergedInterceptorFns = [
...interceptorMap.pre,
...interceptorMap.normal,
...interceptorMap.post
];
return (ctx) => {
return dispatch(0);
function dispatch(i) {
const interceptor = mergedInterceptorFns[i];
return interceptor(ctx, dispatch.bind(null, i + 1));
}
};
}
const INVALID_RE = /\s{2,}/;
const isValidName = (name) => name === Root ? true : !(name.startsWith(" ") || name.endsWith(" ")) && !INVALID_RE.test(name);
const withBrackets = (s, isOptional) => isOptional ? `[${s}]` : `<${s}>`;
const ROOT = "<Root>";
const formatCommandName = (name) => Array.isArray(name) ? name.join(" ") : typeof name === "string" ? name : ROOT;
const detectLocale = () => process.env.CLERC_LOCALE ? process.env.CLERC_LOCALE : Intl.DateTimeFormat().resolvedOptions().locale;
const stripFlags = (argv) => argv.filter((arg) => !arg.startsWith("-"));
var __accessCheck = (obj, member, msg) => {
if (!member.has(obj))
throw TypeError("Cannot " + msg);
};
var __privateGet = (obj, member, getter) => {
__accessCheck(obj, member, "read from private field");
return getter ? getter.call(obj) : member.get(obj);
};
var __privateAdd = (obj, member, value) => {
if (member.has(obj))
throw TypeError("Cannot add the same private member more than once");
member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
};
var __privateSet = (obj, member, value, setter) => {
__accessCheck(obj, member, "write to private field");
setter ? setter.call(obj, value) : member.set(obj, value);
return value;
};
var __privateMethod = (obj, member, method) => {
__accessCheck(obj, member, "access private method");
return method;
};
var _name, _scriptName, _description, _version, _interceptors, _commands, _commandEmitter, _flags, _usedNames, _argv, _errorHandlers, _isOtherMethodCalled, _defaultLocale, _locale, _locales, _hasRootOrAlias, hasRootOrAlias_get, _hasRoot, hasRoot_get, _addCoreLocales, addCoreLocales_fn, _otherMethodCalled, otherMethodCalled_fn, _command, command_fn, _validateMeta, validateMeta_fn, _getContext, getContext_fn, _handleError, handleError_fn, _callWithErrorHandling, callWithErrorHandling_fn, _runMatchedCommand, runMatchedCommand_fn;
const Root = Symbol.for("Clerc.Root");
const _Clerc = class _Clerc {
constructor(scriptName, description, version) {
__privateAdd(this, _hasRootOrAlias);
__privateAdd(this, _hasRoot);
__privateAdd(this, _addCoreLocales);
__privateAdd(this, _otherMethodCalled);
__privateAdd(this, _command);
__privateAdd(this, _validateMeta);
__privateAdd(this, _getContext);
__privateAdd(this, _handleError);
__privateAdd(this, _callWithErrorHandling);
__privateAdd(this, _runMatchedCommand);
__privateAdd(this, _name, "");
__privateAdd(this, _scriptName, "");
__privateAdd(this, _description, "");
__privateAdd(this, _version, "");
__privateAdd(this, _interceptors, []);
__privateAdd(this, _commands, /* @__PURE__ */ Object.create(null));
__privateAdd(this, _commandEmitter, new LiteEmit({
errorHandler: (msg) => {
__privateMethod(this, _handleError, handleError_fn).call(this, new Error(msg));
}
}));
__privateAdd(this, _flags, /* @__PURE__ */ Object.create(null));
__privateAdd(this, _usedNames, /* @__PURE__ */ new Set());
__privateAdd(this, _argv, void 0);
__privateAdd(this, _errorHandlers, []);
__privateAdd(this, _isOtherMethodCalled, false);
__privateAdd(this, _defaultLocale, "en");
__privateAdd(this, _locale, "en");
__privateAdd(this, _locales, /* @__PURE__ */ Object.create(null));
__privateSet(this, _scriptName, scriptName != null ? scriptName : __privateGet(this, _scriptName));
__privateSet(this, _description, description != null ? description : __privateGet(this, _description));
__privateSet(this, _version, version != null ? version : __privateGet(this, _version));
__privateSet(this, _locale, detectLocale());
__privateMethod(this, _addCoreLocales, addCoreLocales_fn).call(this);
}
get i18n() {
return {
add: (locales2) => {
__privateSet(this, _locales, defu(__privateGet(this, _locales), locales2));
},
t: (name, ...args) => {
const localeObject = __privateGet(this, _locales)[__privateGet(this, _locale)] || __privateGet(this, _locales)[__privateGet(this, _defaultLocale)];
const defaultLocaleObject = __privateGet(this, _locales)[__privateGet(this, _defaultLocale)];
return localeObject[name] ? format(localeObject[name], ...args) : defaultLocaleObject[name] ? format(defaultLocaleObject[name], ...args) : void 0;
}
};
}
get _name() {
return __privateGet(this, _name) || __privateGet(this, _scriptName);
}
get _scriptName() {
return __privateGet(this, _scriptName);
}
get _description() {
return __privateGet(this, _description);
}
get _version() {
return __privateGet(this, _version);
}
/**
* @deprecated This is a typo. Use `_interceptor` instead.
*/
get _inspectors() {
return __privateGet(this, _interceptors);
}
get _interceptors() {
return __privateGet(this, _interceptors);
}
get _commands() {
return __privateGet(this, _commands);
}
get _flags() {
return __privateGet(this, _flags);
}
/**
* Create a new cli
*
* @example
*
* ```ts
* const cli = Clerc.create();
* ```
*
* @param name
* @param description
* @param version
* @returns
*/
static create(name, description, version) {
return new _Clerc(name, description, version);
}
/**
* Set the name of the cli
*
* @example
*
* ```ts
* Clerc.create().name("test");
* ```
*
* @param name
* @returns
*/
name(name) {
__privateMethod(this, _otherMethodCalled, otherMethodCalled_fn).call(this);
__privateSet(this, _name, name);
return this;
}
/**
* Set the script name of the cli
*
* @example
*
* ```ts
* Clerc.create().scriptName("test");
* ```
*
* @param scriptName
* @returns
*/
scriptName(scriptName) {
__privateMethod(this, _otherMethodCalled, otherMethodCalled_fn).call(this);
__privateSet(this, _scriptName, scriptName);
return this;
}
/**
* Set the description of the cli
*
* @example
*
* ```ts
* Clerc.create().description("test cli");
* ```
*
* @param description
* @returns
*/
description(description) {
__privateMethod(this, _otherMethodCalled, otherMethodCalled_fn).call(this);
__privateSet(this, _description, description);
return this;
}
/**
* Set the version of the cli
*
* @example
*
* ```ts
* Clerc.create().version("1.0.0");
* ```
*
* @param version
* @returns
*/
version(version) {
__privateMethod(this, _otherMethodCalled, otherMethodCalled_fn).call(this);
__privateSet(this, _version, version);
return this;
}
/**
* Set the Locale You must call this method once after you created the Clerc
* instance.
*
* @example
*
* ```ts
* Clerc.create()
* .locale("en")
* .command(...)
* ```
*
* @param locale
* @returns
*/
locale(locale) {
if (__privateGet(this, _isOtherMethodCalled)) {
throw new LocaleNotCalledFirstError(this.i18n.t);
}
__privateSet(this, _locale, locale);
return this;
}
/**
* Set the fallback Locale You must call this method once after you created
* the Clerc instance.
*
* @example
*
* ```ts
* Clerc.create()
* .fallbackLocale("en")
* .command(...)
* ```
*
* @param fallbackLocale
* @returns
*/
fallbackLocale(fallbackLocale) {
if (__privateGet(this, _isOtherMethodCalled)) {
throw new LocaleNotCalledFirstError(this.i18n.t);
}
__privateSet(this, _defaultLocale, fallbackLocale);
return this;
}
/**
* Register a error handler
*
* @example
*
* ```ts
* Clerc.create().errorHandler((err) => {
* console.log(err);
* });
* ```
*
* @param handler
* @returns
*/
errorHandler(handler) {
__privateGet(this, _errorHandlers).push(handler);
return this;
}
command(nameOrCommand, description, options = {}) {
__privateMethod(this, _callWithErrorHandling, callWithErrorHandling_fn).call(this, () => {
if (Array.isArray(nameOrCommand)) {
for (const command of nameOrCommand) {
__privateMethod(this, _command, command_fn).call(this, command);
}
} else {
__privateMethod(this, _command, command_fn).call(this, nameOrCommand, description, options);
}
});
return this;
}
/**
* Register a global flag
*
* @example
*
* ```ts
* Clerc.create().flag("help", "help", {
* alias: "h",
* type: Boolean,
* });
* ```
*
* @param name
* @param description
* @param options
* @returns
*/
flag(name, description, options) {
__privateGet(this, _flags)[name] = {
description,
...options
};
return this;
}
/**
* Register a handler
*
* @example
*
* ```ts
* Clerc.create()
* .command("test", "test command")
* .on("test", (ctx) => {
* console.log(ctx);
* });
* ```
*
* @param name
* @param handler
* @returns
*/
on(name, handler) {
__privateGet(this, _commandEmitter).on(name, handler);
return this;
}
/**
* Use a plugin
*
* @example
*
* ```ts
* Clerc.create().use(plugin);
* ```
*
* @param plugin
* @returns
*/
use(plugin) {
__privateMethod(this, _otherMethodCalled, otherMethodCalled_fn).call(this);
return plugin.setup(this);
}
/**
* @deprecated This is a typo. Use `intercetor()` instead.
*/
inspector(interceptor) {
return this.interceptor(interceptor);
}
/**
* Register a interceptor
*
* @example
*
* ```ts
* Clerc.create().interceptor((ctx, next) => {
* console.log(ctx);
* next();
* });
* ```
*
* @param interceptor
* @returns
*/
interceptor(interceptor) {
__privateMethod(this, _otherMethodCalled, otherMethodCalled_fn).call(this);
__privateGet(this, _interceptors).push(interceptor);
return this;
}
/**
* Parse the command line arguments
*
* @example
*
* ```ts
* Clerc.create().parse(process.argv.slice(2)); // Optional
* ```
*
* @param args
* @param optionsOrArgv
* @returns
*/
parse(optionsOrArgv = resolveArgv()) {
__privateMethod(this, _otherMethodCalled, otherMethodCalled_fn).call(this);
const { argv, run } = Array.isArray(optionsOrArgv) ? {
argv: optionsOrArgv,
run: true
} : {
argv: resolveArgv(),
...optionsOrArgv
};
__privateSet(this, _argv, [...argv]);
__privateMethod(this, _validateMeta, validateMeta_fn).call(this);
if (run) {
this.runMatchedCommand();
}
return this;
}
/**
* Run matched command
*
* @example
*
* ```ts
* Clerc.create().parse({ run: false }).runMatchedCommand();
* ```
*
* @returns
*/
runMatchedCommand() {
__privateMethod(this, _callWithErrorHandling, callWithErrorHandling_fn).call(this, () => __privateMethod(this, _runMatchedCommand, runMatchedCommand_fn).call(this));
process.title = __privateGet(this, _name);
return this;
}
};
_name = new WeakMap();
_scriptName = new WeakMap();
_description = new WeakMap();
_version = new WeakMap();
_interceptors = new WeakMap();
_commands = new WeakMap();
_commandEmitter = new WeakMap();
_flags = new WeakMap();
_usedNames = new WeakMap();
_argv = new WeakMap();
_errorHandlers = new WeakMap();
_isOtherMethodCalled = new WeakMap();
_defaultLocale = new WeakMap();
_locale = new WeakMap();
_locales = new WeakMap();
_hasRootOrAlias = new WeakSet();
hasRootOrAlias_get = function() {
return __privateGet(this, _usedNames).has(Root);
};
_hasRoot = new WeakSet();
hasRoot_get = function() {
return Object.prototype.hasOwnProperty.call(this._commands, Root);
};
_addCoreLocales = new WeakSet();
addCoreLocales_fn = function() {
this.i18n.add(locales);
};
_otherMethodCalled = new WeakSet();
otherMethodCalled_fn = function() {
__privateSet(this, _isOtherMethodCalled, true);
};
_command = new WeakSet();
command_fn = function(nameOrCommand, description, options = {}) {
__privateMethod(this, _otherMethodCalled, otherMethodCalled_fn).call(this);
const { t } = this.i18n;
const checkIsCommandObject = (nameOrCommand2) => !(typeof nameOrCommand2 === "string" || nameOrCommand2 === Root);
const isCommandObject = checkIsCommandObject(nameOrCommand);
const name = isCommandObject ? nameOrCommand.name : nameOrCommand;
if (!isValidName(name)) {
throw new InvalidCommandNameError(name, t);
}
const { handler = void 0, ...commandToSave } = isCommandObject ? nameOrCommand : { name, description, ...options };
const nameList = [commandToSave.name];
const aliasList = commandToSave.alias ? toArray(commandToSave.alias) : [];
commandToSave.alias && nameList.push(...aliasList);
for (const name2 of nameList) {
if (__privateGet(this, _usedNames).has(name2)) {
throw new CommandExistsError(formatCommandName(name2), t);
}
}
__privateGet(this, _commands)[name] = commandToSave;
__privateGet(this, _usedNames).add(commandToSave.name);
for (const a of aliasList) {
__privateGet(this, _usedNames).add(a);
}
isCommandObject && handler && this.on(nameOrCommand.name, handler);
return this;
};
_validateMeta = new WeakSet();
validateMeta_fn = function() {
const { t } = this.i18n;
if (!__privateGet(this, _scriptName)) {
throw new ScriptNameNotSetError(t);
}
if (!__privateGet(this, _description)) {
throw new DescriptionNotSetError(t);
}
if (!__privateGet(this, _version)) {
throw new VersionNotSetError(t);
}
};
_getContext = new WeakSet();
getContext_fn = function(getCommand) {
var _a;
const argv = __privateGet(this, _argv);
const { t } = this.i18n;
const [command, called] = getCommand();
const isCommandResolved = !!command;
const flagsMerged = {
...__privateGet(this, _flags),
...command == null ? void 0 : command.flags
};
const parsed = typeFlag(flagsMerged, [...argv]);
const parametersOffset = (command == null ? void 0 : command.name) === Root || called === Root ? 0 : (called == null ? void 0 : called.length) ? called.length : command == null ? void 0 : command.name.split(" ").length;
const { _: args, flags, unknownFlags } = parsed;
let parameters = !isCommandResolved || command.name === Root ? args : args.slice(parametersOffset);
let commandParameters = (_a = command == null ? void 0 : command.parameters) != null ? _a : [];
const hasEof = commandParameters.indexOf("--");
const eofParameters = commandParameters.slice(hasEof + 1) || [];
const mapping = /* @__PURE__ */ Object.create(null);
if (hasEof > -1 && eofParameters.length > 0) {
commandParameters = commandParameters.slice(0, hasEof);
const eofArguments = args["--"];
parameters = parameters.slice(0, -eofArguments.length || void 0);
mapParametersToArguments(
mapping,
parseParameters(commandParameters, t),
parameters,
t
);
mapParametersToArguments(
mapping,
parseParameters(eofParameters, t),
eofArguments,
t
);
} else {
mapParametersToArguments(
mapping,
parseParameters(commandParameters, t),
parameters,
t
);
}
const mergedFlags = { ...flags, ...unknownFlags };
const context = {
name: command == null ? void 0 : command.name,
called: Array.isArray(called) ? called.join(" ") : called,
resolved: isCommandResolved,
hasRootOrAlias: __privateGet(this, _hasRootOrAlias, hasRootOrAlias_get),
hasRoot: __privateGet(this, _hasRoot, hasRoot_get),
raw: { ...parsed, parameters, mergedFlags },
parameters: mapping,
flags,
unknownFlags,
cli: this
};
return context;
};
_handleError = new WeakSet();
handleError_fn = function(e) {
if (__privateGet(this, _errorHandlers).length > 0) {
for (const cb of __privateGet(this, _errorHandlers)) {
cb(e);
}
} else {
throw e;
}
};
_callWithErrorHandling = new WeakSet();
callWithErrorHandling_fn = function(fn) {
try {
fn();
} catch (e) {
__privateMethod(this, _handleError, handleError_fn).call(this, e);
}
};
_runMatchedCommand = new WeakSet();
runMatchedCommand_fn = function() {
__privateMethod(this, _otherMethodCalled, otherMethodCalled_fn).call(this);
const { t } = this.i18n;
const argv = __privateGet(this, _argv);
if (!argv) {
throw new Error(t("core.cliParseMustBeCalled"));
}
const getCommand = () => resolveCommand(__privateGet(this, _commands), argv, t);
const getContext = () => __privateMethod(this, _getContext, getContext_fn).call(this, getCommand);
const emitHandler = {
enforce: "post",
fn: (ctx) => {
const [command] = getCommand();
const stringName = stripFlags(argv).join(" ");
if (!command) {
const error = stringName ? new NoSuchCommandError(stringName, t) : new NoCommandGivenError(t);
throw error;
}
__privateGet(this, _commandEmitter).emit(command.name, ctx);
}
};
const interceptor = [...__privateGet(this, _interceptors), emitHandler];
const callInterceptor = compose(interceptor);
callInterceptor(getContext());
};
let Clerc = _Clerc;
const definePlugin = (p) => p;
const defineHandler = (_cli, _key, handler) => handler;
const defineInterceptor = (_cli, interceptor) => interceptor;
const defineInspector = defineInterceptor;
const defineCommand = (command, handler) => ({
...command,
handler
});
export { Clerc, CommandExistsError, CommandNameConflictError, DescriptionNotSetError, InvalidCommandNameError, LocaleNotCalledFirstError, NoCommandGivenError, NoSuchCommandError, Root, ScriptNameNotSetError, VersionNotSetError, compose, defineCommand, defineHandler, defineInspector, defineInterceptor, definePlugin, detectLocale, formatCommandName, isValidName, resolveArgv, resolveCommand, resolveFlattenCommands, stripFlags, withBrackets };