@lynx-js/rspeedy
Version:
A webpack/rspack-based frontend toolchain for Lynx
947 lines • 91 kB
JavaScript
import { __webpack_require__ } from "./src_cli_main_ts-node_child_process-node_events-node_fs-node_path-node_process.js";
import "./src_cli_main_ts-node_child_process-node_events-node_fs-node_path-node_process.js";
__webpack_require__.add({
"../../../node_modules/.pnpm/commander@13.1.0/node_modules/commander/index.js" (__unused_rspack_module, exports, __webpack_require__) {
const { Argument } = __webpack_require__("../../../node_modules/.pnpm/commander@13.1.0/node_modules/commander/lib/argument.js");
const { Command } = __webpack_require__("../../../node_modules/.pnpm/commander@13.1.0/node_modules/commander/lib/command.js");
const { CommanderError, InvalidArgumentError } = __webpack_require__("../../../node_modules/.pnpm/commander@13.1.0/node_modules/commander/lib/error.js");
const { Help } = __webpack_require__("../../../node_modules/.pnpm/commander@13.1.0/node_modules/commander/lib/help.js");
const { Option } = __webpack_require__("../../../node_modules/.pnpm/commander@13.1.0/node_modules/commander/lib/option.js");
exports.DM = new Command();
exports.gu = (name)=>new Command(name);
exports.Ww = (flags, description)=>new Option(flags, description);
exports.er = (name, description)=>new Argument(name, description);
exports.uB = Command;
exports.c$ = Option;
exports.ef = Argument;
exports._V = Help;
exports.b7 = CommanderError;
exports.Di = InvalidArgumentError;
exports.a2 = InvalidArgumentError;
},
"../../../node_modules/.pnpm/commander@13.1.0/node_modules/commander/lib/argument.js" (__unused_rspack_module, exports, __webpack_require__) {
const { InvalidArgumentError } = __webpack_require__("../../../node_modules/.pnpm/commander@13.1.0/node_modules/commander/lib/error.js");
class Argument {
constructor(name, description){
this.description = description || '';
this.variadic = false;
this.parseArg = void 0;
this.defaultValue = void 0;
this.defaultValueDescription = void 0;
this.argChoices = void 0;
switch(name[0]){
case '<':
this.required = true;
this._name = name.slice(1, -1);
break;
case '[':
this.required = false;
this._name = name.slice(1, -1);
break;
default:
this.required = true;
this._name = name;
break;
}
if (this._name.length > 3 && '...' === this._name.slice(-3)) {
this.variadic = true;
this._name = this._name.slice(0, -3);
}
}
name() {
return this._name;
}
_concatValue(value, previous) {
if (previous === this.defaultValue || !Array.isArray(previous)) return [
value
];
return previous.concat(value);
}
default(value, description) {
this.defaultValue = value;
this.defaultValueDescription = description;
return this;
}
argParser(fn) {
this.parseArg = fn;
return this;
}
choices(values) {
this.argChoices = values.slice();
this.parseArg = (arg, previous)=>{
if (!this.argChoices.includes(arg)) throw new InvalidArgumentError(`Allowed choices are ${this.argChoices.join(', ')}.`);
if (this.variadic) return this._concatValue(arg, previous);
return arg;
};
return this;
}
argRequired() {
this.required = true;
return this;
}
argOptional() {
this.required = false;
return this;
}
}
function humanReadableArgName(arg) {
const nameOutput = arg.name() + (true === arg.variadic ? '...' : '');
return arg.required ? '<' + nameOutput + '>' : '[' + nameOutput + ']';
}
exports.Argument = Argument;
exports.humanReadableArgName = humanReadableArgName;
},
"../../../node_modules/.pnpm/commander@13.1.0/node_modules/commander/lib/command.js" (__unused_rspack_module, exports, __webpack_require__) {
const EventEmitter = __webpack_require__("node:events").EventEmitter;
const childProcess = __webpack_require__("node:child_process");
const path = __webpack_require__("node:path?435f");
const fs = __webpack_require__("node:fs?9592");
const process = __webpack_require__("node:process?ecf8");
const { Argument, humanReadableArgName } = __webpack_require__("../../../node_modules/.pnpm/commander@13.1.0/node_modules/commander/lib/argument.js");
const { CommanderError } = __webpack_require__("../../../node_modules/.pnpm/commander@13.1.0/node_modules/commander/lib/error.js");
const { Help, stripColor } = __webpack_require__("../../../node_modules/.pnpm/commander@13.1.0/node_modules/commander/lib/help.js");
const { Option, DualOptions } = __webpack_require__("../../../node_modules/.pnpm/commander@13.1.0/node_modules/commander/lib/option.js");
const { suggestSimilar } = __webpack_require__("../../../node_modules/.pnpm/commander@13.1.0/node_modules/commander/lib/suggestSimilar.js");
class Command extends EventEmitter {
constructor(name){
super();
this.commands = [];
this.options = [];
this.parent = null;
this._allowUnknownOption = false;
this._allowExcessArguments = false;
this.registeredArguments = [];
this._args = this.registeredArguments;
this.args = [];
this.rawArgs = [];
this.processedArgs = [];
this._scriptPath = null;
this._name = name || '';
this._optionValues = {};
this._optionValueSources = {};
this._storeOptionsAsProperties = false;
this._actionHandler = null;
this._executableHandler = false;
this._executableFile = null;
this._executableDir = null;
this._defaultCommandName = null;
this._exitCallback = null;
this._aliases = [];
this._combineFlagAndOptionalValue = true;
this._description = '';
this._summary = '';
this._argsDescription = void 0;
this._enablePositionalOptions = false;
this._passThroughOptions = false;
this._lifeCycleHooks = {};
this._showHelpAfterError = false;
this._showSuggestionAfterError = true;
this._savedState = null;
this._outputConfiguration = {
writeOut: (str)=>process.stdout.write(str),
writeErr: (str)=>process.stderr.write(str),
outputError: (str, write)=>write(str),
getOutHelpWidth: ()=>process.stdout.isTTY ? process.stdout.columns : void 0,
getErrHelpWidth: ()=>process.stderr.isTTY ? process.stderr.columns : void 0,
getOutHasColors: ()=>useColor() ?? (process.stdout.isTTY && process.stdout.hasColors?.()),
getErrHasColors: ()=>useColor() ?? (process.stderr.isTTY && process.stderr.hasColors?.()),
stripColor: (str)=>stripColor(str)
};
this._hidden = false;
this._helpOption = void 0;
this._addImplicitHelpCommand = void 0;
this._helpCommand = void 0;
this._helpConfiguration = {};
}
copyInheritedSettings(sourceCommand) {
this._outputConfiguration = sourceCommand._outputConfiguration;
this._helpOption = sourceCommand._helpOption;
this._helpCommand = sourceCommand._helpCommand;
this._helpConfiguration = sourceCommand._helpConfiguration;
this._exitCallback = sourceCommand._exitCallback;
this._storeOptionsAsProperties = sourceCommand._storeOptionsAsProperties;
this._combineFlagAndOptionalValue = sourceCommand._combineFlagAndOptionalValue;
this._allowExcessArguments = sourceCommand._allowExcessArguments;
this._enablePositionalOptions = sourceCommand._enablePositionalOptions;
this._showHelpAfterError = sourceCommand._showHelpAfterError;
this._showSuggestionAfterError = sourceCommand._showSuggestionAfterError;
return this;
}
_getCommandAndAncestors() {
const result = [];
for(let command = this; command; command = command.parent)result.push(command);
return result;
}
command(nameAndArgs, actionOptsOrExecDesc, execOpts) {
let desc = actionOptsOrExecDesc;
let opts = execOpts;
if ('object' == typeof desc && null !== desc) {
opts = desc;
desc = null;
}
opts = opts || {};
const [, name, args] = nameAndArgs.match(/([^ ]+) *(.*)/);
const cmd = this.createCommand(name);
if (desc) {
cmd.description(desc);
cmd._executableHandler = true;
}
if (opts.isDefault) this._defaultCommandName = cmd._name;
cmd._hidden = !!(opts.noHelp || opts.hidden);
cmd._executableFile = opts.executableFile || null;
if (args) cmd.arguments(args);
this._registerCommand(cmd);
cmd.parent = this;
cmd.copyInheritedSettings(this);
if (desc) return this;
return cmd;
}
createCommand(name) {
return new Command(name);
}
createHelp() {
return Object.assign(new Help(), this.configureHelp());
}
configureHelp(configuration) {
if (void 0 === configuration) return this._helpConfiguration;
this._helpConfiguration = configuration;
return this;
}
configureOutput(configuration) {
if (void 0 === configuration) return this._outputConfiguration;
Object.assign(this._outputConfiguration, configuration);
return this;
}
showHelpAfterError(displayHelp = true) {
if ('string' != typeof displayHelp) displayHelp = !!displayHelp;
this._showHelpAfterError = displayHelp;
return this;
}
showSuggestionAfterError(displaySuggestion = true) {
this._showSuggestionAfterError = !!displaySuggestion;
return this;
}
addCommand(cmd, opts) {
if (!cmd._name) throw new Error(`Command passed to .addCommand() must have a name
- specify the name in Command constructor or using .name()`);
opts = opts || {};
if (opts.isDefault) this._defaultCommandName = cmd._name;
if (opts.noHelp || opts.hidden) cmd._hidden = true;
this._registerCommand(cmd);
cmd.parent = this;
cmd._checkForBrokenPassThrough();
return this;
}
createArgument(name, description) {
return new Argument(name, description);
}
argument(name, description, fn, defaultValue) {
const argument = this.createArgument(name, description);
if ('function' == typeof fn) argument.default(defaultValue).argParser(fn);
else argument.default(fn);
this.addArgument(argument);
return this;
}
arguments(names) {
names.trim().split(/ +/).forEach((detail)=>{
this.argument(detail);
});
return this;
}
addArgument(argument) {
const previousArgument = this.registeredArguments.slice(-1)[0];
if (previousArgument && previousArgument.variadic) throw new Error(`only the last argument can be variadic '${previousArgument.name()}'`);
if (argument.required && void 0 !== argument.defaultValue && void 0 === argument.parseArg) throw new Error(`a default value for a required argument is never used: '${argument.name()}'`);
this.registeredArguments.push(argument);
return this;
}
helpCommand(enableOrNameAndArgs, description) {
if ('boolean' == typeof enableOrNameAndArgs) {
this._addImplicitHelpCommand = enableOrNameAndArgs;
return this;
}
enableOrNameAndArgs = enableOrNameAndArgs ?? 'help [command]';
const [, helpName, helpArgs] = enableOrNameAndArgs.match(/([^ ]+) *(.*)/);
const helpDescription = description ?? 'display help for command';
const helpCommand = this.createCommand(helpName);
helpCommand.helpOption(false);
if (helpArgs) helpCommand.arguments(helpArgs);
if (helpDescription) helpCommand.description(helpDescription);
this._addImplicitHelpCommand = true;
this._helpCommand = helpCommand;
return this;
}
addHelpCommand(helpCommand, deprecatedDescription) {
if ('object' != typeof helpCommand) {
this.helpCommand(helpCommand, deprecatedDescription);
return this;
}
this._addImplicitHelpCommand = true;
this._helpCommand = helpCommand;
return this;
}
_getHelpCommand() {
const hasImplicitHelpCommand = this._addImplicitHelpCommand ?? (this.commands.length && !this._actionHandler && !this._findCommand('help'));
if (hasImplicitHelpCommand) {
if (void 0 === this._helpCommand) this.helpCommand(void 0, void 0);
return this._helpCommand;
}
return null;
}
hook(event, listener) {
const allowedValues = [
'preSubcommand',
'preAction',
'postAction'
];
if (!allowedValues.includes(event)) throw new Error(`Unexpected value for event passed to hook : '${event}'.
Expecting one of '${allowedValues.join("', '")}'`);
if (this._lifeCycleHooks[event]) this._lifeCycleHooks[event].push(listener);
else this._lifeCycleHooks[event] = [
listener
];
return this;
}
exitOverride(fn) {
if (fn) this._exitCallback = fn;
else this._exitCallback = (err)=>{
if ('commander.executeSubCommandAsync' !== err.code) throw err;
};
return this;
}
_exit(exitCode, code, message) {
if (this._exitCallback) this._exitCallback(new CommanderError(exitCode, code, message));
process.exit(exitCode);
}
action(fn) {
const listener = (args)=>{
const expectedArgsCount = this.registeredArguments.length;
const actionArgs = args.slice(0, expectedArgsCount);
if (this._storeOptionsAsProperties) actionArgs[expectedArgsCount] = this;
else actionArgs[expectedArgsCount] = this.opts();
actionArgs.push(this);
return fn.apply(this, actionArgs);
};
this._actionHandler = listener;
return this;
}
createOption(flags, description) {
return new Option(flags, description);
}
_callParseArg(target, value, previous, invalidArgumentMessage) {
try {
return target.parseArg(value, previous);
} catch (err) {
if ('commander.invalidArgument' === err.code) {
const message = `${invalidArgumentMessage} ${err.message}`;
this.error(message, {
exitCode: err.exitCode,
code: err.code
});
}
throw err;
}
}
_registerOption(option) {
const matchingOption = option.short && this._findOption(option.short) || option.long && this._findOption(option.long);
if (matchingOption) {
const matchingFlag = option.long && this._findOption(option.long) ? option.long : option.short;
throw new Error(`Cannot add option '${option.flags}'${this._name && ` to command '${this._name}'`} due to conflicting flag '${matchingFlag}'
- already used by option '${matchingOption.flags}'`);
}
this.options.push(option);
}
_registerCommand(command) {
const knownBy = (cmd)=>[
cmd.name()
].concat(cmd.aliases());
const alreadyUsed = knownBy(command).find((name)=>this._findCommand(name));
if (alreadyUsed) {
const existingCmd = knownBy(this._findCommand(alreadyUsed)).join('|');
const newCmd = knownBy(command).join('|');
throw new Error(`cannot add command '${newCmd}' as already have command '${existingCmd}'`);
}
this.commands.push(command);
}
addOption(option) {
this._registerOption(option);
const oname = option.name();
const name = option.attributeName();
if (option.negate) {
const positiveLongFlag = option.long.replace(/^--no-/, '--');
if (!this._findOption(positiveLongFlag)) this.setOptionValueWithSource(name, void 0 === option.defaultValue ? true : option.defaultValue, 'default');
} else if (void 0 !== option.defaultValue) this.setOptionValueWithSource(name, option.defaultValue, 'default');
const handleOptionValue = (val, invalidValueMessage, valueSource)=>{
if (null == val && void 0 !== option.presetArg) val = option.presetArg;
const oldValue = this.getOptionValue(name);
if (null !== val && option.parseArg) val = this._callParseArg(option, val, oldValue, invalidValueMessage);
else if (null !== val && option.variadic) val = option._concatValue(val, oldValue);
if (null == val) val = option.negate ? false : option.isBoolean() || option.optional ? true : '';
this.setOptionValueWithSource(name, val, valueSource);
};
this.on('option:' + oname, (val)=>{
const invalidValueMessage = `error: option '${option.flags}' argument '${val}' is invalid.`;
handleOptionValue(val, invalidValueMessage, 'cli');
});
if (option.envVar) this.on('optionEnv:' + oname, (val)=>{
const invalidValueMessage = `error: option '${option.flags}' value '${val}' from env '${option.envVar}' is invalid.`;
handleOptionValue(val, invalidValueMessage, 'env');
});
return this;
}
_optionEx(config, flags, description, fn, defaultValue) {
if ('object' == typeof flags && flags instanceof Option) throw new Error('To add an Option object use addOption() instead of option() or requiredOption()');
const option = this.createOption(flags, description);
option.makeOptionMandatory(!!config.mandatory);
if ('function' == typeof fn) option.default(defaultValue).argParser(fn);
else if (fn instanceof RegExp) {
const regex = fn;
fn = (val, def)=>{
const m = regex.exec(val);
return m ? m[0] : def;
};
option.default(defaultValue).argParser(fn);
} else option.default(fn);
return this.addOption(option);
}
option(flags, description, parseArg, defaultValue) {
return this._optionEx({}, flags, description, parseArg, defaultValue);
}
requiredOption(flags, description, parseArg, defaultValue) {
return this._optionEx({
mandatory: true
}, flags, description, parseArg, defaultValue);
}
combineFlagAndOptionalValue(combine = true) {
this._combineFlagAndOptionalValue = !!combine;
return this;
}
allowUnknownOption(allowUnknown = true) {
this._allowUnknownOption = !!allowUnknown;
return this;
}
allowExcessArguments(allowExcess = true) {
this._allowExcessArguments = !!allowExcess;
return this;
}
enablePositionalOptions(positional = true) {
this._enablePositionalOptions = !!positional;
return this;
}
passThroughOptions(passThrough = true) {
this._passThroughOptions = !!passThrough;
this._checkForBrokenPassThrough();
return this;
}
_checkForBrokenPassThrough() {
if (this.parent && this._passThroughOptions && !this.parent._enablePositionalOptions) throw new Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`);
}
storeOptionsAsProperties(storeAsProperties = true) {
if (this.options.length) throw new Error('call .storeOptionsAsProperties() before adding options');
if (Object.keys(this._optionValues).length) throw new Error('call .storeOptionsAsProperties() before setting option values');
this._storeOptionsAsProperties = !!storeAsProperties;
return this;
}
getOptionValue(key) {
if (this._storeOptionsAsProperties) return this[key];
return this._optionValues[key];
}
setOptionValue(key, value) {
return this.setOptionValueWithSource(key, value, void 0);
}
setOptionValueWithSource(key, value, source) {
if (this._storeOptionsAsProperties) this[key] = value;
else this._optionValues[key] = value;
this._optionValueSources[key] = source;
return this;
}
getOptionValueSource(key) {
return this._optionValueSources[key];
}
getOptionValueSourceWithGlobals(key) {
let source;
this._getCommandAndAncestors().forEach((cmd)=>{
if (void 0 !== cmd.getOptionValueSource(key)) source = cmd.getOptionValueSource(key);
});
return source;
}
_prepareUserArgs(argv, parseOptions) {
if (void 0 !== argv && !Array.isArray(argv)) throw new Error('first parameter to parse must be array or undefined');
parseOptions = parseOptions || {};
if (void 0 === argv && void 0 === parseOptions.from) {
if (process.versions?.electron) parseOptions.from = 'electron';
const execArgv = process.execArgv ?? [];
if (execArgv.includes('-e') || execArgv.includes('--eval') || execArgv.includes('-p') || execArgv.includes('--print')) parseOptions.from = 'eval';
}
if (void 0 === argv) argv = process.argv;
this.rawArgs = argv.slice();
let userArgs;
switch(parseOptions.from){
case void 0:
case 'node':
this._scriptPath = argv[1];
userArgs = argv.slice(2);
break;
case 'electron':
if (process.defaultApp) {
this._scriptPath = argv[1];
userArgs = argv.slice(2);
} else userArgs = argv.slice(1);
break;
case 'user':
userArgs = argv.slice(0);
break;
case 'eval':
userArgs = argv.slice(1);
break;
default:
throw new Error(`unexpected parse option { from: '${parseOptions.from}' }`);
}
if (!this._name && this._scriptPath) this.nameFromFilename(this._scriptPath);
this._name = this._name || 'program';
return userArgs;
}
parse(argv, parseOptions) {
this._prepareForParse();
const userArgs = this._prepareUserArgs(argv, parseOptions);
this._parseCommand([], userArgs);
return this;
}
async parseAsync(argv, parseOptions) {
this._prepareForParse();
const userArgs = this._prepareUserArgs(argv, parseOptions);
await this._parseCommand([], userArgs);
return this;
}
_prepareForParse() {
if (null === this._savedState) this.saveStateBeforeParse();
else this.restoreStateBeforeParse();
}
saveStateBeforeParse() {
this._savedState = {
_name: this._name,
_optionValues: {
...this._optionValues
},
_optionValueSources: {
...this._optionValueSources
}
};
}
restoreStateBeforeParse() {
if (this._storeOptionsAsProperties) throw new Error(`Can not call parse again when storeOptionsAsProperties is true.
- either make a new Command for each call to parse, or stop storing options as properties`);
this._name = this._savedState._name;
this._scriptPath = null;
this.rawArgs = [];
this._optionValues = {
...this._savedState._optionValues
};
this._optionValueSources = {
...this._savedState._optionValueSources
};
this.args = [];
this.processedArgs = [];
}
_checkForMissingExecutable(executableFile, executableDir, subcommandName) {
if (fs.existsSync(executableFile)) return;
const executableDirMessage = executableDir ? `searched for local subcommand relative to directory '${executableDir}'` : 'no directory for search for local subcommand, use .executableDir() to supply a custom directory';
const executableMissing = `'${executableFile}' does not exist
- if '${subcommandName}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
- if the default executable name is not suitable, use the executableFile option to supply a custom name or path
- ${executableDirMessage}`;
throw new Error(executableMissing);
}
_executeSubCommand(subcommand, args) {
args = args.slice();
let launchWithNode = false;
const sourceExt = [
'.js',
'.ts',
'.tsx',
'.mjs',
'.cjs'
];
function findFile(baseDir, baseName) {
const localBin = path.resolve(baseDir, baseName);
if (fs.existsSync(localBin)) return localBin;
if (sourceExt.includes(path.extname(baseName))) return;
const foundExt = sourceExt.find((ext)=>fs.existsSync(`${localBin}${ext}`));
if (foundExt) return `${localBin}${foundExt}`;
}
this._checkForMissingMandatoryOptions();
this._checkForConflictingOptions();
let executableFile = subcommand._executableFile || `${this._name}-${subcommand._name}`;
let executableDir = this._executableDir || '';
if (this._scriptPath) {
let resolvedScriptPath;
try {
resolvedScriptPath = fs.realpathSync(this._scriptPath);
} catch {
resolvedScriptPath = this._scriptPath;
}
executableDir = path.resolve(path.dirname(resolvedScriptPath), executableDir);
}
if (executableDir) {
let localFile = findFile(executableDir, executableFile);
if (!localFile && !subcommand._executableFile && this._scriptPath) {
const legacyName = path.basename(this._scriptPath, path.extname(this._scriptPath));
if (legacyName !== this._name) localFile = findFile(executableDir, `${legacyName}-${subcommand._name}`);
}
executableFile = localFile || executableFile;
}
launchWithNode = sourceExt.includes(path.extname(executableFile));
let proc;
if ('win32' !== process.platform) if (launchWithNode) {
args.unshift(executableFile);
args = incrementNodeInspectorPort(process.execArgv).concat(args);
proc = childProcess.spawn(process.argv[0], args, {
stdio: 'inherit'
});
} else proc = childProcess.spawn(executableFile, args, {
stdio: 'inherit'
});
else {
this._checkForMissingExecutable(executableFile, executableDir, subcommand._name);
args.unshift(executableFile);
args = incrementNodeInspectorPort(process.execArgv).concat(args);
proc = childProcess.spawn(process.execPath, args, {
stdio: 'inherit'
});
}
if (!proc.killed) {
const signals = [
'SIGUSR1',
'SIGUSR2',
'SIGTERM',
'SIGINT',
'SIGHUP'
];
signals.forEach((signal)=>{
process.on(signal, ()=>{
if (false === proc.killed && null === proc.exitCode) proc.kill(signal);
});
});
}
const exitCallback = this._exitCallback;
proc.on('close', (code)=>{
code = code ?? 1;
if (exitCallback) exitCallback(new CommanderError(code, 'commander.executeSubCommandAsync', '(close)'));
else process.exit(code);
});
proc.on('error', (err)=>{
if ('ENOENT' === err.code) this._checkForMissingExecutable(executableFile, executableDir, subcommand._name);
else if ('EACCES' === err.code) throw new Error(`'${executableFile}' not executable`);
if (exitCallback) {
const wrappedError = new CommanderError(1, 'commander.executeSubCommandAsync', '(error)');
wrappedError.nestedError = err;
exitCallback(wrappedError);
} else process.exit(1);
});
this.runningCommand = proc;
}
_dispatchSubcommand(commandName, operands, unknown) {
const subCommand = this._findCommand(commandName);
if (!subCommand) this.help({
error: true
});
subCommand._prepareForParse();
let promiseChain;
promiseChain = this._chainOrCallSubCommandHook(promiseChain, subCommand, 'preSubcommand');
promiseChain = this._chainOrCall(promiseChain, ()=>{
if (!subCommand._executableHandler) return subCommand._parseCommand(operands, unknown);
this._executeSubCommand(subCommand, operands.concat(unknown));
});
return promiseChain;
}
_dispatchHelpCommand(subcommandName) {
if (!subcommandName) this.help();
const subCommand = this._findCommand(subcommandName);
if (subCommand && !subCommand._executableHandler) subCommand.help();
return this._dispatchSubcommand(subcommandName, [], [
this._getHelpOption()?.long ?? this._getHelpOption()?.short ?? '--help'
]);
}
_checkNumberOfArguments() {
this.registeredArguments.forEach((arg, i)=>{
if (arg.required && null == this.args[i]) this.missingArgument(arg.name());
});
if (this.registeredArguments.length > 0 && this.registeredArguments[this.registeredArguments.length - 1].variadic) return;
if (this.args.length > this.registeredArguments.length) this._excessArguments(this.args);
}
_processArguments() {
const myParseArg = (argument, value, previous)=>{
let parsedValue = value;
if (null !== value && argument.parseArg) {
const invalidValueMessage = `error: command-argument value '${value}' is invalid for argument '${argument.name()}'.`;
parsedValue = this._callParseArg(argument, value, previous, invalidValueMessage);
}
return parsedValue;
};
this._checkNumberOfArguments();
const processedArgs = [];
this.registeredArguments.forEach((declaredArg, index)=>{
let value = declaredArg.defaultValue;
if (declaredArg.variadic) {
if (index < this.args.length) {
value = this.args.slice(index);
if (declaredArg.parseArg) value = value.reduce((processed, v)=>myParseArg(declaredArg, v, processed), declaredArg.defaultValue);
} else if (void 0 === value) value = [];
} else if (index < this.args.length) {
value = this.args[index];
if (declaredArg.parseArg) value = myParseArg(declaredArg, value, declaredArg.defaultValue);
}
processedArgs[index] = value;
});
this.processedArgs = processedArgs;
}
_chainOrCall(promise, fn) {
if (promise && promise.then && 'function' == typeof promise.then) return promise.then(()=>fn());
return fn();
}
_chainOrCallHooks(promise, event) {
let result = promise;
const hooks = [];
this._getCommandAndAncestors().reverse().filter((cmd)=>void 0 !== cmd._lifeCycleHooks[event]).forEach((hookedCommand)=>{
hookedCommand._lifeCycleHooks[event].forEach((callback)=>{
hooks.push({
hookedCommand,
callback
});
});
});
if ('postAction' === event) hooks.reverse();
hooks.forEach((hookDetail)=>{
result = this._chainOrCall(result, ()=>hookDetail.callback(hookDetail.hookedCommand, this));
});
return result;
}
_chainOrCallSubCommandHook(promise, subCommand, event) {
let result = promise;
if (void 0 !== this._lifeCycleHooks[event]) this._lifeCycleHooks[event].forEach((hook)=>{
result = this._chainOrCall(result, ()=>hook(this, subCommand));
});
return result;
}
_parseCommand(operands, unknown) {
const parsed = this.parseOptions(unknown);
this._parseOptionsEnv();
this._parseOptionsImplied();
operands = operands.concat(parsed.operands);
unknown = parsed.unknown;
this.args = operands.concat(unknown);
if (operands && this._findCommand(operands[0])) return this._dispatchSubcommand(operands[0], operands.slice(1), unknown);
if (this._getHelpCommand() && operands[0] === this._getHelpCommand().name()) return this._dispatchHelpCommand(operands[1]);
if (this._defaultCommandName) {
this._outputHelpIfRequested(unknown);
return this._dispatchSubcommand(this._defaultCommandName, operands, unknown);
}
if (this.commands.length && 0 === this.args.length && !this._actionHandler && !this._defaultCommandName) this.help({
error: true
});
this._outputHelpIfRequested(parsed.unknown);
this._checkForMissingMandatoryOptions();
this._checkForConflictingOptions();
const checkForUnknownOptions = ()=>{
if (parsed.unknown.length > 0) this.unknownOption(parsed.unknown[0]);
};
const commandEvent = `command:${this.name()}`;
if (this._actionHandler) {
checkForUnknownOptions();
this._processArguments();
let promiseChain;
promiseChain = this._chainOrCallHooks(promiseChain, 'preAction');
promiseChain = this._chainOrCall(promiseChain, ()=>this._actionHandler(this.processedArgs));
if (this.parent) promiseChain = this._chainOrCall(promiseChain, ()=>{
this.parent.emit(commandEvent, operands, unknown);
});
promiseChain = this._chainOrCallHooks(promiseChain, 'postAction');
return promiseChain;
}
if (this.parent && this.parent.listenerCount(commandEvent)) {
checkForUnknownOptions();
this._processArguments();
this.parent.emit(commandEvent, operands, unknown);
} else if (operands.length) {
if (this._findCommand('*')) return this._dispatchSubcommand('*', operands, unknown);
if (this.listenerCount('command:*')) this.emit('command:*', operands, unknown);
else if (this.commands.length) this.unknownCommand();
else {
checkForUnknownOptions();
this._processArguments();
}
} else if (this.commands.length) {
checkForUnknownOptions();
this.help({
error: true
});
} else {
checkForUnknownOptions();
this._processArguments();
}
}
_findCommand(name) {
if (!name) return;
return this.commands.find((cmd)=>cmd._name === name || cmd._aliases.includes(name));
}
_findOption(arg) {
return this.options.find((option)=>option.is(arg));
}
_checkForMissingMandatoryOptions() {
this._getCommandAndAncestors().forEach((cmd)=>{
cmd.options.forEach((anOption)=>{
if (anOption.mandatory && void 0 === cmd.getOptionValue(anOption.attributeName())) cmd.missingMandatoryOptionValue(anOption);
});
});
}
_checkForConflictingLocalOptions() {
const definedNonDefaultOptions = this.options.filter((option)=>{
const optionKey = option.attributeName();
if (void 0 === this.getOptionValue(optionKey)) return false;
return 'default' !== this.getOptionValueSource(optionKey);
});
const optionsWithConflicting = definedNonDefaultOptions.filter((option)=>option.conflictsWith.length > 0);
optionsWithConflicting.forEach((option)=>{
const conflictingAndDefined = definedNonDefaultOptions.find((defined)=>option.conflictsWith.includes(defined.attributeName()));
if (conflictingAndDefined) this._conflictingOption(option, conflictingAndDefined);
});
}
_checkForConflictingOptions() {
this._getCommandAndAncestors().forEach((cmd)=>{
cmd._checkForConflictingLocalOptions();
});
}
parseOptions(argv) {
const operands = [];
const unknown = [];
let dest = operands;
const args = argv.slice();
function maybeOption(arg) {
return arg.length > 1 && '-' === arg[0];
}
let activeVariadicOption = null;
while(args.length){
const arg = args.shift();
if ('--' === arg) {
if (dest === unknown) dest.push(arg);
dest.push(...args);
break;
}
if (activeVariadicOption && !maybeOption(arg)) {
this.emit(`option:${activeVariadicOption.name()}`, arg);
continue;
}
activeVariadicOption = null;
if (maybeOption(arg)) {
const option = this._findOption(arg);
if (option) {
if (option.required) {
const value = args.shift();
if (void 0 === value) this.optionMissingArgument(option);
this.emit(`option:${option.name()}`, value);
} else if (option.optional) {
let value = null;
if (args.length > 0 && !maybeOption(args[0])) value = args.shift();
this.emit(`option:${option.name()}`, value);
} else this.emit(`option:${option.name()}`);
activeVariadicOption = option.variadic ? option : null;
continue;
}
}
if (arg.length > 2 && '-' === arg[0] && '-' !== arg[1]) {
const option = this._findOption(`-${arg[1]}`);
if (option) {
if (option.required || option.optional && this._combineFlagAndOptionalValue) this.emit(`option:${option.name()}`, arg.slice(2));
else {
this.emit(`option:${option.name()}`);
args.unshift(`-${arg.slice(2)}`);
}
continue;
}
}
if (/^--[^=]+=/.test(arg)) {
const index = arg.indexOf('=');
const option = this._findOption(arg.slice(0, index));
if (option && (option.required || option.optional)) {
this.emit(`option:${option.name()}`, arg.slice(index + 1));
continue;
}
}
if (maybeOption(arg)) dest = unknown;
if ((this._enablePositionalOptions || this._passThroughOptions) && 0 === operands.length && 0 === unknown.length) {
if (this._findCommand(arg)) {
operands.push(arg);
if (args.length > 0) unknown.push(...args);
break;
} else if (this._getHelpCommand() && arg === this._getHelpCommand().name()) {
operands.push(arg);
if (args.length > 0) operands.push(...args);
break;
} else if (this._defaultCommandName) {
unknown.push(arg);
if (args.length > 0) unknown.push(...args);
break;
}
}
if (this._passThroughOptions) {
dest.push(arg);
if (args.length > 0) dest.push(...args);
break;
}
dest.push(arg);
}
return {
operands,
unknown
};
}
opts() {
if (this._storeOptionsAsProperties) {
const result = {};
const len = this.options.length;
for(let i = 0; i < len; i++){
const key = this.options[i].attributeName();
result[key] = key === this._versionOptionName ? this._version : this[key];
}
return result;
}
return this._optionValues;
}
optsWithGlobals() {
return this._getCommandAndAncestors().reduce((combinedOptions, cmd)=>Object.assign(combinedOptions, cmd.opts()), {});
}
error(message, errorOptions) {
this._outputConfiguration.outputError(`${message}\n`, this._outputConfiguration.writeErr);
if ('string' == typeof this._showHelpAfterError) this._outputConfiguration.writeErr(`${this._showHelpAfterError}\n`);
else if (this._showHelpAfterError) {
this._outputConfiguration.writeErr('\n');
this.outputHelp({
error: true
});
}
const config = errorOptions || {};
const exitCode = config.exitCode || 1;
const code = config.code || 'commander.error';
this._exit(exitCode, code, message);
}
_parseOptionsEnv() {
this.options.forEach((option)=>{
if (option.envVar && option.envVar in process.env) {
const optionKey = option.attributeName();
if (void 0 === this.getOptionValue(optionKey) || [
'default',
'config',
'env'
].includes(this.getOptionValueSource(optionKey))) if (option.required || option.optional) this.emit(`optionEnv:${option.name()}`, process.env[option.envVar]);
else this.emit(`optionEnv:${option.name()}`);
}
});
}
_parseOptionsImplied() {
const dualHelper = new DualOptions(this.options);
const hasCustomOptionValue = (optionKey)=>void 0 !== this.getOptionValue(optionKey) && ![
'default',
'implied'
].includes(this.getOptionValueSource(optionKey));
this.options.filter((option)=>void 0 !== option.implied && hasCustomOptionValue(option.attributeName()) && dualHelper.valueFromOption(this.getOptionValue(option.attributeName()), option)).forEach((option)=>{
Object.keys(option.implied).filter((impliedKey)=>!hasCustomOptionValue(impliedKey)).forEach((