UNPKG

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