UNPKG

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