UNPKG

49.7 kBTypeScriptView Raw
1// Type definitions for yargs 17.0
2// Project: https://github.com/chevex/yargs, https://yargs.js.org
3// Definitions by: Martin Poelstra <https://github.com/poelstra>
4// Mizunashi Mana <https://github.com/mizunashi-mana>
5// Jeffery Grajkowski <https://github.com/pushplay>
6// Jimi (Dimitris) Charalampidis <https://github.com/JimiC>
7// Steffen Viken Valvåg <https://github.com/steffenvv>
8// Emily Marigold Klassen <https://github.com/forivall>
9// ExE Boss <https://github.com/ExE-Boss>
10// Aankhen <https://github.com/Aankhen>
11// Ben Coe <https://github.com/bcoe>
12// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
13// TypeScript Version: 3.0
14
15// The following TSLint rules have been disabled:
16// unified-signatures: Because there is useful information in the argument names of the overloaded signatures
17
18// Convention:
19// Use 'union types' when:
20// - parameter types have similar signature type (i.e. 'string | ReadonlyArray<string>')
21// - parameter names have the same semantic meaning (i.e. ['command', 'commands'] , ['key', 'keys'])
22// An example for not using 'union types' is the declaration of 'env' where `prefix` and `enable` parameters
23// have different semantics. On the other hand, in the declaration of 'usage', a `command: string` parameter
24// has the same semantic meaning with declaring an overload method by using `commands: ReadonlyArray<string>`,
25// thus it's preferred to use `command: string | ReadonlyArray<string>`
26// Use parameterless declaration instead of declaring all parameters optional,
27// when all parameters are optional and more than one
28
29import { DetailedArguments, Configuration } from 'yargs-parser';
30
31declare namespace yargs {
32 type BuilderCallback<T, R> = ((args: Argv<T>) => PromiseLike<Argv<R>>) | ((args: Argv<T>) => Argv<R>) | ((args: Argv<T>) => void);
33
34 type ParserConfigurationOptions = Configuration & {
35 /** Sort commands alphabetically. Default is `false` */
36 'sort-commands': boolean;
37 };
38
39 /**
40 * The type parameter `T` is the expected shape of the parsed options.
41 * `Arguments<T>` is those options plus `_` and `$0`, and an indexer falling
42 * back to `unknown` for unknown options.
43 *
44 * For the return type / `argv` property, we create a mapped type over
45 * `Arguments<T>` to simplify the inferred type signature in client code.
46 */
47 interface Argv<T = {}> {
48 (): { [key in keyof Arguments<T>]: Arguments<T>[key] } | Promise<{ [key in keyof Arguments<T>]: Arguments<T>[key] }>;
49 (args: ReadonlyArray<string>, cwd?: string): Argv<T>;
50
51 /**
52 * Set key names as equivalent such that updates to a key will propagate to aliases and vice-versa.
53 *
54 * Optionally `.alias()` can take an object that maps keys to aliases.
55 * Each key of this object should be the canonical version of the option, and each value should be a string or an array of strings.
56 */
57 // Aliases for previously declared options can inherit the types of those options.
58 alias<K1 extends keyof T, K2 extends string>(shortName: K1, longName: K2 | ReadonlyArray<K2>): Argv<T & { [key in K2]: T[K1] }>;
59 alias<K1 extends keyof T, K2 extends string>(shortName: K2, longName: K1 | ReadonlyArray<K1>): Argv<T & { [key in K2]: T[K1] }>;
60 alias(shortName: string | ReadonlyArray<string>, longName: string | ReadonlyArray<string>): Argv<T>;
61 alias(aliases: { [shortName: string]: string | ReadonlyArray<string> }): Argv<T>;
62
63 /**
64 * Get the arguments as a plain old object.
65 *
66 * Arguments without a corresponding flag show up in the `argv._` array.
67 *
68 * The script name or node command is available at `argv.$0` similarly to how `$0` works in bash or perl.
69 *
70 * If `yargs` is executed in an environment that embeds node and there's no script name (e.g. Electron or nw.js),
71 * it will ignore the first parameter since it expects it to be the script name. In order to override
72 * this behavior, use `.parse(process.argv.slice(1))` instead of .argv and the first parameter won't be ignored.
73 */
74 argv: { [key in keyof Arguments<T>]: Arguments<T>[key] } | Promise<{ [key in keyof Arguments<T>]: Arguments<T>[key] }>;
75
76 /**
77 * Tell the parser to interpret `key` as an array.
78 * If `.array('foo')` is set, `--foo foo bar` will be parsed as `['foo', 'bar']` rather than as `'foo'`.
79 * Also, if you use the option multiple times all the values will be flattened in one array so `--foo foo --foo bar` will be parsed as `['foo', 'bar']`
80 *
81 * When the option is used with a positional, use `--` to tell `yargs` to stop adding values to the array.
82 */
83 array<K extends keyof T>(key: K | ReadonlyArray<K>): Argv<Omit<T, K> & { [key in K]: ToArray<T[key]> }>;
84 array<K extends string>(key: K | ReadonlyArray<K>): Argv<T & { [key in K]: Array<string | number> | undefined }>;
85
86 /**
87 * Interpret `key` as a boolean. If a non-flag option follows `key` in `process.argv`, that string won't get set as the value of `key`.
88 *
89 * `key` will default to `false`, unless a `default(key, undefined)` is explicitly set.
90 *
91 * If `key` is an array, interpret all the elements as booleans.
92 */
93 boolean<K extends keyof T>(key: K | ReadonlyArray<K>): Argv<Omit<T, K> & { [key in K]: boolean | undefined }>;
94 boolean<K extends string>(key: K | ReadonlyArray<K>): Argv<T & { [key in K]: boolean | undefined }>;
95
96 /**
97 * Check that certain conditions are met in the provided arguments.
98 * @param func Called with two arguments, the parsed `argv` hash and an array of options and their aliases.
99 * If `func` throws or returns a non-truthy value, show the thrown error, usage information, and exit.
100 * @param global Indicates whether `check()` should be enabled both at the top-level and for each sub-command.
101 */
102 check(func: (argv: Arguments<T>, aliases: { [alias: string]: string }) => any, global?: boolean): Argv<T>;
103
104 /**
105 * Limit valid values for key to a predefined set of choices, given as an array or as an individual value.
106 * If this method is called multiple times, all enumerated values will be merged together.
107 * Choices are generally strings or numbers, and value matching is case-sensitive.
108 *
109 * Optionally `.choices()` can take an object that maps multiple keys to their choices.
110 *
111 * Choices can also be specified as choices in the object given to `option()`.
112 */
113 choices<K extends keyof T, C extends ReadonlyArray<any>>(key: K, values: C): Argv<Omit<T, K> & { [key in K]: C[number] | undefined }>;
114 choices<K extends string, C extends ReadonlyArray<any>>(key: K, values: C): Argv<T & { [key in K]: C[number] | undefined }>;
115 choices<C extends { [key: string]: ReadonlyArray<any> }>(choices: C): Argv<Omit<T, keyof C> & { [key in keyof C]: C[key][number] | undefined }>;
116
117 /**
118 * Provide a synchronous function to coerce or transform the value(s) given on the command line for `key`.
119 *
120 * The coercion function should accept one argument, representing the parsed value from the command line, and should return a new value or throw an error.
121 * The returned value will be used as the value for `key` (or one of its aliases) in `argv`.
122 *
123 * If the function throws, the error will be treated as a validation failure, delegating to either a custom `.fail()` handler or printing the error message in the console.
124 *
125 * Coercion will be applied to a value after all other modifications, such as `.normalize()`.
126 *
127 * Optionally `.coerce()` can take an object that maps several keys to their respective coercion function.
128 *
129 * You can also map the same function to several keys at one time. Just pass an array of keys as the first argument to `.coerce()`.
130 *
131 * If you are using dot-notion or arrays, .e.g., `user.email` and `user.password`, coercion will be applied to the final object that has been parsed
132 */
133 coerce<K extends keyof T, V>(key: K | ReadonlyArray<K>, func: (arg: any) => V): Argv<Omit<T, K> & { [key in K]: V | undefined }>;
134 coerce<K extends string, V>(key: K | ReadonlyArray<K>, func: (arg: any) => V): Argv<T & { [key in K]: V | undefined }>;
135 coerce<O extends { [key: string]: (arg: any) => any }>(opts: O): Argv<Omit<T, keyof O> & { [key in keyof O]: ReturnType<O[key]> | undefined }>;
136
137 /**
138 * Define the commands exposed by your application.
139 * @param command Should be a string representing the command or an array of strings representing the command and its aliases.
140 * @param description Use to provide a description for each command your application accepts (the values stored in `argv._`).
141 * Set `description` to false to create a hidden command. Hidden commands don't show up in the help output and aren't available for completion.
142 * @param [builder] Object to give hints about the options that your command accepts.
143 * Can also be a function. This function is executed with a yargs instance, and can be used to provide advanced command specific help.
144 *
145 * Note that when `void` is returned, the handler `argv` object type will not include command-specific arguments.
146 * @param [handler] Function, which will be executed with the parsed `argv` object.
147 */
148 command<U = T>(
149 command: string | ReadonlyArray<string>,
150 description: string,
151 builder?: BuilderCallback<T, U>,
152 handler?: (args: Arguments<U>) => void,
153 middlewares?: MiddlewareFunction[],
154 deprecated?: boolean | string,
155 ): Argv<U>;
156 command<O extends { [key: string]: Options }>(
157 command: string | ReadonlyArray<string>,
158 description: string,
159 builder?: O,
160 handler?: (args: Arguments<InferredOptionTypes<O>>) => void,
161 middlewares?: MiddlewareFunction[],
162 deprecated?: boolean | string,
163 ): Argv<T>;
164 command<U>(command: string | ReadonlyArray<string>, description: string, module: CommandModule<T, U>): Argv<U>;
165 command<U = T>(
166 command: string | ReadonlyArray<string>,
167 showInHelp: false,
168 builder?: BuilderCallback<T, U>,
169 handler?: (args: Arguments<U>) => void,
170 middlewares?: MiddlewareFunction[],
171 deprecated?: boolean | string,
172 ): Argv<T>;
173 command<O extends { [key: string]: Options }>(
174 command: string | ReadonlyArray<string>,
175 showInHelp: false,
176 builder?: O,
177 handler?: (args: Arguments<InferredOptionTypes<O>>) => void,
178 ): Argv<T>;
179 command<U>(command: string | ReadonlyArray<string>, showInHelp: false, module: CommandModule<T, U>): Argv<U>;
180 command<U>(module: CommandModule<T, U>): Argv<U>;
181
182 // Advanced API
183 /** Apply command modules from a directory relative to the module calling this method. */
184 commandDir(dir: string, opts?: RequireDirectoryOptions): Argv<T>;
185
186 /**
187 * Enable bash/zsh-completion shortcuts for commands and options.
188 *
189 * If invoked without parameters, `.completion()` will make completion the command to output the completion script.
190 *
191 * @param [cmd] When present in `argv._`, will result in the `.bashrc` or `.zshrc` completion script being outputted.
192 * To enable bash/zsh completions, concat the generated script to your `.bashrc` or `.bash_profile` (or `.zshrc` for zsh).
193 * @param [description] Provide a description in your usage instructions for the command that generates the completion scripts.
194 * @param [func] Rather than relying on yargs' default completion functionality, which shiver me timbers is pretty awesome, you can provide your own completion method.
195 */
196 completion(): Argv<T>;
197 completion(cmd: string, func?: AsyncCompletionFunction): Argv<T>;
198 completion(cmd: string, func?: SyncCompletionFunction): Argv<T>;
199 completion(cmd: string, func?: PromiseCompletionFunction): Argv<T>;
200 completion(cmd: string, description?: string | false, func?: AsyncCompletionFunction): Argv<T>;
201 completion(cmd: string, description?: string | false, func?: SyncCompletionFunction): Argv<T>;
202 completion(cmd: string, description?: string | false, func?: PromiseCompletionFunction): Argv<T>;
203
204 /**
205 * Tells the parser that if the option specified by `key` is passed in, it should be interpreted as a path to a JSON config file.
206 * The file is loaded and parsed, and its properties are set as arguments.
207 * Because the file is loaded using Node's require(), the filename MUST end in `.json` to be interpreted correctly.
208 *
209 * If invoked without parameters, `.config()` will make --config the option to pass the JSON config file.
210 *
211 * @param [description] Provided to customize the config (`key`) option in the usage string.
212 * @param [explicitConfigurationObject] An explicit configuration `object`
213 */
214 config(): Argv<T>;
215 config(key: string | ReadonlyArray<string>, description?: string, parseFn?: (configPath: string) => object): Argv<T>;
216 config(key: string | ReadonlyArray<string>, parseFn: (configPath: string) => object): Argv<T>;
217 config(explicitConfigurationObject: object): Argv<T>;
218
219 /**
220 * Given the key `x` is set, the key `y` must not be set. `y` can either be a single string or an array of argument names that `x` conflicts with.
221 *
222 * Optionally `.conflicts()` can accept an object specifying multiple conflicting keys.
223 */
224 conflicts(key: string, value: string | ReadonlyArray<string>): Argv<T>;
225 conflicts(conflicts: { [key: string]: string | ReadonlyArray<string> }): Argv<T>;
226
227 /**
228 * Interpret `key` as a boolean flag, but set its parsed value to the number of flag occurrences rather than `true` or `false`. Default value is thus `0`.
229 */
230 count<K extends keyof T>(key: K | ReadonlyArray<K>): Argv<Omit<T, K> & { [key in K]: number }>;
231 count<K extends string>(key: K | ReadonlyArray<K>): Argv<T & { [key in K]: number }>;
232
233 /**
234 * Set `argv[key]` to `value` if no option was specified in `process.argv`.
235 *
236 * Optionally `.default()` can take an object that maps keys to default values.
237 *
238 * The default value can be a `function` which returns a value. The name of the function will be used in the usage string.
239 *
240 * Optionally, `description` can also be provided and will take precedence over displaying the value in the usage instructions.
241 */
242 default<K extends keyof T, V>(key: K, value: V, description?: string): Argv<Omit<T, K> & { [key in K]: V }>;
243 default<K extends string, V>(key: K, value: V, description?: string): Argv<T & { [key in K]: V }>;
244 default<D extends { [key: string]: any }>(defaults: D, description?: string): Argv<Omit<T, keyof D> & D>;
245
246 /**
247 * @deprecated since version 6.6.0
248 * Use '.demandCommand()' or '.demandOption()' instead
249 */
250 demand<K extends keyof T>(key: K | ReadonlyArray<K>, msg?: string | true): Argv<Defined<T, K>>;
251 demand<K extends string>(key: K | ReadonlyArray<K>, msg?: string | true): Argv<T & { [key in K]: unknown }>;
252 demand(key: string | ReadonlyArray<string>, required?: boolean): Argv<T>;
253 demand(positionals: number, msg: string): Argv<T>;
254 demand(positionals: number, required?: boolean): Argv<T>;
255 demand(positionals: number, max: number, msg?: string): Argv<T>;
256
257 /**
258 * @param key If is a string, show the usage information and exit if key wasn't specified in `process.argv`.
259 * If is an array, demand each element.
260 * @param msg If string is given, it will be printed when the argument is missing, instead of the standard error message.
261 * @param demand Controls whether the option is demanded; this is useful when using .options() to specify command line parameters.
262 */
263 demandOption<K extends keyof T>(key: K | ReadonlyArray<K>, msg?: string | true): Argv<Defined<T, K>>;
264 demandOption<K extends string>(key: K | ReadonlyArray<K>, msg?: string | true): Argv<T & { [key in K]: unknown }>;
265 demandOption(key: string | ReadonlyArray<string>, demand?: boolean): Argv<T>;
266
267 /**
268 * Demand in context of commands.
269 * You can demand a minimum and a maximum number a user can have within your program, as well as provide corresponding error messages if either of the demands is not met.
270 */
271 demandCommand(): Argv<T>;
272 demandCommand(min: number, minMsg?: string): Argv<T>;
273 demandCommand(min: number, max?: number, minMsg?: string, maxMsg?: string): Argv<T>;
274
275 /**
276 * Shows a [deprecated] notice in front of the option
277 */
278 deprecateOption(option: string, msg?: string): Argv<T>;
279
280 /**
281 * Describe a `key` for the generated usage information.
282 *
283 * Optionally `.describe()` can take an object that maps keys to descriptions.
284 */
285 describe(key: string | ReadonlyArray<string>, description: string): Argv<T>;
286 describe(descriptions: { [key: string]: string }): Argv<T>;
287
288 /** Should yargs attempt to detect the os' locale? Defaults to `true`. */
289 detectLocale(detect: boolean): Argv<T>;
290
291 /**
292 * Tell yargs to parse environment variables matching the given prefix and apply them to argv as though they were command line arguments.
293 *
294 * Use the "__" separator in the environment variable to indicate nested options. (e.g. prefix_nested__foo => nested.foo)
295 *
296 * If this method is called with no argument or with an empty string or with true, then all env vars will be applied to argv.
297 *
298 * Program arguments are defined in this order of precedence:
299 * 1. Command line args
300 * 2. Env vars
301 * 3. Config file/objects
302 * 4. Configured defaults
303 *
304 * Env var parsing is disabled by default, but you can also explicitly disable it by calling `.env(false)`, e.g. if you need to undo previous configuration.
305 */
306 env(): Argv<T>;
307 env(prefix: string): Argv<T>;
308 env(enable: boolean): Argv<T>;
309
310 /** A message to print at the end of the usage instructions */
311 epilog(msg: string): Argv<T>;
312 /** A message to print at the end of the usage instructions */
313 epilogue(msg: string): Argv<T>;
314
315 /**
316 * Give some example invocations of your program.
317 * Inside `cmd`, the string `$0` will get interpolated to the current script name or node command for the present script similar to how `$0` works in bash or perl.
318 * Examples will be printed out as part of the help message.
319 */
320 example(command: string, description: string): Argv<T>;
321 example(command: ReadonlyArray<[string, string?]>): Argv<T>;
322
323 /** Manually indicate that the program should exit, and provide context about why we wanted to exit. Follows the behavior set by `.exitProcess().` */
324 exit(code: number, err: Error): void;
325
326 /**
327 * By default, yargs exits the process when the user passes a help flag, the user uses the `.version` functionality, validation fails, or the command handler fails.
328 * Calling `.exitProcess(false)` disables this behavior, enabling further actions after yargs have been validated.
329 */
330 exitProcess(enabled: boolean): Argv<T>;
331
332 /**
333 * Method to execute when a failure occurs, rather than printing the failure message.
334 * @param func Is called with the failure message that would have been printed, the Error instance originally thrown and yargs state when the failure occurred.
335 */
336 fail(func: ((msg: string, err: Error, yargs: Argv<T>) => any) | boolean): Argv<T>;
337
338 /**
339 * Allows to programmatically get completion choices for any line.
340 * @param args An array of the words in the command line to complete.
341 * @param done The callback to be called with the resulting completions.
342 */
343 getCompletion(args: ReadonlyArray<string>, done: (completions: ReadonlyArray<string>) => void): Argv<T>;
344
345 /**
346 * Returns a promise which resolves to a string containing the help text.
347 */
348 getHelp(): Promise<string>;
349
350 /**
351 * Indicate that an option (or group of options) should not be reset when a command is executed
352 *
353 * Options default to being global.
354 */
355 global(key: string | ReadonlyArray<string>): Argv<T>;
356
357 /** Given a key, or an array of keys, places options under an alternative heading when displaying usage instructions */
358 group(key: string | ReadonlyArray<string>, groupName: string): Argv<T>;
359
360 /** Hides a key from the generated usage information. Unless a `--show-hidden` option is also passed with `--help` (see `showHidden()`). */
361 hide(key: string): Argv<T>;
362
363 /**
364 * Configure an (e.g. `--help`) and implicit command that displays the usage string and exits the process.
365 * By default yargs enables help on the `--help` option.
366 *
367 * Note that any multi-char aliases (e.g. `help`) used for the help option will also be used for the implicit command.
368 * If there are no multi-char aliases (e.g. `h`), then all single-char aliases will be used for the command.
369 *
370 * If invoked without parameters, `.help()` will use `--help` as the option and help as the implicit command to trigger help output.
371 *
372 * @param [description] Customizes the description of the help option in the usage string.
373 * @param [enableExplicit] If `false` is provided, it will disable --help.
374 */
375 help(): Argv<T>;
376 help(enableExplicit: boolean): Argv<T>;
377 help(option: string, enableExplicit: boolean): Argv<T>;
378 help(option: string, description?: string, enableExplicit?: boolean): Argv<T>;
379
380 /**
381 * Given the key `x` is set, it is required that the key `y` is set.
382 * y` can either be the name of an argument to imply, a number indicating the position of an argument or an array of multiple implications to associate with `x`.
383 *
384 * Optionally `.implies()` can accept an object specifying multiple implications.
385 */
386 implies(key: string, value: string | ReadonlyArray<string>): Argv<T>;
387 implies(implies: { [key: string]: string | ReadonlyArray<string> }): Argv<T>;
388
389 /**
390 * Return the locale that yargs is currently using.
391 *
392 * By default, yargs will auto-detect the operating system's locale so that yargs-generated help content will display in the user's language.
393 */
394 locale(): string;
395 /**
396 * Override the auto-detected locale from the user's operating system with a static locale.
397 * Note that the OS locale can be modified by setting/exporting the `LC_ALL` environment variable.
398 */
399 locale(loc: string): Argv<T>;
400
401 /**
402 * Define global middleware functions to be called first, in list order, for all cli command.
403 * @param callbacks Can be a function or a list of functions. Each callback gets passed a reference to argv.
404 * @param [applyBeforeValidation] Set to `true` to apply middleware before validation. This will execute the middleware prior to validation checks, but after parsing.
405 */
406 middleware(callbacks: MiddlewareFunction<T> | ReadonlyArray<MiddlewareFunction<T>>, applyBeforeValidation?: boolean): Argv<T>;
407
408 /**
409 * The number of arguments that should be consumed after a key. This can be a useful hint to prevent parsing ambiguity.
410 *
411 * Optionally `.nargs()` can take an object of `key`/`narg` pairs.
412 */
413 nargs(key: string, count: number): Argv<T>;
414 nargs(nargs: { [key: string]: number }): Argv<T>;
415
416 /** The key provided represents a path and should have `path.normalize()` applied. */
417 normalize<K extends keyof T>(key: K | ReadonlyArray<K>): Argv<Omit<T, K> & { [key in K]: ToString<T[key]> }>;
418 normalize<K extends string>(key: K | ReadonlyArray<K>): Argv<T & { [key in K]: string | undefined }>;
419
420 /**
421 * Tell the parser to always interpret key as a number.
422 *
423 * If `key` is an array, all elements will be parsed as numbers.
424 *
425 * If the option is given on the command line without a value, `argv` will be populated with `undefined`.
426 *
427 * If the value given on the command line cannot be parsed as a number, `argv` will be populated with `NaN`.
428 *
429 * Note that decimals, hexadecimals, and scientific notation are all accepted.
430 */
431 number<K extends keyof T>(key: K | ReadonlyArray<K>): Argv<Omit<T, K> & { [key in K]: ToNumber<T[key]> }>;
432 number<K extends string>(key: K | ReadonlyArray<K>): Argv<T & { [key in K]: number | undefined }>;
433
434 /**
435 * Method to execute when a command finishes successfully.
436 * @param func Is called with the successful result of the command that finished.
437 */
438 onFinishCommand(func: (result: any) => void): Argv<T>;
439
440 /**
441 * This method can be used to make yargs aware of options that could exist.
442 * You can also pass an opt object which can hold further customization, like `.alias()`, `.demandOption()` etc. for that option.
443 */
444 option<K extends keyof T, O extends Options>(key: K, options: O): Argv<Omit<T, K> & { [key in K]: InferredOptionType<O> }>;
445 option<K extends string, O extends Options>(key: K, options: O): Argv<T & { [key in K]: InferredOptionType<O> }>;
446 option<O extends { [key: string]: Options }>(options: O): Argv<Omit<T, keyof O> & InferredOptionTypes<O>>;
447
448 /**
449 * This method can be used to make yargs aware of options that could exist.
450 * You can also pass an opt object which can hold further customization, like `.alias()`, `.demandOption()` etc. for that option.
451 */
452 options<K extends keyof T, O extends Options>(key: K, options: O): Argv<Omit<T, K> & { [key in K]: InferredOptionType<O> }>;
453 options<K extends string, O extends Options>(key: K, options: O): Argv<T & { [key in K]: InferredOptionType<O> }>;
454 options<O extends { [key: string]: Options }>(options: O): Argv<Omit<T, keyof O> & InferredOptionTypes<O>>;
455
456 /**
457 * Parse `args` instead of `process.argv`. Returns the `argv` object. `args` may either be a pre-processed argv array, or a raw argument string.
458 *
459 * Note: Providing a callback to parse() disables the `exitProcess` setting until after the callback is invoked.
460 * @param [context] Provides a useful mechanism for passing state information to commands
461 */
462 parse(): { [key in keyof Arguments<T>]: Arguments<T>[key] } | Promise<{ [key in keyof Arguments<T>]: Arguments<T>[key] }>;
463 parse(arg: string | ReadonlyArray<string>, context?: object, parseCallback?: ParseCallback<T>): { [key in keyof Arguments<T>]: Arguments<T>[key] }
464 | Promise<{ [key in keyof Arguments<T>]: Arguments<T>[key] }>;
465 parseSync(): { [key in keyof Arguments<T>]: Arguments<T>[key] };
466 parseSync(arg: string | ReadonlyArray<string>, context?: object, parseCallback?: ParseCallback<T>): { [key in keyof Arguments<T>]: Arguments<T>[key] };
467 parseAsync(): Promise<{ [key in keyof Arguments<T>]: Arguments<T>[key] }>;
468 parseAsync(arg: string | ReadonlyArray<string>, context?: object, parseCallback?: ParseCallback<T>): Promise<{ [key in keyof Arguments<T>]: Arguments<T>[key] }>;
469
470 /**
471 * If the arguments have not been parsed, this property is `false`.
472 *
473 * If the arguments have been parsed, this contain detailed parsed arguments.
474 */
475 parsed: DetailedArguments | false;
476
477 /** Allows to configure advanced yargs features. */
478 parserConfiguration(configuration: Partial<ParserConfigurationOptions>): Argv<T>;
479
480 /**
481 * Similar to `config()`, indicates that yargs should interpret the object from the specified key in package.json as a configuration object.
482 * @param [cwd] If provided, the package.json will be read from this location
483 */
484 pkgConf(key: string | ReadonlyArray<string>, cwd?: string): Argv<T>;
485
486 /**
487 * Allows you to configure a command's positional arguments with an API similar to `.option()`.
488 * `.positional()` should be called in a command's builder function, and is not available on the top-level yargs instance. If so, it will throw an error.
489 */
490 positional<K extends keyof T, O extends PositionalOptions>(key: K, opt: O): Argv<Omit<T, K> & { [key in K]: InferredOptionType<O> }>;
491 positional<K extends string, O extends PositionalOptions>(key: K, opt: O): Argv<T & { [key in K]: InferredOptionType<O> }>;
492
493 /** Should yargs provide suggestions regarding similar commands if no matching command is found? */
494 recommendCommands(): Argv<T>;
495
496 /**
497 * @deprecated since version 6.6.0
498 * Use '.demandCommand()' or '.demandOption()' instead
499 */
500 require<K extends keyof T>(key: K | ReadonlyArray<K>, msg?: string | true): Argv<Defined<T, K>>;
501 require(key: string, msg: string): Argv<T>;
502 require(key: string, required: boolean): Argv<T>;
503 require(keys: ReadonlyArray<number>, msg: string): Argv<T>;
504 require(keys: ReadonlyArray<number>, required: boolean): Argv<T>;
505 require(positionals: number, required: boolean): Argv<T>;
506 require(positionals: number, msg: string): Argv<T>;
507
508 /**
509 * @deprecated since version 6.6.0
510 * Use '.demandCommand()' or '.demandOption()' instead
511 */
512 required<K extends keyof T>(key: K | ReadonlyArray<K>, msg?: string | true): Argv<Defined<T, K>>;
513 required(key: string, msg: string): Argv<T>;
514 required(key: string, required: boolean): Argv<T>;
515 required(keys: ReadonlyArray<number>, msg: string): Argv<T>;
516 required(keys: ReadonlyArray<number>, required: boolean): Argv<T>;
517 required(positionals: number, required: boolean): Argv<T>;
518 required(positionals: number, msg: string): Argv<T>;
519
520 requiresArg(key: string | ReadonlyArray<string>): Argv<T>;
521
522 /** Set the name of your script ($0). Default is the base filename executed by node (`process.argv[1]`) */
523 scriptName($0: string): Argv<T>;
524
525 /**
526 * Generate a bash completion script.
527 * Users of your application can install this script in their `.bashrc`, and yargs will provide completion shortcuts for commands and options.
528 */
529 showCompletionScript(): Argv<T>;
530
531 /**
532 * Configure the `--show-hidden` option that displays the hidden keys (see `hide()`).
533 * @param option If `boolean`, it enables/disables this option altogether. i.e. hidden keys will be permanently hidden if first argument is `false`.
534 * If `string` it changes the key name ("--show-hidden").
535 * @param description Changes the default description ("Show hidden options")
536 */
537 showHidden(option?: string | boolean): Argv<T>;
538 showHidden(option: string, description?: string): Argv<T>;
539
540 /**
541 * Print the usage data using the console function consoleLevel for printing.
542 * @param [consoleLevel='error']
543 */
544 showHelp(consoleLevel?: string): Argv<T>;
545
546 /**
547 * Provide the usage data as a string.
548 * @param printCallback a function with a single argument.
549 */
550 showHelp(printCallback: (s: string) => void): Argv<T>;
551
552 /**
553 * By default, yargs outputs a usage string if any error is detected.
554 * Use the `.showHelpOnFail()` method to customize this behavior.
555 * @param enable If `false`, the usage string is not output.
556 * @param [message] Message that is output after the error message.
557 */
558 showHelpOnFail(enable: boolean, message?: string): Argv<T>;
559
560 /** Specifies either a single option key (string), or an array of options. If any of the options is present, yargs validation is skipped. */
561 skipValidation(key: string | ReadonlyArray<string>): Argv<T>;
562
563 /**
564 * Any command-line argument given that is not demanded, or does not have a corresponding description, will be reported as an error.
565 *
566 * Unrecognized commands will also be reported as errors.
567 */
568 strict(): Argv<T>;
569 strict(enabled: boolean): Argv<T>;
570
571 /**
572 * Similar to .strict(), except that it only applies to unrecognized commands.
573 * A user can still provide arbitrary options, but unknown positional commands
574 * will raise an error.
575 */
576 strictCommands(): Argv<T>;
577 strictCommands(enabled: boolean): Argv<T>;
578
579 /**
580 * Similar to `.strict()`, except that it only applies to unrecognized options. A
581 * user can still provide arbitrary positional options, but unknown options
582 * will raise an error.
583 */
584 strictOptions(): Argv<T>;
585 strictOptions(enabled: boolean): Argv<T>;
586
587 /**
588 * Tell the parser logic not to interpret `key` as a number or boolean. This can be useful if you need to preserve leading zeros in an input.
589 *
590 * If `key` is an array, interpret all the elements as strings.
591 *
592 * `.string('_')` will result in non-hyphenated arguments being interpreted as strings, regardless of whether they resemble numbers.
593 */
594 string<K extends keyof T>(key: K | ReadonlyArray<K>): Argv<Omit<T, K> & { [key in K]: ToString<T[key]> }>;
595 string<K extends string>(key: K | ReadonlyArray<K>): Argv<T & { [key in K]: string | undefined }>;
596
597 // Intended to be used with '.wrap()'
598 terminalWidth(): number;
599
600 updateLocale(obj: { [key: string]: string }): Argv<T>;
601
602 /**
603 * Override the default strings used by yargs with the key/value pairs provided in obj
604 *
605 * If you explicitly specify a locale(), you should do so before calling `updateStrings()`.
606 */
607 updateStrings(obj: { [key: string]: string }): Argv<T>;
608
609 /**
610 * Set a usage message to show which commands to use.
611 * Inside `message`, the string `$0` will get interpolated to the current script name or node command for the present script similar to how `$0` works in bash or perl.
612 *
613 * If the optional `description`/`builder`/`handler` are provided, `.usage()` acts an an alias for `.command()`.
614 * This allows you to use `.usage()` to configure the default command that will be run as an entry-point to your application
615 * and allows you to provide configuration for the positional arguments accepted by your program:
616 */
617 usage(message: string): Argv<T>;
618 usage<U>(command: string | ReadonlyArray<string>, description: string, builder?: (args: Argv<T>) => Argv<U>, handler?: (args: Arguments<U>) => void): Argv<T>;
619 usage<U>(command: string | ReadonlyArray<string>, showInHelp: boolean, builder?: (args: Argv<T>) => Argv<U>, handler?: (args: Arguments<U>) => void): Argv<T>;
620 usage<O extends { [key: string]: Options }>(command: string | ReadonlyArray<string>, description: string, builder?: O, handler?: (args: Arguments<InferredOptionTypes<O>>) => void): Argv<T>;
621 usage<O extends { [key: string]: Options }>(command: string | ReadonlyArray<string>, showInHelp: boolean, builder?: O, handler?: (args: Arguments<InferredOptionTypes<O>>) => void): Argv<T>;
622
623 /**
624 * Add an option (e.g. `--version`) that displays the version number (given by the version parameter) and exits the process.
625 * By default yargs enables version for the `--version` option.
626 *
627 * If no arguments are passed to version (`.version()`), yargs will parse the package.json of your module and use its version value.
628 *
629 * If the boolean argument `false` is provided, it will disable `--version`.
630 */
631 version(): Argv<T>;
632 version(version: string): Argv<T>;
633 version(enable: boolean): Argv<T>;
634 version(optionKey: string, version: string): Argv<T>;
635 version(optionKey: string, description: string, version: string): Argv<T>;
636
637 /**
638 * Format usage output to wrap at columns many columns.
639 *
640 * By default wrap will be set to `Math.min(80, windowWidth)`. Use `.wrap(null)` to specify no column limit (no right-align).
641 * Use `.wrap(yargs.terminalWidth())` to maximize the width of yargs' usage instructions.
642 */
643 wrap(columns: number | null): Argv<T>;
644 }
645
646 type Arguments<T = {}> = T & {
647 /** Non-option arguments */
648 _: Array<string | number>;
649 /** The script name or node command */
650 $0: string;
651 /** All remaining options */
652 [argName: string]: unknown;
653 };
654
655 interface RequireDirectoryOptions {
656 /** Look for command modules in all subdirectories and apply them as a flattened (non-hierarchical) list. */
657 recurse?: boolean | undefined;
658 /** The types of files to look for when requiring command modules. */
659 extensions?: ReadonlyArray<string> | undefined;
660 /**
661 * A synchronous function called for each command module encountered.
662 * Accepts `commandObject`, `pathToFile`, and `filename` as arguments.
663 * Returns `commandObject` to include the command; any falsy value to exclude/skip it.
664 */
665 visit?: ((commandObject: any, pathToFile?: string, filename?: string) => any) | undefined;
666 /** Whitelist certain modules */
667 include?: RegExp | ((pathToFile: string) => boolean) | undefined;
668 /** Blacklist certain modules. */
669 exclude?: RegExp | ((pathToFile: string) => boolean) | undefined;
670 }
671
672 interface Options {
673 /** string or array of strings, alias(es) for the canonical option key, see `alias()` */
674 alias?: string | ReadonlyArray<string> | undefined;
675 /** boolean, interpret option as an array, see `array()` */
676 array?: boolean | undefined;
677 /** boolean, interpret option as a boolean flag, see `boolean()` */
678 boolean?: boolean | undefined;
679 /** value or array of values, limit valid option arguments to a predefined set, see `choices()` */
680 choices?: Choices | undefined;
681 /** function, coerce or transform parsed command line values into another value, see `coerce()` */
682 coerce?: ((arg: any) => any) | undefined;
683 /** boolean, interpret option as a path to a JSON config file, see `config()` */
684 config?: boolean | undefined;
685 /** function, provide a custom config parsing function, see `config()` */
686 configParser?: ((configPath: string) => object) | undefined;
687 /** string or object, require certain keys not to be set, see `conflicts()` */
688 conflicts?: string | ReadonlyArray<string> | { [key: string]: string | ReadonlyArray<string> } | undefined;
689 /** boolean, interpret option as a count of boolean flags, see `count()` */
690 count?: boolean | undefined;
691 /** value, set a default value for the option, see `default()` */
692 default?: any;
693 /** string, use this description for the default value in help content, see `default()` */
694 defaultDescription?: string | undefined;
695 /**
696 * @deprecated since version 6.6.0
697 * Use 'demandOption' instead
698 */
699 demand?: boolean | string | undefined;
700 /** boolean or string, mark the argument as deprecated, see `deprecateOption()` */
701 deprecate?: boolean | string | undefined;
702 /** boolean or string, mark the argument as deprecated, see `deprecateOption()` */
703 deprecated?: boolean | string | undefined;
704 /** boolean or string, demand the option be given, with optional error message, see `demandOption()` */
705 demandOption?: boolean | string | undefined;
706 /** string, the option description for help content, see `describe()` */
707 desc?: string | undefined;
708 /** string, the option description for help content, see `describe()` */
709 describe?: string | undefined;
710 /** string, the option description for help content, see `describe()` */
711 description?: string | undefined;
712 /** boolean, indicate that this key should not be reset when a command is invoked, see `global()` */
713 global?: boolean | undefined;
714 /** string, when displaying usage instructions place the option under an alternative group heading, see `group()` */
715 group?: string | undefined;
716 /** don't display option in help output. */
717 hidden?: boolean | undefined;
718 /** string or object, require certain keys to be set, see `implies()` */
719 implies?: string | ReadonlyArray<string> | { [key: string]: string | ReadonlyArray<string> } | undefined;
720 /** number, specify how many arguments should be consumed for the option, see `nargs()` */
721 nargs?: number | undefined;
722 /** boolean, apply path.normalize() to the option, see `normalize()` */
723 normalize?: boolean | undefined;
724 /** boolean, interpret option as a number, `number()` */
725 number?: boolean | undefined;
726 /**
727 * @deprecated since version 6.6.0
728 * Use 'demandOption' instead
729 */
730 require?: boolean | string | undefined;
731 /**
732 * @deprecated since version 6.6.0
733 * Use 'demandOption' instead
734 */
735 required?: boolean | string | undefined;
736 /** boolean, require the option be specified with a value, see `requiresArg()` */
737 requiresArg?: boolean | undefined;
738 /** boolean, skips validation if the option is present, see `skipValidation()` */
739 skipValidation?: boolean | undefined;
740 /** boolean, interpret option as a string, see `string()` */
741 string?: boolean | undefined;
742 type?: "array" | "count" | PositionalOptionsType | undefined;
743 }
744
745 interface PositionalOptions {
746 /** string or array of strings, see `alias()` */
747 alias?: string | ReadonlyArray<string> | undefined;
748 /** boolean, interpret option as an array, see `array()` */
749 array?: boolean | undefined;
750 /** value or array of values, limit valid option arguments to a predefined set, see `choices()` */
751 choices?: Choices | undefined;
752 /** function, coerce or transform parsed command line values into another value, see `coerce()` */
753 coerce?: ((arg: any) => any) | undefined;
754 /** string or object, require certain keys not to be set, see `conflicts()` */
755 conflicts?: string | ReadonlyArray<string> | { [key: string]: string | ReadonlyArray<string> } | undefined;
756 /** value, set a default value for the option, see `default()` */
757 default?: any;
758 /** boolean or string, demand the option be given, with optional error message, see `demandOption()` */
759 demandOption?: boolean | string | undefined;
760 /** string, the option description for help content, see `describe()` */
761 desc?: string | undefined;
762 /** string, the option description for help content, see `describe()` */
763 describe?: string | undefined;
764 /** string, the option description for help content, see `describe()` */
765 description?: string | undefined;
766 /** string or object, require certain keys to be set, see `implies()` */
767 implies?: string | ReadonlyArray<string> | { [key: string]: string | ReadonlyArray<string> } | undefined;
768 /** boolean, apply path.normalize() to the option, see normalize() */
769 normalize?: boolean | undefined;
770 type?: PositionalOptionsType | undefined;
771 }
772
773 /** Remove keys K in T */
774 type Omit<T, K> = { [key in Exclude<keyof T, K>]: T[key] };
775
776 /** Remove undefined as a possible value for keys K in T */
777 type Defined<T, K extends keyof T> = Omit<T, K> & { [key in K]: Exclude<T[key], undefined> };
778
779 /** Convert T to T[] and T | undefined to T[] | undefined */
780 type ToArray<T> = Array<Exclude<T, undefined>> | Extract<T, undefined>;
781
782 /** Gives string[] if T is an array type, otherwise string. Preserves | undefined. */
783 type ToString<T> = (Exclude<T, undefined> extends any[] ? string[] : string) | Extract<T, undefined>;
784
785 /** Gives number[] if T is an array type, otherwise number. Preserves | undefined. */
786 type ToNumber<T> = (Exclude<T, undefined> extends any[] ? number[] : number) | Extract<T, undefined>;
787
788 type InferredOptionType<O extends Options | PositionalOptions> =
789 O extends (
790 | { required: string | true }
791 | { require: string | true }
792 | { demand: string | true }
793 | { demandOption: string | true }
794 ) ?
795 Exclude<InferredOptionTypeInner<O>, undefined> :
796 InferredOptionTypeInner<O>;
797
798 type InferredOptionTypeInner<O extends Options | PositionalOptions> =
799 O extends { default: any, coerce: (arg: any) => infer T } ? T :
800 O extends { default: infer D } ? D :
801 O extends { type: "count" } ? number :
802 O extends { count: true } ? number :
803 RequiredOptionType<O> | undefined;
804
805 type RequiredOptionType<O extends Options | PositionalOptions> =
806 O extends { type: "array", string: true } ? string[] :
807 O extends { type: "array", number: true } ? number[] :
808 O extends { type: "array", normalize: true } ? string[] :
809 O extends { type: "string", array: true } ? string[] :
810 O extends { type: "number", array: true } ? number[] :
811 O extends { string: true, array: true } ? string[] :
812 O extends { number: true, array: true } ? number[] :
813 O extends { normalize: true, array: true } ? string[] :
814 O extends { type: "array" } ? Array<string | number> :
815 O extends { type: "boolean" } ? boolean :
816 O extends { type: "number" } ? number :
817 O extends { type: "string" } ? string :
818 O extends { array: true } ? Array<string | number> :
819 O extends { boolean: true } ? boolean :
820 O extends { number: true } ? number :
821 O extends { string: true } ? string :
822 O extends { normalize: true } ? string :
823 O extends { choices: ReadonlyArray<infer C> } ? C :
824 O extends { coerce: (arg: any) => infer T } ? T :
825 unknown;
826
827 type InferredOptionTypes<O extends { [key: string]: Options }> = { [key in keyof O]: InferredOptionType<O[key]> };
828
829 interface CommandModule<T = {}, U = {}> {
830 /** array of strings (or a single string) representing aliases of `exports.command`, positional args defined in an alias are ignored */
831 aliases?: ReadonlyArray<string> | string | undefined;
832 /** object declaring the options the command accepts, or a function accepting and returning a yargs instance */
833 builder?: CommandBuilder<T, U> | undefined;
834 /** string (or array of strings) that executes this command when given on the command line, first string may contain positional args */
835 command?: ReadonlyArray<string> | string | undefined;
836 /** boolean (or string) to show deprecation notice */
837 deprecated?: boolean | string | undefined;
838 /** string used as the description for the command in help text, use `false` for a hidden command */
839 describe?: string | false | undefined;
840 /** a function which will be passed the parsed argv. */
841 handler: (args: Arguments<U>) => void;
842 }
843
844 type ParseCallback<T = {}> = (err: Error | undefined, argv: Arguments<T>|Promise<Arguments<T>>, output: string) => void;
845 type CommandBuilder<T = {}, U = {}> = { [key: string]: Options } | ((args: Argv<T>) => Argv<U>) | ((args: Argv<T>) => PromiseLike<Argv<U>>);
846 type SyncCompletionFunction = (current: string, argv: any) => string[];
847 type AsyncCompletionFunction = (current: string, argv: any, done: (completion: ReadonlyArray<string>) => void) => void;
848 type PromiseCompletionFunction = (current: string, argv: any) => Promise<string[]>;
849 type MiddlewareFunction<T = {}> = (args: Arguments<T>) => void;
850 type Choices = ReadonlyArray<string | number | true | undefined>;
851 type PositionalOptionsType = "boolean" | "number" | "string";
852}
853
854declare var yargs: yargs.Argv;
855export = yargs;