lib/yargs-factory.ts
2437 LOC · 2437 covered · 0 uncovered · 555 ranges · 1119 concepts · 263 introducers · 788 tests
File neighbourhood
The centred file is linked to every concept that introduces one of its ranges, every test that runs code from the file, and the gray connector concepts standing between those tests and the file's own introducer concepts. Undirected links join concepts to every file where they introduce source and concepts to the tests they introduce; arrows show specialization between the displayed concepts and bridge only concepts omitted from this view. Concept colors match the source ranges below; connector concepts have no source color and are shown in gray.
Focused file, its introducer and connector concepts, their introduced files, and tests that run code from the file
In the embedded map, ordinary wheel input scrolls the page; use the visible controls to zoom and drag to pan. Open the full-screen map for canvas navigation: wheel pans, Ctrl/Command plus wheel zooms, and arrow keys pan when this region is focused. On touch screens, open the full-screen map to pan or pinch. If JavaScript or WebGL is unavailable, use the related-file, concept, and source links on this page.
Graph controls are ready.
Interactive rendering requires JavaScript and WebGL. Use the related-file, concept, and source links on this page while the interactive map is unavailable.
// Platform agnostic entrypoint for yargs, i.e., this factory is used to
// create an instance of yargs for CJS, ESM, Deno.
//
// Works by accepting a shim which shims methods that contain platform
// specific logic.
import {
command as Command,
CommandInstance,
CommandHandler,
CommandBuilderDefinition,
CommandBuilder,
CommandHandlerCallback,
CommandHandlerDefinition,
DefinitionOrCommandName,
} from './command.js';
import type {
Dictionary,
KeyOf,
DictionaryKeyof,
ValueOf,
RequireDirectoryOptions,
PlatformShim,
RequireType,
nil,
} from './typings/common-types.js';
import {
assertNotStrictEqual,
assertSingleKey,
objectKeys,
} from './typings/common-types.js';
import {
ArgsOutput,
DetailedArguments as ParserDetailedArguments,
Configuration as ParserConfiguration,
Options as ParserOptions,
ConfigCallback,
CoerceCallback,
} from './typings/yargs-parser-types.js';
import {YError} from './yerror.js';
import {UsageInstance, FailureFunction, usage as Usage} from './usage.js';
import {argsert} from './argsert.js';
import {
completion as Completion,
CompletionInstance,
CompletionFunction,
} from './completion.js';
import {
validation as Validation,
ValidationInstance,
KeyOrPos,
} from './validation.js';
import {objFilter} from './utils/obj-filter.js';
import {applyExtends} from './utils/apply-extends.js';
import {
applyMiddleware,
GlobalMiddleware,
MiddlewareCallback,
Middleware,
} from './middleware.js';
import {isPromise} from './utils/is-promise.js';
import {maybeAsyncResult} from './utils/maybe-async-result.js';
import setBlocking from './utils/set-blocking.js';
export function YargsFactory(_shim: PlatformShim) {
return (
cwd = _shim.process.cwd(),
parentRequire?: RequireType
): YargsInstance => {
const yargs = new YargsInstance(processArgs, cwd, parentRequire, _shim);
// Legacy yargs.argv interface, it's recommended that you use .parse().
Object.defineProperty(yargs, 'argv', {
get: () => {
enumerable: true,
});
// an app should almost always have --version and --help,
// if you *really* want to disable this use .help(false)/.version(false).
yargs.help();
yargs.version();
return yargs;
}
// Used to expose private methods to other module-level classes,
// such as the command parser and usage printer.
const kCopyDoubleDash = Symbol('copyDoubleDash');
const kCreateLogger = Symbol('copyDoubleDash');
const kDeleteFromParserHintObject = Symbol('deleteFromParserHintObject');
const kEmitWarning = Symbol('emitWarning');
const kFreeze = Symbol('freeze');
const kGetDollarZero = Symbol('getDollarZero');
const kGetParserConfiguration = Symbol('getParserConfiguration');
const kGetUsageConfiguration = Symbol('getUsageConfiguration');
const kGuessLocale = Symbol('guessLocale');
const kGuessVersion = Symbol('guessVersion');
const kParsePositionalNumbers = Symbol('parsePositionalNumbers');
const kPkgUp = Symbol('pkgUp');
const kPopulateParserHintArray = Symbol('populateParserHintArray');
const kPopulateParserHintSingleValueDictionary = Symbol(
'populateParserHintSingleValueDictionary'
);
const kPopulateParserHintArrayDictionary = Symbol(
'populateParserHintArrayDictionary'
);
const kPopulateParserHintDictionary = Symbol('populateParserHintDictionary');
const kSanitizeKey = Symbol('sanitizeKey');
const kSetKey = Symbol('setKey');
const kUnfreeze = Symbol('unfreeze');
const kValidateAsync = Symbol('validateAsync');
const kGetCommandInstance = Symbol('getCommandInstance');
const kGetContext = Symbol('getContext');
const kGetHasOutput = Symbol('getHasOutput');
const kGetLoggerInstance = Symbol('getLoggerInstance');
const kGetParseContext = Symbol('getParseContext');
const kGetUsageInstance = Symbol('getUsageInstance');
const kGetValidationInstance = Symbol('getValidationInstance');
const kHasParseCallback = Symbol('hasParseCallback');
const kIsGlobalContext = Symbol('isGlobalContext');
const kPostProcess = Symbol('postProcess');
const kRebase = Symbol('rebase');
const kReset = Symbol('reset');
const kRunYargsParserAndExecuteCommands = Symbol(
'runYargsParserAndExecuteCommands'
);
const kRunValidation = Symbol('runValidation');
const kSetHasOutput = Symbol('setHasOutput');
const kTrackManuallySetKeys = Symbol('kTrackManuallySetKeys');
const DEFAULT_LOCALE = 'en_US';
export interface YargsInternalMethods {
getCommandInstance(): CommandInstance;
getContext(): Context;
getHasOutput(): boolean;
getLoggerInstance(): LoggerInstance;
getParseContext(): object;
getParserConfiguration(): Configuration;
getUsageConfiguration(): UsageConfiguration;
getUsageInstance(): UsageInstance;
getValidationInstance(): ValidationInstance;
hasParseCallback(): boolean;
isGlobalContext(): boolean;
postProcess<T extends Arguments | Promise<Arguments>>(
argv: Arguments | Promise<Arguments>,
populateDoubleDash: boolean,
calledFromCommand: boolean,
runGlobalMiddleware: boolean
): any;
reset(aliases?: Aliases): YargsInstance;
runValidation(
aliases: Dictionary<string[]>,
positionalMap: Dictionary<string[]>,
parseErrors: Error | null,
isDefaultCommand?: boolean
): (argv: Arguments) => void;
runYargsParserAndExecuteCommands(
args: string | string[] | null,
shortCircuit?: boolean | null,
calledFromCommand?: boolean,
commandIndex?: number,
helpOnly?: boolean
): Arguments | Promise<Arguments>;
setHasOutput(): void;
}
export class YargsInstance {
$0: string;
argv?: Arguments;
customScriptName = false;
parsed: DetailedArguments | false = false;
#command: CommandInstance;
#cwd: string;
// use context object to keep track of resets, subcommand execution, etc.,
// submodules should modify and check the state of context as necessary:
#context: Context = {commands: [], fullCommands: []};
#completion: CompletionInstance | null = null;
#completionCommand: string | null = null;
#defaultShowHiddenOpt = 'show-hidden';
#exitError: YError | string | nil = null;
#detectLocale = true;
#emittedWarnings: Dictionary<boolean> = {};
#exitProcess = true;
#frozens: FrozenYargsInstance[] = [];
#globalMiddleware: GlobalMiddleware;
#groups: Dictionary<string[]> = {};
#hasOutput = false;
#helpOpt: string | null = null;
#isGlobalContext = true;
#logger: LoggerInstance;
#output = '';
#options: Options;
#parentRequire?: RequireType;
#parserConfig: Configuration = {};
#parseFn: ParseCallback | null = null;
#parseContext: object | null = null;
#pkgs: Dictionary<{[key: string]: string | {[key: string]: string}}> = {};
#preservedGroups: Dictionary<string[]> = {};
#processArgs: string | string[];
#recommendCommands = false;
#shim: PlatformShim;
#strict = false;
#strictCommands = false;
#strictOptions = false;
#usage: UsageInstance;
#usageConfig: UsageConfiguration = {};
#versionOpt: string | null = null;
#validation: ValidationInstance;
constructor(
cwd: string,
parentRequire: RequireType | undefined,
shim: PlatformShim
) {
this.#shim = shim;
this.#processArgs = processArgs;
this.#cwd = cwd;
this.#parentRequire = parentRequire;
this.#globalMiddleware = new GlobalMiddleware(this);
this.$0 = this[kGetDollarZero]();
// #command, #validation, and #usage are initialized on first reset:
this[kReset]();
this.#command = this!.#command;
this.#usage = this!.#usage;
this.#validation = this!.#validation;
this.#options = this!.#options;
this.#options.showHiddenOpt = this.#defaultShowHiddenOpt;
this.#logger = this[kCreateLogger]();
// y18n is a singleton intentionally, to prevent locales
// from being loaded multiple times off disk. We reset
// the language code whenever a new YargsInstance
// is created mainly for unit tests.
this.#shim.y18n.setLocale(DEFAULT_LOCALE);
}
argsert('[string|boolean] [string]', [opt, msg], arguments.length);
// nuke the key previously configured
// to return help.
if (this.#helpOpt) {
this.#helpOpt = null;
}
if (opt === false && msg === undefined) return this;
// use arguments, fallback to defaults for opt and msg
this.#helpOpt = typeof opt === 'string' ? opt : defaultHelpOpt;
this.boolean(this.#helpOpt);
this.describe(
this.#helpOpt,
msg || this.#usage.deferY18nLookup('Show help')
);
return this;
}
}
addShowHiddenOpt(opt?: string | false, msg?: string): YargsInstance {
if (opt === false && msg === undefined) return this;
const showHiddenOpt =
typeof opt === 'string' ? opt : this.#defaultShowHiddenOpt;
this.boolean(showHiddenOpt);
this.describe(
showHiddenOpt,
msg || this.#usage.deferY18nLookup('Show hidden options')
);
this.#options.showHiddenOpt = showHiddenOpt;
return this;
}
}
alias(
value?: string | string[]
): YargsInstance {
argsert(
'<object|string|array> [string|array]',
[key, value],
arguments.length
);
this[kPopulateParserHintArrayDictionary](
this.alias.bind(this),
'alias',
key,
value
);
return this;
}
this[kPopulateParserHintArray]('array', keys);
this[kTrackManuallySetKeys](keys);
return this;
}
this[kPopulateParserHintArray]('boolean', keys);
this[kTrackManuallySetKeys](keys);
return this;
}
global?: boolean
): YargsInstance {
argsert('<function> [boolean]', [f, global], arguments.length);
this.middleware(
(
_yargs: YargsInstance
): Partial<Arguments> | Promise<Partial<Arguments>> => {
return maybeAsyncResult<
Partial<Arguments> | Promise<Partial<Arguments>> | any
>(
() => {
return f(argv, _yargs.getOptions());
},
(result: any): Partial<Arguments> | Promise<Partial<Arguments>> => {
this.#shim.y18n.__('Argument check failed: %s', f.toString())
);
}
(err: Error): Partial<Arguments> | Promise<Partial<Arguments>> => {
return argv;
}
false,
global
);
return this;
}
value?: string | string[]
): YargsInstance {
argsert(
'<object|string|array> [string|array]',
[key, value],
arguments.length
);
this[kPopulateParserHintArrayDictionary](
this.choices.bind(this),
'choices',
key,
value
);
return this;
}
value?: CoerceCallback
): YargsInstance {
argsert(
'<object|string|array> [function]',
[keys, value],
arguments.length
);
if (Array.isArray(keys)) {
}
this.coerce(key, value);
}
return this;
this.coerce(key, keys[key]);
}
return this;
}
}
// Handled multiple above, down to one key.
const coerceKey = keys;
// This noop tells yargs-parser about the existence of the option
// represented by "coerceKey", so that it can apply camel case expansion
// if needed:
this.#options.key[coerceKey] = true;
this.#globalMiddleware.addCoerceMiddleware(
(
yargs: YargsInstance
): Partial<Arguments> | Promise<Partial<Arguments>> => {
// Narrow down the possible keys to the ones present in argv.
const coerceKeyAliases = yargs.getAliases()[coerceKey] ?? [];
const argvKeys = [coerceKey, ...coerceKeyAliases].filter(key =>
Object.prototype.hasOwnProperty.call(argv, key)
);
// Skip coerce if nothing to coerce.
if (argvKeys.length === 0) {
}
return maybeAsyncResult<
Partial<Arguments> | Promise<Partial<Arguments>> | any
>(
() => {
return value(argv[argvKeys[0]]);
},
(result: any): Partial<Arguments> => {
argv[key] = result;
});
return argv;
(err: Error): Partial<Arguments> | Promise<Partial<Arguments>> => {
}
coerceKey
);
return this;
}
key2?: string | string[]
): YargsInstance {
argsert('<string|object> [string|array]', [key1, key2], arguments.length);
this.#validation.conflicts(key1, key2);
return this;
}
msg?: string | ConfigCallback,
parseFn?: ConfigCallback
): YargsInstance {
argsert(
'[object|string] [string|function] [function]',
[key, msg, parseFn],
arguments.length
);
// allow a config object to be provided directly.
if (typeof key === 'object' && !Array.isArray(key)) {
key,
this.#cwd,
this[kGetParserConfiguration]()['deep-merge-config'] || false,
this.#shim
);
this.#options.configObjects = (this.#options.configObjects || []).concat(
key
);
return this;
}
// allow for a custom parsing function.
if (typeof msg === 'function') {
msg = undefined;
}
this.describe(
key,
msg || this.#usage.deferY18nLookup('Path to JSON config file')
(Array.isArray(key) ? key : [key]).forEach(k => {
return this;
}
desc?: string | false | CompletionFunction,
fn?: CompletionFunction
): YargsInstance {
argsert(
'[string] [string|boolean|function] [function]',
[cmd, desc, fn],
arguments.length
);
// a function to execute when generating
// completions can be provided as the second
// or third argument to completion.
if (typeof desc === 'function') {
desc = undefined;
}
// register the completion command.
this.#completionCommand = cmd || this.#completionCommand || 'completion';
if (!desc && desc !== false) {
}
// a function can be provided
if (fn) this.#completion!.registerFunction(fn);
return this;
}
description?: CommandHandler['description'],
builder?: CommandBuilderDefinition | CommandBuilder,
handler?: CommandHandlerCallback,
middlewares?: Middleware[],
deprecated?: boolean
): YargsInstance {
argsert(
'<string|array|object> [string|boolean] [function|object] [function] [array] [boolean|string]',
[cmd, description, builder, handler, middlewares, deprecated],
arguments.length
);
this.#command.addHandler(
cmd,
description,
builder,
handler,
middlewares,
deprecated
);
return this;
}
description?: CommandHandler['description'],
builder?: CommandBuilderDefinition | CommandBuilder,
handler?: CommandHandlerCallback,
middlewares?: Middleware[],
deprecated?: boolean
): YargsInstance {
return this.command(
cmd,
description,
builder,
handler,
middlewares,
deprecated
);
}
commandDir(dir: string, opts?: RequireDirectoryOptions): YargsInstance {
yargs-factory.ts ×124
const req = this.#parentRequire || this.#shim.require;
this.#command.addDirectory(dir, req, this.#shim.getCallerFile(), opts);
return this;
}
this[kPopulateParserHintArray]('count', keys);
this[kTrackManuallySetKeys](keys);
return this;
}
value?: any,
defaultDescription?: string
): YargsInstance {
argsert(
'<object|string|array> [*] [string]',
[key, value, defaultDescription],
arguments.length
);
if (defaultDescription) {
this.#options.defaultDescription[key] = defaultDescription;
}
if (!this.#options.defaultDescription[key])
this.#options.defaultDescription[key] =
}
this.default.bind(this),
'default',
key,
value
);
return this;
}
value?: any,
defaultDescription?: string
): YargsInstance {
return this.default(key, value, defaultDescription);
}
max?: number | string,
minMsg?: string | null,
maxMsg?: string | null
): YargsInstance {
argsert(
'[number] [number|string] [string|null|undefined] [string|null|undefined]',
[min, max, minMsg, maxMsg],
arguments.length
);
if (typeof max !== 'number') {
max = Infinity;
}
this.global('_', false);
this.#options.demandedCommands._ = {
min,
max,
minMsg,
maxMsg,
};
return this;
}
max?: number | string[] | string | true,
msg?: string | true
): YargsInstance {
// you can optionally provide a 'max' key,
// which will raise an exception if too many '_'
// options are provided.
if (Array.isArray(max)) {
assertNotStrictEqual(msg, true as const, this.#shim);
this.demandOption(key, msg);
});
max = Infinity;
max = Infinity;
}
if (typeof keys === 'number') {
this.demandCommand(keys, max, msg, msg);
assertNotStrictEqual(msg, true as const, this.#shim);
this.demandOption(key, msg);
});
}
return this;
}
msg?: string
): YargsInstance {
argsert('<object|string|array> [string]', [keys, msg], arguments.length);
this[kPopulateParserHintSingleValueDictionary](
this.demandOption.bind(this),
'demandedOptions',
keys,
msg
);
return this;
}
deprecateOption(option: string, message: string | boolean): YargsInstance {
yargs-factory.ts ×124
this.#options.deprecatedOptions[option] = message;
return this;
}
description?: string
): YargsInstance {
argsert(
'<object|string|array> [string]',
[keys, description],
arguments.length
);
this[kSetKey](keys, true);
this.#usage.describe(keys, description);
return this;
}
this.#detectLocale = detect;
return this;
}
// parser will apply env vars matching prefix to argv
env(prefix?: string | false): YargsInstance {
if (prefix === false) delete this.#options.envPrefix;
}
this.#usage.epilog(msg);
return this;
}
}
description?: string
): YargsInstance {
argsert('<string|array> [string]', [cmd, description], arguments.length);
if (Array.isArray(cmd)) {
this.#usage.example(cmd, description);
}
return this;
}
exit(code: number, err?: YError | string): void {
this.#exitError = err;
if (this.#exitProcess) this.#shim.process.exit(code);
}
this.#exitProcess = enabled;
return this;
}
if (typeof f === 'boolean' && f !== false) {
"Invalid first argument. Expected function or boolean 'false'"
);
}
return this;
}
}
done?: (err: Error | null, completions: string[] | undefined) => void
): Promise<string[] | void> {
argsert('<array> [function]', [args, done], arguments.length);
if (!done) {
this.#completion!.getCompletion(args, (err, completions) => {
if (err) reject(err);
else resolve(completions);
});
});
}
return this.#options.demandedOptions;
}
return this.#options.demandedCommands;
}
return this.#options.deprecatedOptions;
}
}
}
// combine explicit and preserved groups. explicit groups should be first
yargs-factory.ts ×124
getGroups(): Dictionary<string[]> {
}
if (!this.#usage.hasCachedHelpMessage()) {
// the last parameter `true` indicates).
const parse = this[kRunYargsParserAndExecuteCommands](
this.#processArgs,
undefined,
undefined,
0,
true
);
if (isPromise(parse)) {
return this.#usage.help();
});
}
const builderResponse = this.#command.runDefaultBuilderOn(this);
if (isPromise(builderResponse)) {
return this.#usage.help();
});
}
}
}
}
}
}
globals = ([] as string[]).concat(globals);
if (global !== false) {
l => globals.indexOf(l) === -1
);
if (!this.#options.local.includes(g)) this.#options.local.push(g);
});
}
}
const existing =
this.#preservedGroups[groupName] || this.#groups[groupName];
if (this.#preservedGroups[groupName]) {
delete this.#preservedGroups[groupName];
}
this.#groups[groupName] = (existing || []).concat(opts).filter(key => {
if (seen[key]) return false;
return (seen[key] = true);
});
return this;
}
this.#options.hiddenOptions.push(key);
return this;
}
value?: KeyOrPos | KeyOrPos[]
): YargsInstance {
argsert(
'<string|object> [number|string|array]',
[key, value],
arguments.length
);
this.#validation.implies(key, value);
return this;
}
if (locale === undefined) {
return this.#shim.y18n.getLocale();
}
this.#shim.y18n.setLocale(locale);
return this;
}
applyBeforeValidation?: boolean,
global?: boolean
): YargsInstance {
return this.#globalMiddleware.addMiddleware(
callback,
!!applyBeforeValidation,
global
);
}
value?: number
): YargsInstance {
argsert('<string|object|array> [number]', [key, value], arguments.length);
this[kPopulateParserHintSingleValueDictionary](
this.nargs.bind(this),
'narg',
key,
value
);
return this;
}
this[kPopulateParserHintArray]('normalize', keys);
return this;
}
this[kPopulateParserHintArray]('number', keys);
this[kTrackManuallySetKeys](keys);
return this;
}
opt?: OptionDefinition
): YargsInstance {
argsert('<string|object> [object]', [key, opt], arguments.length);
if (typeof key === 'object') {
this.options(k, key[k]);
});
if (typeof opt !== 'object') {
}
this[kTrackManuallySetKeys](key);
// Warn about version name collision
// Addresses: https://github.com/yargs/yargs/issues/1979
if (this.#versionOpt && (key === 'version' || opt?.alias === 'version')) {
[
'"version" is a reserved word.',
'Please do one of the following:',
'- Disable version with `yargs.version(false)` if using "version" as an option',
'- Use the built-in `yargs.version` method instead (if applicable)',
'- Use a different option key',
'https://yargs.js.org/docs/#api-reference-version',
].join('\n'),
undefined,
'versionWarning' // TODO: better dedupeId
);
}
this.#options.key[key] = true; // track manually set keys.
if (opt.alias) this.alias(key, opt.alias);
const deprecate = opt.deprecate || opt.deprecated;
if (deprecate) {
}
const demand = opt.demand || opt.required || opt.require;
// A required option can be specified via "demand: true".
if (demand) {
}
if (opt.demandOption) {
key,
typeof opt.demandOption === 'string' ? opt.demandOption : undefined
);
}
if (opt.conflicts) {
}
if ('default' in opt) {
}
if (opt.implies !== undefined) {
}
if (opt.nargs !== undefined) {
}
if (opt.config) {
}
if (opt.normalize) {
}
if (opt.choices) {
}
if (opt.coerce) {
}
if (opt.group) {
}
if (opt.boolean || opt.type === 'boolean') {
if (opt.alias) this.boolean(opt.alias);
}
if (opt.array || opt.type === 'array') {
if (opt.alias) this.array(opt.alias);
}
if (opt.number || opt.type === 'number') {
if (opt.alias) this.number(opt.alias);
}
if (opt.string || opt.type === 'string') {
if (opt.alias) this.string(opt.alias);
}
if (opt.count || opt.type === 'count') {
}
if (typeof opt.global === 'boolean') {
}
if (opt.defaultDescription) {
}
if (opt.skipValidation) {
}
const desc = opt.describe || opt.description || opt.desc;
const descriptions = this.#usage.getDescriptions();
if (
!Object.prototype.hasOwnProperty.call(descriptions, key) ||
}
if (opt.hidden) {
}
if (opt.requiresArg) {
}
return this;
}
opt?: OptionDefinition
): YargsInstance {
return this.option(key, opt);
}
shortCircuit?: object | ParseCallback | boolean,
_parseFn?: ParseCallback
): Arguments | Promise<Arguments> {
argsert(
'[string|array] [function|boolean|object] [function]',
[args, shortCircuit, _parseFn],
arguments.length
);
this[kFreeze](); // Push current state of parser onto stack.
if (typeof args === 'undefined') {
}
// a context object can optionally be provided, this allows
// additional information to be passed to a command handler.
if (typeof shortCircuit === 'object') {
shortCircuit = _parseFn;
}
// by providing a function as a second argument to
// parse you can capture output that would otherwise
// default to printing to stdout/stderr.
if (typeof shortCircuit === 'function') {
shortCircuit = false;
}
// skipping validation, etc.
if (!shortCircuit) this.#processArgs = args;
if (this.#parseFn) this.#exitProcess = false;
const parsed = this[kRunYargsParserAndExecuteCommands](
args,
!!shortCircuit
);
const tmpParsed = this.parsed;
this.#completion!.setParsed(this.parsed as DetailedArguments);
if (isPromise(parsed)) {
.then(argv => {
return argv;
.catch(err => {
err,
(this.parsed as DetailedArguments).argv,
this.#output
);
}
.finally(() => {
this[kUnfreeze](); // Pop the stack.
this.parsed = tmpParsed;
});
this[kUnfreeze](); // Pop the stack.
this.parsed = tmpParsed;
}
return parsed;
}
shortCircuit?: object | ParseCallback | boolean,
_parseFn?: ParseCallback
): Promise<Arguments> {
const maybePromise = this.parse(args, shortCircuit, _parseFn);
return !isPromise(maybePromise)
? Promise.resolve(maybePromise)
: maybePromise;
}
shortCircuit?: object | ParseCallback | boolean,
_parseFn?: ParseCallback
): Arguments {
const maybePromise = this.parse(args, shortCircuit, _parseFn);
if (isPromise(maybePromise)) {
'.parseSync() must not be used with asynchronous builders, handlers, or middleware'
);
}
}
this.#parserConfig = config;
return this;
}
let conf = null;
// prefer cwd to require-main-filename in this method
// since we're looking for e.g. "nyc" config in nyc consumer
// rather than "yargs" config in nyc (where nyc is the main filename)
const obj = this[kPkgUp](rootPath || this.#cwd);
// If an object exists in the key, add it to options.configObjects
if (obj[key] && typeof obj[key] === 'object') {
obj[key] as {[key: string]: string},
rootPath || this.#cwd,
this[kGetParserConfiguration]()['deep-merge-config'] || false,
this.#shim
);
this.#options.configObjects = (this.#options.configObjects || []).concat(
conf
);
}
}
// .positional() only supports a subset of the configuration
// options available to .option():
const supportedOpts: (keyof PositionalDefinition)[] = [
'default',
'defaultDescription',
'implies',
'normalize',
'choices',
'conflicts',
'coerce',
'type',
'describe',
'desc',
'description',
'alias',
];
opts = objFilter(opts, (k, v) => {
if (k === 'type' && !['string', 'number', 'boolean'].includes(v))
return false;
return supportedOpts.includes(k);
// copy over any settings that can be inferred from the command string.
const fullCommand =
this.#context.fullCommands[this.#context.fullCommands.length - 1];
const parseOptions = fullCommand
? this.#command.cmdToParseOptions(fullCommand)
: {
alias: {},
default: {},
demand: {},
};
const parseOption = parseOptions[pk];
if (Array.isArray(parseOption)) {
if (parseOption.indexOf(key) !== -1) opts[pk] = true;
} else {
if (parseOption[key] && !(pk in opts)) opts[pk] = parseOption[key];
}
});
this.group(key, this.#usage.getPositionalGroupName());
return this.option(key, opts);
}
this.#recommendCommands = recommend;
return this;
}
max?: number | string[] | string | true,
msg?: string | true
): YargsInstance {
return this.demand(keys, max, msg);
}
max?: number | string[] | string | true,
msg?: string | true
): YargsInstance {
return this.demand(keys, max, msg);
}
// as populateParserHintSingleValueDictionary recursively calls requiresArg
// with Nan as a 2nd parameter, although we ignore it
argsert('<array|string|object> [number]', [keys], arguments.length);
// If someone configures nargs at the same time as requiresArg,
// nargs should take precedence,
// see: https://github.com/yargs/yargs/pull/1572
// TODO: make this work with aliases, using a check similar to
// checkAllAliases() in yargs-parser.
if (typeof keys === 'string' && this.#options.narg[keys]) {
this.requiresArg.bind(this),
'narg',
keys,
NaN
);
}
return this;
}
$0 = $0 || this.$0;
this.#logger.log(
this.#completion!.generateCompletionScript(
$0,
cmd || this.#completionCommand || 'completion'
)
);
return this;
}
): YargsInstance {
argsert('[string|function]', [level], arguments.length);
this.#hasOutput = true;
if (!this.#usage.hasCachedHelpMessage()) {
// the last parameter `true` indicates).
const parse = this[kRunYargsParserAndExecuteCommands](
this.#processArgs,
undefined,
undefined,
0,
true
);
if (isPromise(parse)) {
this.#usage.showHelp(level);
});
return this;
}
const builderResponse = this.#command.runDefaultBuilderOn(this);
if (isPromise(builderResponse)) {
this.#usage.showHelp(level);
});
return this;
}
return this;
}
this.$0 = scriptName;
return this;
}
showHelpOnFail(enabled?: string | boolean, message?: string): YargsInstance {
yargs-factory.ts ×124
this.#usage.showHelpOnFail(enabled, message);
return this;
}
): YargsInstance {
argsert('[string|function]', [level], arguments.length);
this.#usage.showVersion(level);
return this;
}
this[kPopulateParserHintArray]('skipValidation', keys);
return this;
}
this.#strict = enabled !== false;
return this;
}
this.#strictCommands = enabled !== false;
return this;
}
this.#strictOptions = enabled !== false;
return this;
}
this[kPopulateParserHintArray]('string', keys);
this[kTrackManuallySetKeys](keys);
return this;
}
return this.#shim.process.stdColumns;
}
}
this.#detectLocale = false;
this.#shim.y18n.updateLocale(obj);
return this;
}
description?: CommandHandler['description'],
builder?: CommandBuilderDefinition | CommandBuilder,
handler?: CommandHandlerCallback
): YargsInstance {
argsert(
'<string|null|undefined> [string|boolean] [function|object] [function]',
[msg, description, builder, handler],
arguments.length
);
if (description !== undefined) {
// .usage() can be used as an alias for defining
// a default command.
if ((msg || '').match(/^\$0( |$)/)) {
'.usage() description must start with $0 if being used as alias for .command()'
);
}
return this;
}
this.#usageConfig = config;
return this;
}
version(opt?: string | false, msg?: string, ver?: string): YargsInstance {
yargs-factory.ts ×124
argsert(
'[boolean|string] [string] [string]',
[opt, msg, ver],
arguments.length
);
// nuke the key previously configured
// to return version #.
if (this.#versionOpt) {
this.#usage.version(undefined);
this.#versionOpt = null;
}
if (arguments.length === 0) {
ver = this[kGuessVersion]();
opt = defaultVersionOpt;
} else if (arguments.length === 1) {
return this;
}
opt = defaultVersionOpt;
msg = undefined;
}
this.#versionOpt = typeof opt === 'string' ? opt : defaultVersionOpt;
msg = msg || this.#usage.deferY18nLookup('Show version number');
this.#usage.version(ver || undefined);
this.boolean(this.#versionOpt);
this.describe(this.#versionOpt, msg);
return this;
}
this.#usage.wrap(cols);
return this;
}
// to simplify the parsing of positionals in commands,
// we temporarily populate '--' rather than _, with arguments
// after the '--' directive. After the parse, we copy these back.
[kCopyDoubleDash](argv: Arguments): any {
argv._.push.apply(argv._, argv['--']);
// We catch an error here, in case someone has called Object.seal()
// on the parsed object, see: https://github.com/babel/babel/pull/10733
try {
delete argv['--'];
// eslint-disable-next-line no-empty
} catch (_err) {}
return argv;
}
log: (...args: any[]) => {
this.#hasOutput = true;
if (this.#output.length) this.#output += '\n';
this.#output += args.join(' ');
error: (...args: any[]) => {
this.#hasOutput = true;
if (this.#output.length) this.#output += '\n';
this.#output += args.join(' ');
};
}
// boolean, array, key, alias, etc.
objectKeys(this.#options).forEach((hintKey: keyof Options) => {
// configObjects is not a parsing hint array
if (((key): key is 'configObjects' => key === 'configObjects')(hintKey))
return;
const hint = this.#options[hintKey];
if (Array.isArray(hint)) {
if (hint.includes(optionKey)) hint.splice(hint.indexOf(optionKey), 1);
} else if (typeof hint === 'object') {
delete (hint as Dictionary)[optionKey];
}
});
// now delete the description from usage.js.
delete this.#usage.getDescriptions()[optionKey];
}
type: string | undefined,
deduplicationId: string
) {
// prevent duplicate warning emissions
if (!this.#emittedWarnings[deduplicationId]) {
this.#shim.process.emitWarning(warning, type);
this.#emittedWarnings[deduplicationId] = true;
}
}
options: this.#options,
configObjects: this.#options.configObjects.slice(0),
exitProcess: this.#exitProcess,
groups: this.#groups,
strict: this.#strict,
strictCommands: this.#strictCommands,
strictOptions: this.#strictOptions,
completionCommand: this.#completionCommand,
output: this.#output,
exitError: this.#exitError!,
hasOutput: this.#hasOutput,
parsed: this.parsed,
parseFn: this.#parseFn!,
parseContext: this.#parseContext,
});
this.#usage.freeze();
this.#validation.freeze();
this.#command.freeze();
this.#globalMiddleware.freeze();
}
// ignore the node bin, specify this in your
// bin file with #!/usr/bin/env node
let default$0: string[];
if (
/\b(node|iojs|electron|bun)(\.exe)?$/.test(this.#shim.process.argv()[0])
) {
}
$0 = default$0
.map(x => {
const b = this[kRebase](this.#cwd, x);
return x.match(/^(\/|([a-zA-Z]:)?\\)/) && b.length < x.length ? b : x;
})
.join(' ')
.trim();
if (
this.#shim.getEnv('_') &&
this.#shim.getProcessArgvBin() === this.#shim.getEnv('_')
) {
.getEnv('_')!
.replace(
`${this.#shim.path.dirname(this.#shim.process.execPath())}/`,
''
);
}
}
}
}
this.#shim.getEnv('LC_ALL') ||
this.#shim.getEnv('LANG') ||
this.#shim.getEnv('LANGUAGE') ||
'en_US';
this.locale(locale.replace(/[.:].*/, ''));
}
return (obj.version as string) || 'unknown';
}
// We wait to coerce numbers for positionals until after the initial parse.
yargs-factory.ts ×124
// This allows commands to configure number parsing on a positional by
// positional basis:
[kParsePositionalNumbers](argv: Arguments): any {
for (let i = 0, arg; (arg = args[i]) !== undefined; i++) {
this.#shim.Parser.looksLikeNumber(arg) &&
}
}
if (this.#pkgs[npath]) return this.#pkgs[npath];
let obj = {};
try {
let startDir = rootPath || this.#shim.mainFilename;
// If a file path is provided for root, remove the file and keep path.
if (this.#shim.path.extname(startDir)) {
}
const pkgJsonPath = this.#shim.findUp(
startDir,
(dir: string[], names: string[]) => {
if (names.includes('package.json')) {
return 'package.json';
} else {
}
);
assertNotStrictEqual(pkgJsonPath, undefined, this.#shim);
obj = JSON.parse(this.#shim.readFileSync(pkgJsonPath, 'utf8'));
// eslint-disable-next-line no-empty
} catch (_noop) {}
this.#pkgs[npath] = obj || {};
return this.#pkgs[npath];
}
keys: string | string[]
) {
keys = ([] as string[]).concat(keys);
keys.forEach(key => {
key = this[kSanitizeKey](key);
this.#options[type].push(key);
});
}
| Exclude<DictionaryKeyof<Options>, DictionaryKeyof<Options, any[]>>
| 'default',
K extends keyof Options[T] & string = keyof Options[T] & string,
V extends ValueOf<Options[T]> = ValueOf<Options[T]>,
>(
builder: (key: K, value: V, ...otherArgs: any[]) => YargsInstance,
type: T,
key: K | K[] | {[key in K]: V | undefined},
value?: V
) {
this[kPopulateParserHintDictionary]<T, K, V>(
builder,
type,
key,
value,
(type, key, value) => {
this.#options[type][key] = value as ValueOf<Options[T]>;
}
);
}
K extends keyof Options[T] & string = keyof Options[T] & string,
V extends ValueOf<ValueOf<Options[T]>> | ValueOf<ValueOf<Options[T]>>[] =
ValueOf<ValueOf<Options[T]>> | ValueOf<ValueOf<Options[T]>>[],
>(
builder: (key: K, value: V, ...otherArgs: any[]) => YargsInstance,
type: T,
key: K | K[] | {[key in K]: V},
value?: V
) {
this[kPopulateParserHintDictionary]<T, K, V>(
builder,
type,
key,
value,
(type, key, value) => {
this.#options[type][key] = (
this.#options[type][key] || ([] as Options[T][keyof Options[T]])
).concat(value);
}
);
}
K extends keyof Options[T],
V,
>(
builder: (key: K, value: V, ...otherArgs: any[]) => YargsInstance,
type: T,
key: K | K[] | {[key in K]: V | undefined},
value: V | undefined,
singleKeyHandler: (type: T, key: K, value?: V) => void
) {
if (Array.isArray(key)) {
key.forEach(k => {
builder(k, value!);
});
((key): key is {[key in K]: V} => typeof key === 'object')(key)
) {
for (const k of objectKeys(key)) {
builder(k, key[k]);
}
singleKeyHandler(type, this[kSanitizeKey](key), value);
}
}
return key;
}
set?: boolean | string
) {
this[kPopulateParserHintSingleValueDictionary](
this[kSetKey].bind(this),
'key',
key,
set
);
return this;
}
assertNotStrictEqual(frozen, undefined, this.#shim);
let configObjects: Dictionary[];
({
options: this.#options,
configObjects,
exitProcess: this.#exitProcess,
groups: this.#groups,
output: this.#output,
exitError: this.#exitError,
hasOutput: this.#hasOutput,
parsed: this.parsed,
strict: this.#strict,
strictCommands: this.#strictCommands,
strictOptions: this.#strictOptions,
completionCommand: this.#completionCommand,
parseFn: this.#parseFn,
parseContext: this.#parseContext,
} = frozen);
this.#options.configObjects = configObjects;
this.#usage.unfreeze();
this.#validation.unfreeze();
this.#command.unfreeze();
this.#globalMiddleware.unfreeze();
}
// If argv is a promise (which is possible if async middleware is used)
yargs-factory.ts ×124
// delay applying validation until the promise has resolved:
[kValidateAsync](
argv: Arguments | Promise<Arguments>
): Arguments | Promise<Arguments> {
return maybeAsyncResult<Arguments>(argv, result => {
validation(result);
return result;
});
}
// Note: these method names could change at any time, and should not be
// depended upon externally:
getInternalMethods(): YargsInternalMethods {
getCommandInstance: this[kGetCommandInstance].bind(this),
getContext: this[kGetContext].bind(this),
getHasOutput: this[kGetHasOutput].bind(this),
getLoggerInstance: this[kGetLoggerInstance].bind(this),
getParseContext: this[kGetParseContext].bind(this),
getParserConfiguration: this[kGetParserConfiguration].bind(this),
getUsageConfiguration: this[kGetUsageConfiguration].bind(this),
getUsageInstance: this[kGetUsageInstance].bind(this),
getValidationInstance: this[kGetValidationInstance].bind(this),
hasParseCallback: this[kHasParseCallback].bind(this),
isGlobalContext: this[kIsGlobalContext].bind(this),
postProcess: this[kPostProcess].bind(this),
reset: this[kReset].bind(this),
runValidation: this[kRunValidation].bind(this),
runYargsParserAndExecuteCommands:
this[kRunYargsParserAndExecuteCommands].bind(this),
setHasOutput: this[kSetHasOutput].bind(this),
};
}
}
}
}
}
}
}
}
}
}
populateDoubleDash: boolean,
calledFromCommand: boolean,
runGlobalMiddleware: boolean
): any {
if (calledFromCommand) return argv;
}
this[kGetParserConfiguration]()['parse-positional-numbers'] ||
this[kGetParserConfiguration]()['parse-positional-numbers'] === undefined;
yargs-factory.ts ×2
if (parsePositionalNumbers) {
}
if (runGlobalMiddleware) {
argv,
this,
this.#globalMiddleware.getMiddleware(),
false
);
}
}
// put yargs back into an initial state; this is used mainly for running
yargs-factory.ts ×124
// commands in a breadth first manner:
[kReset](aliases: Aliases = {}): YargsInstance {
const tmpOptions = {} as Options;
tmpOptions.local = this.#options.local || [];
tmpOptions.configObjects = this.#options.configObjects || [];
// if a key has been explicitly set as local,
// we should reset it before passing options to command.
const localLookup: Dictionary<boolean> = {};
tmpOptions.local.forEach(l => {
(aliases[l] || []).forEach(a => {
// add all groups not set to local to preserved groups
Object.assign(
this.#preservedGroups,
Object.keys(this.#groups).reduce(
(acc, groupName) => {
key => !(key in localLookup)
);
if (keys.length > 0) {
}
{} as Dictionary<string[]>
)
);
// groups can now be reset
this.#groups = {};
const arrayOptions: KeyOf<Options, string[]>[] = [
'array',
'boolean',
'string',
'skipValidation',
'count',
'normalize',
'number',
'hiddenOptions',
];
const objectOptions: DictionaryKeyof<Options>[] = [
'narg',
'key',
'alias',
'default',
'defaultDescription',
'config',
'choices',
'demandedOptions',
'demandedCommands',
'deprecatedOptions',
];
arrayOptions.forEach(k => {
tmpOptions[k] = (this.#options[k] || []).filter(
(k: string) => !localLookup[k]
);
});
objectOptions.forEach(<K extends DictionaryKeyof<Options>>(k: K) => {
tmpOptions[k] = objFilter(
this.#options[k],
k => !localLookup[k as string]
);
});
tmpOptions.envPrefix = this.#options.envPrefix;
this.#options = tmpOptions;
// if this is the first time being executed, create
// instances of all our helpers -- otherwise just reset.
this.#usage = this.#usage
? this.#usage.reset(localLookup)
: Usage(this, this.#shim);
this.#validation = this.#validation
? this.#validation.reset(localLookup)
: Validation(this, this.#usage, this.#shim);
this.#command = this.#command
? this.#command.reset()
: Command(
this.#usage,
this.#validation,
this.#globalMiddleware,
this.#shim
);
if (!this.#completion)
this.#completion = Completion(
this,
this.#usage,
this.#command,
this.#shim
);
this.#globalMiddleware.reset();
this.#completionCommand = null;
this.#output = '';
this.#exitError = null;
this.#hasOutput = false;
this.parsed = false;
return this;
}
}
shortCircuit?: boolean | null,
calledFromCommand?: boolean,
commandIndex = 0,
helpOnly = false
): Arguments | Promise<Arguments> {
let skipValidation = !!calledFromCommand || helpOnly;
args = args || this.#processArgs;
this.#options.__ = this.#shim.y18n.__;
this.#options.configuration = this[kGetParserConfiguration]();
const populateDoubleDash = !!this.#options.configuration['populate--'];
const config = Object.assign({}, this.#options.configuration, {
'populate--': true,
});
const parsed = this.#shim.Parser.detailed(
args,
Object.assign({}, this.#options, {
configuration: {'parse-positional-numbers': false, ...config},
})
) as DetailedArguments;
const argv: Arguments = Object.assign(
parsed.argv,
this.#parseContext
) as Arguments;
let argvPromise: Arguments | Promise<Arguments> | undefined = undefined;
const aliases = parsed.aliases;
let helpOptSet = false;
let versionOptSet = false;
Object.keys(argv).forEach(key => {
if (key === this.#helpOpt && argv[key]) {
}
argv.$0 = this.$0;
this.parsed = parsed;
// A single yargs instance may be used multiple times, e.g.
// const y = yargs(); y.parse('foo --bar'); yargs.parse('bar --foo').
// When a prior parse has completed and a new parse is beginning, we
// need to clear the cached help message from the previous parse:
if (commandIndex === 0) {
this.#usage.clearCachedHelpMessage();
}
try {
this[kGuessLocale](); // guess locale lazily, so that it can be turned off in chain.
// while building up the argv object, there
// are two passes through the parser. If completion
// is being performed short-circuit on the first pass.
if (shortCircuit) {
argv,
populateDoubleDash,
!!calledFromCommand,
false // Don't run middleware when figuring out completion.
);
}
// if there's a handler associated with a
// command defer processing to it.
if (this.#helpOpt) {
// unless all helpOpt aliases are single-char
// note that parsed.aliases is a normalized bidirectional map :)
const helpCmds = [this.#helpOpt]
.concat(aliases[this.#helpOpt] || [])
.filter(k => k.length > 1);
// check if help should trigger and strip it from _.
if (helpCmds.includes('' + argv._[argv._.length - 1])) {
helpOptSet = true;
}
this.#isGlobalContext = false;
const handlerKeys = this.#command.getCommands();
? [
...(this.getAliases()[this.#completion?.completionKey] ?? []),
].some((key: string) =>
Object.prototype.hasOwnProperty.call(argv, key)
: false;
const skipRecommendation = helpOptSet || requestCompletions || helpOnly;
if (argv._.length) {
for (let i = commandIndex || 0, cmd; argv._[i] !== undefined; i++) {
cmd = String(argv._[i]);
if (handlerKeys.includes(cmd) && cmd !== this.#completionCommand) {
// the deepest command first; we keep track of the position in the
// argv._ array that is currently being executed.
const innerArgv = this.#command.runCommand(
cmd,
this,
parsed,
i + 1,
// Don't run a handler, just figure out the help string:
helpOnly,
// Passed to builder so that expensive commands can be deferred:
helpOptSet || versionOptSet || helpOnly
);
return this[kPostProcess](
innerArgv,
populateDoubleDash,
!!calledFromCommand,
false
);
cmd !== this.#completionCommand
) {
break;
}
// been enabled, and no commands were found to execute
if (
!this.#command.hasDefaultCommand() &&
firstUnknownCommand &&
firstUnknownCommand,
handlerKeys
);
}
// generate a completion script for adding to ~/.bashrc.
if (
this.#completionCommand &&
argv._.includes(this.#completionCommand) &&
this.showCompletionScript();
this.exit(0);
}
null,
this,
parsed,
0,
helpOnly,
helpOptSet || versionOptSet || helpOnly
);
return this[kPostProcess](
innerArgv,
populateDoubleDash,
!!calledFromCommand,
false
);
}
// we must run completions first, a user might
// want to complete the --help or --version option.
if (requestCompletions) {
// we allow for asynchronous completions,
// e.g., loading in a list of commands from an API.
args = ([] as string[]).concat(args);
const completionArgs = args.slice(
args.indexOf(`--${this.#completion!.completionKey}`) + 1
);
this.#completion!.getCompletion(completionArgs, (err, completions) => {
if (err) throw new YError(err.message);
(completions || []).forEach(completion => {
this.exit(0);
});
return this[kPostProcess](
argv,
!populateDoubleDash,
!!calledFromCommand,
false // Don't run middleware when figuring out completion.
);
}
// Handle 'help' and 'version' options
// if we haven't already output help!
if (!this.#hasOutput) {
skipValidation = true;
this.showHelp(message => {
this.#logger.log(message);
this.exit(0);
});
skipValidation = true;
this.#usage.showVersion('log');
this.exit(0);
}
// Check if any of the options to skip validation were provided
key =>
this.#options.skipValidation.indexOf(key) >= 0 && argv[key] === true
);
}
// If the help or version options were used and exitProcess is false,
// or if explicitly skipped, we won't run validations.
if (!skipValidation) {
// if we're executed via bash completion, don't
// bother with validation.
if (!requestCompletions) {
const validation = this[kRunValidation](aliases, {}, parsed.error);
if (!calledFromCommand) {
argvPromise = applyMiddleware(
argv,
this,
this.#globalMiddleware.getMiddleware(),
true
);
}
argvPromise = this[kValidateAsync](validation, argvPromise ?? argv);
if (isPromise(argvPromise) && !calledFromCommand) {
argv,
this,
this.#globalMiddleware.getMiddleware(),
false
);
}
return this[kPostProcess](
populateDoubleDash,
!!calledFromCommand,
true
);
}
positionalMap: Dictionary<string[]>,
parseErrors: Error | null,
isDefaultCommand?: boolean
): (argv: Arguments) => void {
const demandedOptions = {...this.getDemandedOptions()};
return (argv: Arguments) => {
this.#validation.nonOptionCount(argv);
this.#validation.requiredArguments(argv, demandedOptions);
let failedStrictCommands = false;
if (this.#strictCommands) {
}
argv,
aliases,
positionalMap,
!!isDefaultCommand
);
}
this.#validation.implications(argv);
this.#validation.conflicting(argv);
}
}
this.#options.key[keys] = true;
} else {
}
export function isYargsInstance(y: YargsInstance | void): y is YargsInstance {
}
/** Yargs' context. */
export interface Context {
commands: string[];
fullCommands: string[];
}
interface LoggerInstance {
error: Function;
log: Function;
}
export interface Options extends ParserOptions {
__: (format: any, ...param: any[]) => string;
alias: Dictionary<string[]>;
array: string[];
boolean: string[];
choices: Dictionary<string[]>;
config: Dictionary<ConfigCallback | boolean>;
configObjects: Dictionary[];
configuration: Configuration;
count: string[];
defaultDescription: Dictionary<string | undefined>;
demandedCommands: Dictionary<{
min: number;
max: number;
minMsg?: string | null;
maxMsg?: string | null;
}>;
demandedOptions: Dictionary<string | undefined>;
deprecatedOptions: Dictionary<string | boolean | undefined>;
hiddenOptions: string[];
/** Manually set keys */
key: Dictionary<boolean | string>;
local: string[];
normalize: string[];
number: string[];
showHiddenOpt: string;
skipValidation: string[];
string: string[];
}
export interface Configuration extends Partial<ParserConfiguration> {
/** Should a config object be deep-merged with the object config it extends? */
'deep-merge-config'?: boolean;
/** Should commands be sorted in help? */
'sort-commands'?: boolean;
}
export interface UsageConfiguration {
/** Should types be hidden when usage is displayed */
'hide-types'?: boolean;
}
export interface OptionDefinition {
alias?: string | string[];
array?: boolean;
boolean?: boolean;
choices?: string | string[];
coerce?: CoerceCallback;
config?: boolean;
configParser?: ConfigCallback;
conflicts?: string | string[];
count?: boolean;
default?: any;
defaultDescription?: string;
deprecate?: string | boolean;
deprecated?: OptionDefinition['deprecate'];
desc?: string;
describe?: OptionDefinition['desc'];
description?: OptionDefinition['desc'];
demand?: string | true;
demandOption?: OptionDefinition['demand'];
global?: boolean;
group?: string;
hidden?: boolean;
implies?: string | number | KeyOrPos[];
nargs?: number;
normalize?: boolean;
number?: boolean;
require?: OptionDefinition['demand'];
required?: OptionDefinition['demand'];
requiresArg?: boolean;
skipValidation?: boolean;
string?: boolean;
type?: 'array' | 'boolean' | 'count' | 'number' | 'string';
}
interface PositionalDefinition extends Pick<
OptionDefinition,
| 'alias'
| 'array'
| 'coerce'
| 'choices'
| 'conflicts'
| 'default'
| 'defaultDescription'
| 'demand'
| 'desc'
| 'describe'
| 'description'
| 'implies'
| 'normalize'
> {
type?: 'boolean' | 'number' | 'string';
}
interface FrozenYargsInstance {
options: Options;
configObjects: Dictionary[];
exitProcess: boolean;
groups: Dictionary<string[]>;
strict: boolean;
strictCommands: boolean;
strictOptions: boolean;
completionCommand: string | null;
output: string;
exitError: YError | string | nil;
hasOutput: boolean;
parsed: DetailedArguments | false;
parseFn: ParseCallback | null;
parseContext: object | null;
}
interface ParseCallback {
(err: YError | string | nil, argv: Arguments, output: string): void;
}
interface Aliases {
[key: string]: Array<string>;
}
export interface Arguments {
/** The script name or node command */
$0: string;
/** Non-option arguments */
_: ArgsOutput;
/** Arguments after the end-of-options flag `--` */
'--'?: ArgsOutput;
/** All remaining options */
[argName: string]: any;
}
export interface DetailedArguments extends ParserDetailedArguments {
argv: Arguments;
aliases: Dictionary<string[]>;
}