-
-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathindex.d.ts
1467 lines (1323 loc) · 43 KB
/
index.d.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// eslint complains about {} as a type, but hard to be more accurate.
/* eslint-disable @typescript-eslint/no-empty-object-type */
type TrimRight<S extends string> = S extends `${infer R} ` ? TrimRight<R> : S;
type TrimLeft<S extends string> = S extends ` ${infer R}` ? TrimLeft<R> : S;
type Trim<S extends string> = TrimLeft<TrimRight<S>>;
type CamelCase<S extends string> = S extends `${infer W}-${infer Rest}`
? CamelCase<`${W}${Capitalize<Rest>}`>
: S;
// This is a trick to encourage TypeScript to resolve intersections for displaying,
// like { a: number } & { b : string } => { a: number, b: string }
// References:
// - https://github.com/sindresorhus/type-fest/blob/main/source/simplify.d.ts
// - https://effectivetypescript.com/2022/02/25/gentips-4-display/
type Resolve<T> = T extends infer O ? { [K in keyof O]: O[K] } : never;
// This is a trick to encourage editor to suggest the known literals while still
// allowing any BaseType value.
// References:
// - https://github.com/microsoft/TypeScript/issues/29729
// - https://github.com/sindresorhus/type-fest/blob/main/source/literal-union.d.ts
// - https://github.com/sindresorhus/type-fest/blob/main/source/primitive.d.ts
type LiteralUnion<LiteralType, BaseType extends string | number> =
| LiteralType
| (BaseType & Record<never, never>);
// Side note: not trying to represent arrays as non-empty, keep it simple.
// https://stackoverflow.com/a/56006703/1082434
type InferVariadic<S extends string, ArgT> = S extends `${string}...`
? ArgT[]
: ArgT;
type InferArgumentType<Value extends string, DefaultT, CoerceT, ChoicesT> = [
CoerceT,
] extends [undefined]
?
| InferVariadic<Value, [ChoicesT] extends [undefined] ? string : ChoicesT>
| DefaultT
: [ChoicesT] extends [undefined]
? CoerceT | DefaultT
: CoerceT | DefaultT | ChoicesT;
// Special handling for optional variadic argument, won't be undefined as implementation returns [].
type InferArgumentOptionalType<
Value extends string,
DefaultT,
CoerceT,
ChoicesT,
> = Value extends `${string}...`
? InferArgumentType<
Value,
[DefaultT] extends [undefined] ? never : DefaultT,
CoerceT,
ChoicesT
>
: InferArgumentType<Value, DefaultT, CoerceT, ChoicesT>;
// ArgRequired comes from .argRequired()/.argOptional(), and ArgRequiredFromUsage is implied by usage <required>/[optional]
type ResolveRequired<
ArgRequired extends boolean | undefined,
ArgRequiredFromUsage extends boolean,
> = ArgRequired extends undefined ? ArgRequiredFromUsage : ArgRequired;
type InferArgumentTypeResolvedRequired<
Value extends string,
DefaultT,
CoerceT,
ArgRequired extends boolean,
ChoicesT,
> = ArgRequired extends true
? InferArgumentType<Value, never, CoerceT, ChoicesT>
: InferArgumentOptionalType<Value, DefaultT, CoerceT, ChoicesT>;
// Resolve whether argument required, and strip []/<> from around value.
type InferArgument<
S extends string,
DefaultT = undefined,
CoerceT = undefined,
ArgRequired extends boolean | undefined = undefined,
ChoicesT = undefined,
> = S extends `<${infer Value}>`
? InferArgumentTypeResolvedRequired<
Value,
DefaultT,
CoerceT,
ResolveRequired<ArgRequired, true>,
ChoicesT
>
: S extends `[${infer Value}]`
? InferArgumentTypeResolvedRequired<
Value,
DefaultT,
CoerceT,
ResolveRequired<ArgRequired, false>,
ChoicesT
>
: InferArgumentTypeResolvedRequired<
S,
DefaultT,
CoerceT,
ResolveRequired<ArgRequired, true>,
ChoicesT
>; // the implementation fallback is treat as <required>
type InferArguments<S extends string> = S extends `${infer First} ${infer Rest}`
? [InferArgument<First>, ...InferArguments<TrimLeft<Rest>>]
: [InferArgument<S>];
type InferCommandArguments<S extends string> =
S extends `${string} ${infer Args}` ? InferArguments<TrimLeft<Args>> : [];
type FlagsToFlag<Flags extends string> =
Flags extends `${string},${infer LongFlag}`
? TrimLeft<LongFlag>
: Flags extends `${string}|${infer LongFlag}`
? TrimLeft<LongFlag>
: Flags extends `${string} ${infer LongFlag}`
? TrimLeft<LongFlag>
: Flags;
type ConvertFlagToName<Flag extends string> = Flag extends `--no-${infer Name}`
? CamelCase<Name>
: Flag extends `--${infer Name}`
? CamelCase<Name>
: Flag extends `-${infer Name}`
? CamelCase<Name>
: never;
type CombineOptions<Options, O> = keyof O extends keyof Options
? {
[K in keyof Options]: K extends keyof O
? Options[K] | O[keyof O]
: Options[K];
}
: Options & O;
type IsAlwaysDefined<
DefaulT,
Mandatory extends boolean,
> = Mandatory extends true
? true
: [undefined] extends [DefaulT]
? false
: true;
// Modify PresetT to take into account negated.
type NegatePresetType<
Flag extends string,
PresetT,
> = Flag extends `--no-${string}`
? undefined extends PresetT
? false
: PresetT
: undefined extends PresetT
? true
: PresetT;
// Modify DefaultT to take into account negated.
type NegateDefaultType<
Flag extends string,
DefaultT,
> = Flag extends `--no-${string}`
? [undefined] extends [DefaultT]
? true
: DefaultT
: [undefined] extends [DefaultT]
? never
: DefaultT; // don't add undefined, will make property optional later
// Modify ValueT to take into account coerce function.
type CoerceValueType<CoerceT, ValueT> = [ValueT] extends [never]
? never
: [CoerceT] extends [undefined]
? ValueT
: CoerceT;
// Modify PresetT to take into account coerce function.
type CoercePresetType<CoerceT, PresetT> = [PresetT] extends [never]
? never
: [CoerceT] extends [undefined]
? PresetT
: undefined extends PresetT
? undefined
: CoerceT;
type BuildOptionProperty<
Name extends string,
FullValueT,
AlwaysDefined extends boolean,
> = AlwaysDefined extends true
? { [K in Name]: FullValueT }
: { [K in Name]?: FullValueT };
type InferOptionsCombine<
Options,
Name extends string,
FullValueT,
AlwaysDefined extends boolean,
> = Resolve<
CombineOptions<Options, BuildOptionProperty<Name, FullValueT, AlwaysDefined>>
>;
// Combine the possible types
type InferOptionsNegateCombo<
Options,
Flag extends string,
Name extends string,
ValueT,
PresetT,
DefaultT,
AlwaysDefined extends boolean,
> = Flag extends `--no-${string}`
? Name extends keyof Options
? InferOptionsCombine<Options, Name, PresetT, true> // combo does not set default, leave that to positive option
: InferOptionsCombine<Options, Name, PresetT | DefaultT, true> // lone negated option sets default
: InferOptionsCombine<
Options,
Name,
ValueT | PresetT | DefaultT,
AlwaysDefined
>;
// Recalc values taking into account negated option.
// Fill in appropriate PresetT value if undefined.
type InferOptionTypes<
Options,
Flag extends string,
Value extends string,
ValueT,
PresetT,
DefaultT,
CoerceT,
Mandatory extends boolean,
ChoicesT,
> = InferOptionsNegateCombo<
Options,
Flag,
ConvertFlagToName<Flag>,
CoerceValueType<
CoerceT,
[ChoicesT] extends [undefined]
? InferVariadic<Value, ValueT>
: InferVariadic<Value, ChoicesT>
>,
NegatePresetType<Flag, CoercePresetType<CoerceT, PresetT>>,
NegateDefaultType<Flag, DefaultT>,
IsAlwaysDefined<DefaultT, Mandatory>
>;
type InferOptionsFlag<
Options,
Flags extends string,
Value extends string,
ValueT,
PresetT,
DefaultT,
CoerceT,
Mandatory extends boolean,
ChoicesT,
> = InferOptionTypes<
Options,
FlagsToFlag<Trim<Flags>>,
Trim<Value>,
ValueT,
PresetT,
DefaultT,
CoerceT,
Mandatory,
ChoicesT
>;
// Split up Usage into Flags and Value
type InferOptions<
Options,
Usage extends string,
DefaultT,
CoerceT,
Mandatory extends boolean,
PresetT = undefined,
ChoicesT = undefined,
> = Usage extends `${infer Flags} <${infer Value}>`
? InferOptionsFlag<
Options,
Flags,
Value,
string,
never,
DefaultT,
CoerceT,
Mandatory,
ChoicesT
>
: Usage extends `${infer Flags} [${infer Value}]`
? InferOptionsFlag<
Options,
Flags,
Value,
string,
PresetT,
DefaultT,
CoerceT,
Mandatory,
ChoicesT
>
: InferOptionsFlag<
Options,
Usage,
'',
never,
PresetT,
DefaultT,
CoerceT,
Mandatory,
ChoicesT
>;
export type CommandUnknownOpts = Command<unknown[], OptionValues, OptionValues>;
// ----- full copy of normal commander typings from here down, with extra type inference -----
/* eslint-disable @typescript-eslint/no-explicit-any */
export class CommanderError extends Error {
code: string;
exitCode: number;
message: string;
nestedError?: string;
/**
* Constructs the CommanderError class
* @param exitCode - suggested exit code which could be used with process.exit
* @param code - an id string representing the error
* @param message - human-readable description of the error
* @constructor
*/
constructor(exitCode: number, code: string, message: string);
}
export class InvalidArgumentError extends CommanderError {
/**
* Constructs the InvalidArgumentError class
* @param message - explanation of why argument is invalid
* @constructor
*/
constructor(message: string);
}
export { InvalidArgumentError as InvalidOptionArgumentError }; // deprecated old name
export interface ErrorOptions {
// optional parameter for error()
/** an id string representing the error */
code?: string;
/** suggested exit code which could be used with process.exit */
exitCode?: number;
}
export class Argument<
Usage extends string = '',
DefaultT = undefined,
CoerceT = undefined,
ArgRequired extends boolean | undefined = undefined,
ChoicesT = undefined,
> {
description: string;
required: boolean;
variadic: boolean;
defaultValue?: any;
defaultValueDescription?: string;
argChoices?: string[];
/**
* Initialize a new command argument with the given name and description.
* The default is that the argument is required, and you can explicitly
* indicate this with <> around the name. Put [] around the name for an optional argument.
*/
constructor(arg: Usage, description?: string);
/**
* Return argument name.
*/
name(): string;
/**
* Set the default value, and optionally supply the description to be displayed in the help.
*/
default<const T>(
value: T,
description?: string,
): Argument<Usage, T, CoerceT, ArgRequired, ChoicesT>;
/**
* Set the custom handler for processing CLI command arguments into argument values.
*/
argParser<T>(
fn: (value: string, previous: T) => T,
): Argument<Usage, DefaultT, T, ArgRequired, undefined>; // setting ChoicesT to undefined because argParser overwrites choices
/**
* Only allow argument value to be one of choices.
*/
choices<const T extends readonly string[]>(
values: T,
): Argument<Usage, DefaultT, undefined, ArgRequired, T[number]>; // setting CoerceT to undefined because choices overrides argParser
/**
* Make argument required.
*/
argRequired(): Argument<Usage, DefaultT, CoerceT, true, ChoicesT>;
/**
* Make argument optional.
*/
argOptional(): Argument<Usage, DefaultT, CoerceT, false, ChoicesT>;
}
export class Option<
Usage extends string = '',
PresetT = undefined,
DefaultT = undefined,
CoerceT = undefined,
Mandatory extends boolean = false,
ChoicesT = undefined,
> {
flags: string;
description: string;
required: boolean; // A value must be supplied when the option is specified.
optional: boolean; // A value is optional when the option is specified.
variadic: boolean;
mandatory: boolean; // The option must have a value after parsing, which usually means it must be specified on command line.
short?: string;
long?: string;
negate: boolean;
defaultValue?: any;
defaultValueDescription?: string;
presetArg?: unknown;
envVar?: string;
parseArg?: <T>(value: string, previous: T) => T;
hidden: boolean;
argChoices?: string[];
constructor(flags: Usage, description?: string);
/**
* Set the default value, and optionally supply the description to be displayed in the help.
*/
default<const T>(
value: T,
description?: string,
): Option<Usage, PresetT, T, CoerceT, Mandatory, ChoicesT>;
/**
* Preset to use when option used without option-argument, especially optional but also boolean and negated.
* The custom processing (parseArg) is called.
*
* @example
* ```ts
* new Option('--color').default('GREYSCALE').preset('RGB');
* new Option('--donate [amount]').preset('20').argParser(parseFloat);
* ```
*/
preset<const T>(
arg: T,
): Option<Usage, T, DefaultT, CoerceT, Mandatory, ChoicesT>;
/**
* Add option name(s) that conflict with this option.
* An error will be displayed if conflicting options are found during parsing.
*
* @example
* ```ts
* new Option('--rgb').conflicts('cmyk');
* new Option('--js').conflicts(['ts', 'jsx']);
* ```
*/
conflicts(names: string | string[]): this;
/**
* Specify implied option values for when this option is set and the implied options are not.
*
* The custom processing (parseArg) is not called on the implied values.
*
* @example
* program
* .addOption(new Option('--log', 'write logging information to file'))
* .addOption(new Option('--trace', 'log extra details').implies({ log: 'trace.txt' }));
*/
implies(optionValues: OptionValues): this;
/**
* Set environment variable to check for option value.
*
* An environment variables is only used if when processed the current option value is
* undefined, or the source of the current value is 'default' or 'config' or 'env'.
*/
env(name: string): this;
/**
* Set the custom handler for processing CLI option arguments into option values.
*/
argParser<T>(
fn: (value: string, previous: T) => T,
): Option<Usage, PresetT, DefaultT, T, Mandatory, undefined>; // setting ChoicesT to undefined because argParser overrides choices
/**
* Whether the option is mandatory and must have a value after parsing.
*/
makeOptionMandatory<M extends boolean = true>(
mandatory?: M,
): Option<Usage, PresetT, DefaultT, CoerceT, M, ChoicesT>;
/**
* Hide option in help.
*/
hideHelp(hide?: boolean): this;
/**
* Only allow option value to be one of choices.
*/
choices<const T extends readonly string[]>(
values: T,
): Option<Usage, PresetT, DefaultT, undefined, Mandatory, T[number]>; // setting CoerceT to undefined becuase choices overrides argParser
/**
* Return option name.
*/
name(): string;
/**
* Return option name, in a camelcase format that can be used
* as an object attribute key.
*/
attributeName(): string;
/**
* Return whether a boolean option.
*
* Options are one of boolean, negated, required argument, or optional argument.
*/
isBoolean(): boolean;
}
export class Help {
/** output helpWidth, long lines are wrapped to fit */
helpWidth?: number;
minWidthToWrap: number;
sortSubcommands: boolean;
sortOptions: boolean;
showGlobalOptions: boolean;
constructor();
/*
* prepareContext is called by Commander after applying overrides from `Command.configureHelp()`
* and just before calling `formatHelp()`.
*
* Commander just uses the helpWidth and the others are provided for subclasses.
*/
prepareContext(contextOptions: {
error?: boolean;
helpWidth?: number;
outputHasColors?: boolean;
}): void;
/** Get the command term to show in the list of subcommands. */
subcommandTerm(cmd: CommandUnknownOpts): string;
/** Get the command summary to show in the list of subcommands. */
subcommandDescription(cmd: CommandUnknownOpts): string;
/** Get the option term to show in the list of options. */
optionTerm(option: Option): string;
/** Get the option description to show in the list of options. */
optionDescription(option: Option): string;
/** Get the argument term to show in the list of arguments. */
argumentTerm(argument: Argument): string;
/** Get the argument description to show in the list of arguments. */
argumentDescription(argument: Argument): string;
/** Get the command usage to be displayed at the top of the built-in help. */
commandUsage(cmd: CommandUnknownOpts): string;
/** Get the description for the command. */
commandDescription(cmd: CommandUnknownOpts): string;
/** Get an array of the visible subcommands. Includes a placeholder for the implicit help command, if there is one. */
visibleCommands(cmd: CommandUnknownOpts): CommandUnknownOpts[];
/** Get an array of the visible options. Includes a placeholder for the implicit help option, if there is one. */
visibleOptions(cmd: CommandUnknownOpts): Option[];
/** Get an array of the visible global options. (Not including help.) */
visibleGlobalOptions(cmd: CommandUnknownOpts): Option[];
/** Get an array of the arguments which have descriptions. */
visibleArguments(cmd: CommandUnknownOpts): Argument[];
/** Get the longest command term length. */
longestSubcommandTermLength(cmd: CommandUnknownOpts, helper: Help): number;
/** Get the longest option term length. */
longestOptionTermLength(cmd: CommandUnknownOpts, helper: Help): number;
/** Get the longest global option term length. */
longestGlobalOptionTermLength(cmd: CommandUnknownOpts, helper: Help): number;
/** Get the longest argument term length. */
longestArgumentTermLength(cmd: CommandUnknownOpts, helper: Help): number;
/** Return display width of string, ignoring ANSI escape sequences. Used in padding and wrapping calculations. */
displayWidth(str: string): number;
/** Style the titles. Called with 'Usage:', 'Options:', etc. */
styleTitle(title: string): string;
/** Usage: <str> */
styleUsage(str: string): string;
/** Style for command name in usage string. */
styleCommandText(str: string): string;
styleCommandDescription(str: string): string;
styleOptionDescription(str: string): string;
styleSubcommandDescription(str: string): string;
styleArgumentDescription(str: string): string;
/** Base style used by descriptions. */
styleDescriptionText(str: string): string;
styleOptionTerm(str: string): string;
styleSubcommandTerm(str: string): string;
styleArgumentTerm(str: string): string;
/** Base style used in terms and usage for options. */
styleOptionText(str: string): string;
/** Base style used in terms and usage for subcommands. */
styleSubcommandText(str: string): string;
/** Base style used in terms and usage for arguments. */
styleArgumentText(str: string): string;
/** Calculate the pad width from the maximum term length. */
padWidth(cmd: CommandUnknownOpts, helper: Help): number;
/**
* Wrap a string at whitespace, preserving existing line breaks.
* Wrapping is skipped if the width is less than `minWidthToWrap`.
*/
boxWrap(str: string, width: number): string;
/** Detect manually wrapped and indented strings by checking for line break followed by whitespace. */
preformatted(str: string): boolean;
/**
* Format the "item", which consists of a term and description. Pad the term and wrap the description, indenting the following lines.
*
* So "TTT", 5, "DDD DDDD DD DDD" might be formatted for this.helpWidth=17 like so:
* TTT DDD DDDD
* DD DDD
*/
formatItem(
term: string,
termWidth: number,
description: string,
helper: Help,
): string;
/** Generate the built-in help text. */
formatHelp(cmd: CommandUnknownOpts, helper: Help): string;
}
export type HelpConfiguration = Partial<Help>;
export interface ParseOptions {
from: 'node' | 'electron' | 'user';
}
export interface HelpContext {
// optional parameter for .help() and .outputHelp()
error: boolean;
}
export interface AddHelpTextContext {
// passed to text function used with .addHelpText()
error: boolean;
command: Command;
}
export interface OutputConfiguration {
writeOut?(str: string): void;
writeErr?(str: string): void;
outputError?(str: string, write: (str: string) => void): void;
getOutHelpWidth?(): number;
getErrHelpWidth?(): number;
getOutHasColors?(): boolean;
getErrHasColors?(): boolean;
stripColor?(str: string): string;
}
export type AddHelpTextPosition = 'beforeAll' | 'before' | 'after' | 'afterAll';
export type HookEvent = 'preSubcommand' | 'preAction' | 'postAction';
// The source is a string so author can define their own too.
export type OptionValueSource =
| LiteralUnion<'default' | 'config' | 'env' | 'cli' | 'implied', string>
| undefined;
export type OptionValues = Record<string, unknown>;
export class Command<
Args extends any[] = [],
Opts extends OptionValues = {},
GlobalOpts extends OptionValues = {},
> {
args: string[];
processedArgs: Args;
readonly commands: readonly CommandUnknownOpts[];
readonly options: readonly Option[];
readonly registeredArguments: readonly Argument[];
parent: CommandUnknownOpts | null;
constructor(name?: string);
/**
* Set the program version to `str`.
*
* This method auto-registers the "-V, --version" flag
* which will print the version number when passed.
*
* You can optionally supply the flags and description to override the defaults.
*/
version(str: string, flags?: string, description?: string): this;
/**
* Get the program version.
*/
version(): string | undefined;
/**
* Define a command, implemented using an action handler.
*
* @remarks
* The command description is supplied using `.description`, not as a parameter to `.command`.
*
* @example
* ```ts
* program
* .command('clone <source> [destination]')
* .description('clone a repository into a newly created directory')
* .action((source, destination) => {
* console.log('clone command called');
* });
* ```
*
* @param nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...`
* @param opts - configuration options
* @returns new command
*/
command<Usage extends string>(
nameAndArgs: Usage,
opts?: CommandOptions,
): Command<[...InferCommandArguments<Usage>], {}, Opts & GlobalOpts>;
/**
* Define a command, implemented in a separate executable file.
*
* @remarks
* The command description is supplied as the second parameter to `.command`.
*
* @example
* ```ts
* program
* .command('start <service>', 'start named service')
* .command('stop [service]', 'stop named service, or all if no name supplied');
* ```
*
* @param nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...`
* @param description - description of executable command
* @param opts - configuration options
* @returns `this` command for chaining
*/
command(
nameAndArgs: string,
description: string,
opts?: ExecutableCommandOptions,
): this;
/**
* Factory routine to create a new unattached command.
*
* See .command() for creating an attached subcommand, which uses this routine to
* create the command. You can override createCommand to customise subcommands.
*/
createCommand(name?: string): Command;
/**
* Add a prepared subcommand.
*
* See .command() for creating an attached subcommand which inherits settings from its parent.
*
* @returns `this` command for chaining
*/
addCommand(cmd: CommandUnknownOpts, opts?: CommandOptions): this;
/**
* Factory routine to create a new unattached argument.
*
* See .argument() for creating an attached argument, which uses this routine to
* create the argument. You can override createArgument to return a custom argument.
*/
createArgument<Usage extends string>(
name: Usage,
description?: string,
): Argument<Usage>;
/**
* Define argument syntax for command.
*
* The default is that the argument is required, and you can explicitly
* indicate this with <> around the name. Put [] around the name for an optional argument.
*
* @example
* ```
* program.argument('<input-file>');
* program.argument('[output-file]');
* ```
*
* @returns `this` command for chaining
*/
argument<S extends string, T>(
flags: S,
description: string,
fn: (value: string, previous: T) => T,
): Command<[...Args, InferArgument<S, undefined, T>], Opts, GlobalOpts>;
argument<S extends string, T>(
flags: S,
description: string,
fn: (value: string, previous: T) => T,
defaultValue: T,
): Command<[...Args, InferArgument<S, T, T>], Opts, GlobalOpts>;
argument<S extends string>(
usage: S,
description?: string,
): Command<[...Args, InferArgument<S, undefined>], Opts, GlobalOpts>;
argument<S extends string, DefaultT>(
usage: S,
description: string,
defaultValue: DefaultT,
): Command<[...Args, InferArgument<S, DefaultT>], Opts, GlobalOpts>;
/**
* Define argument syntax for command, adding a prepared argument.
*
* @returns `this` command for chaining
*/
addArgument<
Usage extends string,
DefaultT,
CoerceT,
ArgRequired extends boolean | undefined,
ChoicesT,
>(
arg: Argument<Usage, DefaultT, CoerceT, ArgRequired, ChoicesT>,
): Command<
[...Args, InferArgument<Usage, DefaultT, CoerceT, ArgRequired, ChoicesT>],
Opts,
GlobalOpts
>;
/**
* Define argument syntax for command, adding multiple at once (without descriptions).
*
* See also .argument().
*
* @example
* ```
* program.arguments('<cmd> [env]');
* ```
*
* @returns `this` command for chaining
*/
arguments<Names extends string>(
args: Names,
): Command<[...Args, ...InferArguments<Names>], Opts, GlobalOpts>;
/**
* Customise or override default help command. By default a help command is automatically added if your command has subcommands.
*
* @example
* ```ts
* program.helpCommand('help [cmd]');
* program.helpCommand('help [cmd]', 'show help');
* program.helpCommand(false); // suppress default help command
* program.helpCommand(true); // add help command even if no subcommands
* ```
*/
helpCommand(nameAndArgs: string, description?: string): this;
helpCommand(enable: boolean): this;
/**
* Add prepared custom help command.
*/
addHelpCommand(cmd: Command): this;
/** @deprecated since v12, instead use helpCommand */
addHelpCommand(nameAndArgs: string, description?: string): this;
/** @deprecated since v12, instead use helpCommand */
addHelpCommand(enable?: boolean): this;
/**
* Add hook for life cycle event.
*/
hook(
event: HookEvent,
listener: (
thisCommand: this,
actionCommand: CommandUnknownOpts,
) => void | Promise<void>,
): this;
/**
* Register callback to use as replacement for calling process.exit.
*/
exitOverride(callback?: (err: CommanderError) => never | void): this;
/**
* Display error message and exit (or call exitOverride).
*/
error(message: string, errorOptions?: ErrorOptions): never;
/**
* You can customise the help with a subclass of Help by overriding createHelp,
* or by overriding Help properties using configureHelp().
*/
createHelp(): Help;
/**
* You can customise the help by overriding Help properties using configureHelp(),
* or with a subclass of Help by overriding createHelp().
*/
configureHelp(configuration: HelpConfiguration): this;
/** Get configuration */
configureHelp(): HelpConfiguration;
/**
* The default output goes to stdout and stderr. You can customise this for special
* applications. You can also customise the display of errors by overriding outputError.
*
* The configuration properties are all functions:
* ```
* // functions to change where being written, stdout and stderr
* writeOut(str)
* writeErr(str)
* // matching functions to specify width for wrapping help
* getOutHelpWidth()
* getErrHelpWidth()
* // functions based on what is being written out
* outputError(str, write) // used for displaying errors, and not used for displaying help
* ```
*/
configureOutput(configuration: OutputConfiguration): this;
/** Get configuration */
configureOutput(): OutputConfiguration;
/**
* Copy settings that are useful to have in common across root command and subcommands.
*
* (Used internally when adding a command using `.command()` so subcommands inherit parent settings.)
*/
copyInheritedSettings(sourceCommand: CommandUnknownOpts): this;
/**
* Display the help or a custom message after an error occurs.
*/
showHelpAfterError(displayHelp?: boolean | string): this;
/**
* Display suggestion of similar commands for unknown commands, or options for unknown options.
*/
showSuggestionAfterError(displaySuggestion?: boolean): this;
/**
* Register callback `fn` for the command.
*
* @example
* ```
* program
* .command('serve')
* .description('start service')
* .action(function() {
* // do work here
* });
* ```
*
* @returns `this` command for chaining
*/
action(
fn: (this: this, ...args: [...Args, Opts, this]) => void | Promise<void>,
): this;
/**
* Define option with `flags`, `description`, and optional argument parsing function or `defaultValue` or both.
*
* The `flags` string contains the short and/or long flags, separated by comma, a pipe or space. A required
* option-argument is indicated by `<>` and an optional option-argument by `[]`.
*
* See the README for more details, and see also addOption() and requiredOption().
*
* @example
*
* ```js
* program
* .option('-p, --pepper', 'add pepper')
* .option('-p, --pizza-type <TYPE>', 'type of pizza') // required option-argument
* .option('-c, --cheese [CHEESE]', 'add extra cheese', 'mozzarella') // optional option-argument with default
* .option('-t, --tip <VALUE>', 'add tip to purchase cost', parseFloat) // custom parse function
* ```