brady-cli 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,2873 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+ var __create = Object.create;
4
+ var __defProp = Object.defineProperty;
5
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
+ var __getOwnPropNames = Object.getOwnPropertyNames;
7
+ var __getProtoOf = Object.getPrototypeOf;
8
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
9
+ var __commonJS = (cb, mod) => function __require() {
10
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+
29
+ // node_modules/commander/lib/error.js
30
+ var require_error = __commonJS({
31
+ "node_modules/commander/lib/error.js"(exports) {
32
+ var CommanderError2 = class extends Error {
33
+ /**
34
+ * Constructs the CommanderError class
35
+ * @param {number} exitCode suggested exit code which could be used with process.exit
36
+ * @param {string} code an id string representing the error
37
+ * @param {string} message human-readable description of the error
38
+ * @constructor
39
+ */
40
+ constructor(exitCode, code, message) {
41
+ super(message);
42
+ Error.captureStackTrace(this, this.constructor);
43
+ this.name = this.constructor.name;
44
+ this.code = code;
45
+ this.exitCode = exitCode;
46
+ this.nestedError = void 0;
47
+ }
48
+ };
49
+ var InvalidArgumentError2 = class extends CommanderError2 {
50
+ /**
51
+ * Constructs the InvalidArgumentError class
52
+ * @param {string} [message] explanation of why argument is invalid
53
+ * @constructor
54
+ */
55
+ constructor(message) {
56
+ super(1, "commander.invalidArgument", message);
57
+ Error.captureStackTrace(this, this.constructor);
58
+ this.name = this.constructor.name;
59
+ }
60
+ };
61
+ exports.CommanderError = CommanderError2;
62
+ exports.InvalidArgumentError = InvalidArgumentError2;
63
+ }
64
+ });
65
+
66
+ // node_modules/commander/lib/argument.js
67
+ var require_argument = __commonJS({
68
+ "node_modules/commander/lib/argument.js"(exports) {
69
+ var { InvalidArgumentError: InvalidArgumentError2 } = require_error();
70
+ var Argument2 = class {
71
+ /**
72
+ * Initialize a new command argument with the given name and description.
73
+ * The default is that the argument is required, and you can explicitly
74
+ * indicate this with <> around the name. Put [] around the name for an optional argument.
75
+ *
76
+ * @param {string} name
77
+ * @param {string} [description]
78
+ */
79
+ constructor(name, description) {
80
+ this.description = description || "";
81
+ this.variadic = false;
82
+ this.parseArg = void 0;
83
+ this.defaultValue = void 0;
84
+ this.defaultValueDescription = void 0;
85
+ this.argChoices = void 0;
86
+ switch (name[0]) {
87
+ case "<":
88
+ this.required = true;
89
+ this._name = name.slice(1, -1);
90
+ break;
91
+ case "[":
92
+ this.required = false;
93
+ this._name = name.slice(1, -1);
94
+ break;
95
+ default:
96
+ this.required = true;
97
+ this._name = name;
98
+ break;
99
+ }
100
+ if (this._name.length > 3 && this._name.slice(-3) === "...") {
101
+ this.variadic = true;
102
+ this._name = this._name.slice(0, -3);
103
+ }
104
+ }
105
+ /**
106
+ * Return argument name.
107
+ *
108
+ * @return {string}
109
+ */
110
+ name() {
111
+ return this._name;
112
+ }
113
+ /**
114
+ * @api private
115
+ */
116
+ _concatValue(value, previous) {
117
+ if (previous === this.defaultValue || !Array.isArray(previous)) {
118
+ return [value];
119
+ }
120
+ return previous.concat(value);
121
+ }
122
+ /**
123
+ * Set the default value, and optionally supply the description to be displayed in the help.
124
+ *
125
+ * @param {any} value
126
+ * @param {string} [description]
127
+ * @return {Argument}
128
+ */
129
+ default(value, description) {
130
+ this.defaultValue = value;
131
+ this.defaultValueDescription = description;
132
+ return this;
133
+ }
134
+ /**
135
+ * Set the custom handler for processing CLI command arguments into argument values.
136
+ *
137
+ * @param {Function} [fn]
138
+ * @return {Argument}
139
+ */
140
+ argParser(fn) {
141
+ this.parseArg = fn;
142
+ return this;
143
+ }
144
+ /**
145
+ * Only allow argument value to be one of choices.
146
+ *
147
+ * @param {string[]} values
148
+ * @return {Argument}
149
+ */
150
+ choices(values) {
151
+ this.argChoices = values.slice();
152
+ this.parseArg = (arg, previous) => {
153
+ if (!this.argChoices.includes(arg)) {
154
+ throw new InvalidArgumentError2(`Allowed choices are ${this.argChoices.join(", ")}.`);
155
+ }
156
+ if (this.variadic) {
157
+ return this._concatValue(arg, previous);
158
+ }
159
+ return arg;
160
+ };
161
+ return this;
162
+ }
163
+ /**
164
+ * Make argument required.
165
+ */
166
+ argRequired() {
167
+ this.required = true;
168
+ return this;
169
+ }
170
+ /**
171
+ * Make argument optional.
172
+ */
173
+ argOptional() {
174
+ this.required = false;
175
+ return this;
176
+ }
177
+ };
178
+ function humanReadableArgName(arg) {
179
+ const nameOutput = arg.name() + (arg.variadic === true ? "..." : "");
180
+ return arg.required ? "<" + nameOutput + ">" : "[" + nameOutput + "]";
181
+ }
182
+ exports.Argument = Argument2;
183
+ exports.humanReadableArgName = humanReadableArgName;
184
+ }
185
+ });
186
+
187
+ // node_modules/commander/lib/help.js
188
+ var require_help = __commonJS({
189
+ "node_modules/commander/lib/help.js"(exports) {
190
+ var { humanReadableArgName } = require_argument();
191
+ var Help2 = class {
192
+ constructor() {
193
+ this.helpWidth = void 0;
194
+ this.sortSubcommands = false;
195
+ this.sortOptions = false;
196
+ this.showGlobalOptions = false;
197
+ }
198
+ /**
199
+ * Get an array of the visible subcommands. Includes a placeholder for the implicit help command, if there is one.
200
+ *
201
+ * @param {Command} cmd
202
+ * @returns {Command[]}
203
+ */
204
+ visibleCommands(cmd) {
205
+ const visibleCommands = cmd.commands.filter((cmd2) => !cmd2._hidden);
206
+ if (cmd._hasImplicitHelpCommand()) {
207
+ const [, helpName, helpArgs] = cmd._helpCommandnameAndArgs.match(/([^ ]+) *(.*)/);
208
+ const helpCommand = cmd.createCommand(helpName).helpOption(false);
209
+ helpCommand.description(cmd._helpCommandDescription);
210
+ if (helpArgs)
211
+ helpCommand.arguments(helpArgs);
212
+ visibleCommands.push(helpCommand);
213
+ }
214
+ if (this.sortSubcommands) {
215
+ visibleCommands.sort((a, b) => {
216
+ return a.name().localeCompare(b.name());
217
+ });
218
+ }
219
+ return visibleCommands;
220
+ }
221
+ /**
222
+ * Compare options for sort.
223
+ *
224
+ * @param {Option} a
225
+ * @param {Option} b
226
+ * @returns number
227
+ */
228
+ compareOptions(a, b) {
229
+ const getSortKey = (option) => {
230
+ return option.short ? option.short.replace(/^-/, "") : option.long.replace(/^--/, "");
231
+ };
232
+ return getSortKey(a).localeCompare(getSortKey(b));
233
+ }
234
+ /**
235
+ * Get an array of the visible options. Includes a placeholder for the implicit help option, if there is one.
236
+ *
237
+ * @param {Command} cmd
238
+ * @returns {Option[]}
239
+ */
240
+ visibleOptions(cmd) {
241
+ const visibleOptions = cmd.options.filter((option) => !option.hidden);
242
+ const showShortHelpFlag = cmd._hasHelpOption && cmd._helpShortFlag && !cmd._findOption(cmd._helpShortFlag);
243
+ const showLongHelpFlag = cmd._hasHelpOption && !cmd._findOption(cmd._helpLongFlag);
244
+ if (showShortHelpFlag || showLongHelpFlag) {
245
+ let helpOption;
246
+ if (!showShortHelpFlag) {
247
+ helpOption = cmd.createOption(cmd._helpLongFlag, cmd._helpDescription);
248
+ } else if (!showLongHelpFlag) {
249
+ helpOption = cmd.createOption(cmd._helpShortFlag, cmd._helpDescription);
250
+ } else {
251
+ helpOption = cmd.createOption(cmd._helpFlags, cmd._helpDescription);
252
+ }
253
+ visibleOptions.push(helpOption);
254
+ }
255
+ if (this.sortOptions) {
256
+ visibleOptions.sort(this.compareOptions);
257
+ }
258
+ return visibleOptions;
259
+ }
260
+ /**
261
+ * Get an array of the visible global options. (Not including help.)
262
+ *
263
+ * @param {Command} cmd
264
+ * @returns {Option[]}
265
+ */
266
+ visibleGlobalOptions(cmd) {
267
+ if (!this.showGlobalOptions)
268
+ return [];
269
+ const globalOptions = [];
270
+ for (let parentCmd = cmd.parent; parentCmd; parentCmd = parentCmd.parent) {
271
+ const visibleOptions = parentCmd.options.filter((option) => !option.hidden);
272
+ globalOptions.push(...visibleOptions);
273
+ }
274
+ if (this.sortOptions) {
275
+ globalOptions.sort(this.compareOptions);
276
+ }
277
+ return globalOptions;
278
+ }
279
+ /**
280
+ * Get an array of the arguments if any have a description.
281
+ *
282
+ * @param {Command} cmd
283
+ * @returns {Argument[]}
284
+ */
285
+ visibleArguments(cmd) {
286
+ if (cmd._argsDescription) {
287
+ cmd._args.forEach((argument) => {
288
+ argument.description = argument.description || cmd._argsDescription[argument.name()] || "";
289
+ });
290
+ }
291
+ if (cmd._args.find((argument) => argument.description)) {
292
+ return cmd._args;
293
+ }
294
+ return [];
295
+ }
296
+ /**
297
+ * Get the command term to show in the list of subcommands.
298
+ *
299
+ * @param {Command} cmd
300
+ * @returns {string}
301
+ */
302
+ subcommandTerm(cmd) {
303
+ const args = cmd._args.map((arg) => humanReadableArgName(arg)).join(" ");
304
+ return cmd._name + (cmd._aliases[0] ? "|" + cmd._aliases[0] : "") + (cmd.options.length ? " [options]" : "") + // simplistic check for non-help option
305
+ (args ? " " + args : "");
306
+ }
307
+ /**
308
+ * Get the option term to show in the list of options.
309
+ *
310
+ * @param {Option} option
311
+ * @returns {string}
312
+ */
313
+ optionTerm(option) {
314
+ return option.flags;
315
+ }
316
+ /**
317
+ * Get the argument term to show in the list of arguments.
318
+ *
319
+ * @param {Argument} argument
320
+ * @returns {string}
321
+ */
322
+ argumentTerm(argument) {
323
+ return argument.name();
324
+ }
325
+ /**
326
+ * Get the longest command term length.
327
+ *
328
+ * @param {Command} cmd
329
+ * @param {Help} helper
330
+ * @returns {number}
331
+ */
332
+ longestSubcommandTermLength(cmd, helper) {
333
+ return helper.visibleCommands(cmd).reduce((max, command) => {
334
+ return Math.max(max, helper.subcommandTerm(command).length);
335
+ }, 0);
336
+ }
337
+ /**
338
+ * Get the longest option term length.
339
+ *
340
+ * @param {Command} cmd
341
+ * @param {Help} helper
342
+ * @returns {number}
343
+ */
344
+ longestOptionTermLength(cmd, helper) {
345
+ return helper.visibleOptions(cmd).reduce((max, option) => {
346
+ return Math.max(max, helper.optionTerm(option).length);
347
+ }, 0);
348
+ }
349
+ /**
350
+ * Get the longest global option term length.
351
+ *
352
+ * @param {Command} cmd
353
+ * @param {Help} helper
354
+ * @returns {number}
355
+ */
356
+ longestGlobalOptionTermLength(cmd, helper) {
357
+ return helper.visibleGlobalOptions(cmd).reduce((max, option) => {
358
+ return Math.max(max, helper.optionTerm(option).length);
359
+ }, 0);
360
+ }
361
+ /**
362
+ * Get the longest argument term length.
363
+ *
364
+ * @param {Command} cmd
365
+ * @param {Help} helper
366
+ * @returns {number}
367
+ */
368
+ longestArgumentTermLength(cmd, helper) {
369
+ return helper.visibleArguments(cmd).reduce((max, argument) => {
370
+ return Math.max(max, helper.argumentTerm(argument).length);
371
+ }, 0);
372
+ }
373
+ /**
374
+ * Get the command usage to be displayed at the top of the built-in help.
375
+ *
376
+ * @param {Command} cmd
377
+ * @returns {string}
378
+ */
379
+ commandUsage(cmd) {
380
+ let cmdName = cmd._name;
381
+ if (cmd._aliases[0]) {
382
+ cmdName = cmdName + "|" + cmd._aliases[0];
383
+ }
384
+ let parentCmdNames = "";
385
+ for (let parentCmd = cmd.parent; parentCmd; parentCmd = parentCmd.parent) {
386
+ parentCmdNames = parentCmd.name() + " " + parentCmdNames;
387
+ }
388
+ return parentCmdNames + cmdName + " " + cmd.usage();
389
+ }
390
+ /**
391
+ * Get the description for the command.
392
+ *
393
+ * @param {Command} cmd
394
+ * @returns {string}
395
+ */
396
+ commandDescription(cmd) {
397
+ return cmd.description();
398
+ }
399
+ /**
400
+ * Get the subcommand summary to show in the list of subcommands.
401
+ * (Fallback to description for backwards compatibility.)
402
+ *
403
+ * @param {Command} cmd
404
+ * @returns {string}
405
+ */
406
+ subcommandDescription(cmd) {
407
+ return cmd.summary() || cmd.description();
408
+ }
409
+ /**
410
+ * Get the option description to show in the list of options.
411
+ *
412
+ * @param {Option} option
413
+ * @return {string}
414
+ */
415
+ optionDescription(option) {
416
+ const extraInfo = [];
417
+ if (option.argChoices) {
418
+ extraInfo.push(
419
+ // use stringify to match the display of the default value
420
+ `choices: ${option.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`
421
+ );
422
+ }
423
+ if (option.defaultValue !== void 0) {
424
+ const showDefault = option.required || option.optional || option.isBoolean() && typeof option.defaultValue === "boolean";
425
+ if (showDefault) {
426
+ extraInfo.push(`default: ${option.defaultValueDescription || JSON.stringify(option.defaultValue)}`);
427
+ }
428
+ }
429
+ if (option.presetArg !== void 0 && option.optional) {
430
+ extraInfo.push(`preset: ${JSON.stringify(option.presetArg)}`);
431
+ }
432
+ if (option.envVar !== void 0) {
433
+ extraInfo.push(`env: ${option.envVar}`);
434
+ }
435
+ if (extraInfo.length > 0) {
436
+ return `${option.description} (${extraInfo.join(", ")})`;
437
+ }
438
+ return option.description;
439
+ }
440
+ /**
441
+ * Get the argument description to show in the list of arguments.
442
+ *
443
+ * @param {Argument} argument
444
+ * @return {string}
445
+ */
446
+ argumentDescription(argument) {
447
+ const extraInfo = [];
448
+ if (argument.argChoices) {
449
+ extraInfo.push(
450
+ // use stringify to match the display of the default value
451
+ `choices: ${argument.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`
452
+ );
453
+ }
454
+ if (argument.defaultValue !== void 0) {
455
+ extraInfo.push(`default: ${argument.defaultValueDescription || JSON.stringify(argument.defaultValue)}`);
456
+ }
457
+ if (extraInfo.length > 0) {
458
+ const extraDescripton = `(${extraInfo.join(", ")})`;
459
+ if (argument.description) {
460
+ return `${argument.description} ${extraDescripton}`;
461
+ }
462
+ return extraDescripton;
463
+ }
464
+ return argument.description;
465
+ }
466
+ /**
467
+ * Generate the built-in help text.
468
+ *
469
+ * @param {Command} cmd
470
+ * @param {Help} helper
471
+ * @returns {string}
472
+ */
473
+ formatHelp(cmd, helper) {
474
+ const termWidth = helper.padWidth(cmd, helper);
475
+ const helpWidth = helper.helpWidth || 80;
476
+ const itemIndentWidth = 2;
477
+ const itemSeparatorWidth = 2;
478
+ function formatItem(term, description) {
479
+ if (description) {
480
+ const fullText = `${term.padEnd(termWidth + itemSeparatorWidth)}${description}`;
481
+ return helper.wrap(fullText, helpWidth - itemIndentWidth, termWidth + itemSeparatorWidth);
482
+ }
483
+ return term;
484
+ }
485
+ function formatList(textArray) {
486
+ return textArray.join("\n").replace(/^/gm, " ".repeat(itemIndentWidth));
487
+ }
488
+ let output = [`Usage: ${helper.commandUsage(cmd)}`, ""];
489
+ const commandDescription = helper.commandDescription(cmd);
490
+ if (commandDescription.length > 0) {
491
+ output = output.concat([helper.wrap(commandDescription, helpWidth, 0), ""]);
492
+ }
493
+ const argumentList = helper.visibleArguments(cmd).map((argument) => {
494
+ return formatItem(helper.argumentTerm(argument), helper.argumentDescription(argument));
495
+ });
496
+ if (argumentList.length > 0) {
497
+ output = output.concat(["Arguments:", formatList(argumentList), ""]);
498
+ }
499
+ const optionList = helper.visibleOptions(cmd).map((option) => {
500
+ return formatItem(helper.optionTerm(option), helper.optionDescription(option));
501
+ });
502
+ if (optionList.length > 0) {
503
+ output = output.concat(["Options:", formatList(optionList), ""]);
504
+ }
505
+ if (this.showGlobalOptions) {
506
+ const globalOptionList = helper.visibleGlobalOptions(cmd).map((option) => {
507
+ return formatItem(helper.optionTerm(option), helper.optionDescription(option));
508
+ });
509
+ if (globalOptionList.length > 0) {
510
+ output = output.concat(["Global Options:", formatList(globalOptionList), ""]);
511
+ }
512
+ }
513
+ const commandList = helper.visibleCommands(cmd).map((cmd2) => {
514
+ return formatItem(helper.subcommandTerm(cmd2), helper.subcommandDescription(cmd2));
515
+ });
516
+ if (commandList.length > 0) {
517
+ output = output.concat(["Commands:", formatList(commandList), ""]);
518
+ }
519
+ return output.join("\n");
520
+ }
521
+ /**
522
+ * Calculate the pad width from the maximum term length.
523
+ *
524
+ * @param {Command} cmd
525
+ * @param {Help} helper
526
+ * @returns {number}
527
+ */
528
+ padWidth(cmd, helper) {
529
+ return Math.max(
530
+ helper.longestOptionTermLength(cmd, helper),
531
+ helper.longestGlobalOptionTermLength(cmd, helper),
532
+ helper.longestSubcommandTermLength(cmd, helper),
533
+ helper.longestArgumentTermLength(cmd, helper)
534
+ );
535
+ }
536
+ /**
537
+ * Wrap the given string to width characters per line, with lines after the first indented.
538
+ * Do not wrap if insufficient room for wrapping (minColumnWidth), or string is manually formatted.
539
+ *
540
+ * @param {string} str
541
+ * @param {number} width
542
+ * @param {number} indent
543
+ * @param {number} [minColumnWidth=40]
544
+ * @return {string}
545
+ *
546
+ */
547
+ wrap(str, width, indent, minColumnWidth = 40) {
548
+ const indents = " \\f\\t\\v\xA0\u1680\u2000-\u200A\u202F\u205F\u3000\uFEFF";
549
+ const manualIndent = new RegExp(`[\\n][${indents}]+`);
550
+ if (str.match(manualIndent))
551
+ return str;
552
+ const columnWidth = width - indent;
553
+ if (columnWidth < minColumnWidth)
554
+ return str;
555
+ const leadingStr = str.slice(0, indent);
556
+ const columnText = str.slice(indent).replace("\r\n", "\n");
557
+ const indentString = " ".repeat(indent);
558
+ const zeroWidthSpace = "\u200B";
559
+ const breaks = `\\s${zeroWidthSpace}`;
560
+ const regex = new RegExp(`
561
+ |.{1,${columnWidth - 1}}([${breaks}]|$)|[^${breaks}]+?([${breaks}]|$)`, "g");
562
+ const lines = columnText.match(regex) || [];
563
+ return leadingStr + lines.map((line, i) => {
564
+ if (line === "\n")
565
+ return "";
566
+ return (i > 0 ? indentString : "") + line.trimEnd();
567
+ }).join("\n");
568
+ }
569
+ };
570
+ exports.Help = Help2;
571
+ }
572
+ });
573
+
574
+ // node_modules/commander/lib/option.js
575
+ var require_option = __commonJS({
576
+ "node_modules/commander/lib/option.js"(exports) {
577
+ var { InvalidArgumentError: InvalidArgumentError2 } = require_error();
578
+ var Option2 = class {
579
+ /**
580
+ * Initialize a new `Option` with the given `flags` and `description`.
581
+ *
582
+ * @param {string} flags
583
+ * @param {string} [description]
584
+ */
585
+ constructor(flags, description) {
586
+ this.flags = flags;
587
+ this.description = description || "";
588
+ this.required = flags.includes("<");
589
+ this.optional = flags.includes("[");
590
+ this.variadic = /\w\.\.\.[>\]]$/.test(flags);
591
+ this.mandatory = false;
592
+ const optionFlags = splitOptionFlags(flags);
593
+ this.short = optionFlags.shortFlag;
594
+ this.long = optionFlags.longFlag;
595
+ this.negate = false;
596
+ if (this.long) {
597
+ this.negate = this.long.startsWith("--no-");
598
+ }
599
+ this.defaultValue = void 0;
600
+ this.defaultValueDescription = void 0;
601
+ this.presetArg = void 0;
602
+ this.envVar = void 0;
603
+ this.parseArg = void 0;
604
+ this.hidden = false;
605
+ this.argChoices = void 0;
606
+ this.conflictsWith = [];
607
+ this.implied = void 0;
608
+ }
609
+ /**
610
+ * Set the default value, and optionally supply the description to be displayed in the help.
611
+ *
612
+ * @param {any} value
613
+ * @param {string} [description]
614
+ * @return {Option}
615
+ */
616
+ default(value, description) {
617
+ this.defaultValue = value;
618
+ this.defaultValueDescription = description;
619
+ return this;
620
+ }
621
+ /**
622
+ * Preset to use when option used without option-argument, especially optional but also boolean and negated.
623
+ * The custom processing (parseArg) is called.
624
+ *
625
+ * @example
626
+ * new Option('--color').default('GREYSCALE').preset('RGB');
627
+ * new Option('--donate [amount]').preset('20').argParser(parseFloat);
628
+ *
629
+ * @param {any} arg
630
+ * @return {Option}
631
+ */
632
+ preset(arg) {
633
+ this.presetArg = arg;
634
+ return this;
635
+ }
636
+ /**
637
+ * Add option name(s) that conflict with this option.
638
+ * An error will be displayed if conflicting options are found during parsing.
639
+ *
640
+ * @example
641
+ * new Option('--rgb').conflicts('cmyk');
642
+ * new Option('--js').conflicts(['ts', 'jsx']);
643
+ *
644
+ * @param {string | string[]} names
645
+ * @return {Option}
646
+ */
647
+ conflicts(names) {
648
+ this.conflictsWith = this.conflictsWith.concat(names);
649
+ return this;
650
+ }
651
+ /**
652
+ * Specify implied option values for when this option is set and the implied options are not.
653
+ *
654
+ * The custom processing (parseArg) is not called on the implied values.
655
+ *
656
+ * @example
657
+ * program
658
+ * .addOption(new Option('--log', 'write logging information to file'))
659
+ * .addOption(new Option('--trace', 'log extra details').implies({ log: 'trace.txt' }));
660
+ *
661
+ * @param {Object} impliedOptionValues
662
+ * @return {Option}
663
+ */
664
+ implies(impliedOptionValues) {
665
+ let newImplied = impliedOptionValues;
666
+ if (typeof impliedOptionValues === "string") {
667
+ newImplied = { [impliedOptionValues]: true };
668
+ }
669
+ this.implied = Object.assign(this.implied || {}, newImplied);
670
+ return this;
671
+ }
672
+ /**
673
+ * Set environment variable to check for option value.
674
+ *
675
+ * An environment variable is only used if when processed the current option value is
676
+ * undefined, or the source of the current value is 'default' or 'config' or 'env'.
677
+ *
678
+ * @param {string} name
679
+ * @return {Option}
680
+ */
681
+ env(name) {
682
+ this.envVar = name;
683
+ return this;
684
+ }
685
+ /**
686
+ * Set the custom handler for processing CLI option arguments into option values.
687
+ *
688
+ * @param {Function} [fn]
689
+ * @return {Option}
690
+ */
691
+ argParser(fn) {
692
+ this.parseArg = fn;
693
+ return this;
694
+ }
695
+ /**
696
+ * Whether the option is mandatory and must have a value after parsing.
697
+ *
698
+ * @param {boolean} [mandatory=true]
699
+ * @return {Option}
700
+ */
701
+ makeOptionMandatory(mandatory = true) {
702
+ this.mandatory = !!mandatory;
703
+ return this;
704
+ }
705
+ /**
706
+ * Hide option in help.
707
+ *
708
+ * @param {boolean} [hide=true]
709
+ * @return {Option}
710
+ */
711
+ hideHelp(hide = true) {
712
+ this.hidden = !!hide;
713
+ return this;
714
+ }
715
+ /**
716
+ * @api private
717
+ */
718
+ _concatValue(value, previous) {
719
+ if (previous === this.defaultValue || !Array.isArray(previous)) {
720
+ return [value];
721
+ }
722
+ return previous.concat(value);
723
+ }
724
+ /**
725
+ * Only allow option value to be one of choices.
726
+ *
727
+ * @param {string[]} values
728
+ * @return {Option}
729
+ */
730
+ choices(values) {
731
+ this.argChoices = values.slice();
732
+ this.parseArg = (arg, previous) => {
733
+ if (!this.argChoices.includes(arg)) {
734
+ throw new InvalidArgumentError2(`Allowed choices are ${this.argChoices.join(", ")}.`);
735
+ }
736
+ if (this.variadic) {
737
+ return this._concatValue(arg, previous);
738
+ }
739
+ return arg;
740
+ };
741
+ return this;
742
+ }
743
+ /**
744
+ * Return option name.
745
+ *
746
+ * @return {string}
747
+ */
748
+ name() {
749
+ if (this.long) {
750
+ return this.long.replace(/^--/, "");
751
+ }
752
+ return this.short.replace(/^-/, "");
753
+ }
754
+ /**
755
+ * Return option name, in a camelcase format that can be used
756
+ * as a object attribute key.
757
+ *
758
+ * @return {string}
759
+ * @api private
760
+ */
761
+ attributeName() {
762
+ return camelcase(this.name().replace(/^no-/, ""));
763
+ }
764
+ /**
765
+ * Check if `arg` matches the short or long flag.
766
+ *
767
+ * @param {string} arg
768
+ * @return {boolean}
769
+ * @api private
770
+ */
771
+ is(arg) {
772
+ return this.short === arg || this.long === arg;
773
+ }
774
+ /**
775
+ * Return whether a boolean option.
776
+ *
777
+ * Options are one of boolean, negated, required argument, or optional argument.
778
+ *
779
+ * @return {boolean}
780
+ * @api private
781
+ */
782
+ isBoolean() {
783
+ return !this.required && !this.optional && !this.negate;
784
+ }
785
+ };
786
+ var DualOptions = class {
787
+ /**
788
+ * @param {Option[]} options
789
+ */
790
+ constructor(options) {
791
+ this.positiveOptions = /* @__PURE__ */ new Map();
792
+ this.negativeOptions = /* @__PURE__ */ new Map();
793
+ this.dualOptions = /* @__PURE__ */ new Set();
794
+ options.forEach((option) => {
795
+ if (option.negate) {
796
+ this.negativeOptions.set(option.attributeName(), option);
797
+ } else {
798
+ this.positiveOptions.set(option.attributeName(), option);
799
+ }
800
+ });
801
+ this.negativeOptions.forEach((value, key) => {
802
+ if (this.positiveOptions.has(key)) {
803
+ this.dualOptions.add(key);
804
+ }
805
+ });
806
+ }
807
+ /**
808
+ * Did the value come from the option, and not from possible matching dual option?
809
+ *
810
+ * @param {any} value
811
+ * @param {Option} option
812
+ * @returns {boolean}
813
+ */
814
+ valueFromOption(value, option) {
815
+ const optionKey = option.attributeName();
816
+ if (!this.dualOptions.has(optionKey))
817
+ return true;
818
+ const preset = this.negativeOptions.get(optionKey).presetArg;
819
+ const negativeValue = preset !== void 0 ? preset : false;
820
+ return option.negate === (negativeValue === value);
821
+ }
822
+ };
823
+ function camelcase(str) {
824
+ return str.split("-").reduce((str2, word) => {
825
+ return str2 + word[0].toUpperCase() + word.slice(1);
826
+ });
827
+ }
828
+ function splitOptionFlags(flags) {
829
+ let shortFlag;
830
+ let longFlag;
831
+ const flagParts = flags.split(/[ |,]+/);
832
+ if (flagParts.length > 1 && !/^[[<]/.test(flagParts[1]))
833
+ shortFlag = flagParts.shift();
834
+ longFlag = flagParts.shift();
835
+ if (!shortFlag && /^-[^-]$/.test(longFlag)) {
836
+ shortFlag = longFlag;
837
+ longFlag = void 0;
838
+ }
839
+ return { shortFlag, longFlag };
840
+ }
841
+ exports.Option = Option2;
842
+ exports.splitOptionFlags = splitOptionFlags;
843
+ exports.DualOptions = DualOptions;
844
+ }
845
+ });
846
+
847
+ // node_modules/commander/lib/suggestSimilar.js
848
+ var require_suggestSimilar = __commonJS({
849
+ "node_modules/commander/lib/suggestSimilar.js"(exports) {
850
+ var maxDistance = 3;
851
+ function editDistance(a, b) {
852
+ if (Math.abs(a.length - b.length) > maxDistance)
853
+ return Math.max(a.length, b.length);
854
+ const d = [];
855
+ for (let i = 0; i <= a.length; i++) {
856
+ d[i] = [i];
857
+ }
858
+ for (let j = 0; j <= b.length; j++) {
859
+ d[0][j] = j;
860
+ }
861
+ for (let j = 1; j <= b.length; j++) {
862
+ for (let i = 1; i <= a.length; i++) {
863
+ let cost = 1;
864
+ if (a[i - 1] === b[j - 1]) {
865
+ cost = 0;
866
+ } else {
867
+ cost = 1;
868
+ }
869
+ d[i][j] = Math.min(
870
+ d[i - 1][j] + 1,
871
+ // deletion
872
+ d[i][j - 1] + 1,
873
+ // insertion
874
+ d[i - 1][j - 1] + cost
875
+ // substitution
876
+ );
877
+ if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) {
878
+ d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1);
879
+ }
880
+ }
881
+ }
882
+ return d[a.length][b.length];
883
+ }
884
+ function suggestSimilar(word, candidates) {
885
+ if (!candidates || candidates.length === 0)
886
+ return "";
887
+ candidates = Array.from(new Set(candidates));
888
+ const searchingOptions = word.startsWith("--");
889
+ if (searchingOptions) {
890
+ word = word.slice(2);
891
+ candidates = candidates.map((candidate) => candidate.slice(2));
892
+ }
893
+ let similar = [];
894
+ let bestDistance = maxDistance;
895
+ const minSimilarity = 0.4;
896
+ candidates.forEach((candidate) => {
897
+ if (candidate.length <= 1)
898
+ return;
899
+ const distance = editDistance(word, candidate);
900
+ const length = Math.max(word.length, candidate.length);
901
+ const similarity = (length - distance) / length;
902
+ if (similarity > minSimilarity) {
903
+ if (distance < bestDistance) {
904
+ bestDistance = distance;
905
+ similar = [candidate];
906
+ } else if (distance === bestDistance) {
907
+ similar.push(candidate);
908
+ }
909
+ }
910
+ });
911
+ similar.sort((a, b) => a.localeCompare(b));
912
+ if (searchingOptions) {
913
+ similar = similar.map((candidate) => `--${candidate}`);
914
+ }
915
+ if (similar.length > 1) {
916
+ return `
917
+ (Did you mean one of ${similar.join(", ")}?)`;
918
+ }
919
+ if (similar.length === 1) {
920
+ return `
921
+ (Did you mean ${similar[0]}?)`;
922
+ }
923
+ return "";
924
+ }
925
+ exports.suggestSimilar = suggestSimilar;
926
+ }
927
+ });
928
+
929
+ // node_modules/commander/lib/command.js
930
+ var require_command = __commonJS({
931
+ "node_modules/commander/lib/command.js"(exports) {
932
+ var EventEmitter = require("events").EventEmitter;
933
+ var childProcess = require("child_process");
934
+ var path = require("path");
935
+ var fs = require("fs");
936
+ var process2 = require("process");
937
+ var { Argument: Argument2, humanReadableArgName } = require_argument();
938
+ var { CommanderError: CommanderError2 } = require_error();
939
+ var { Help: Help2 } = require_help();
940
+ var { Option: Option2, splitOptionFlags, DualOptions } = require_option();
941
+ var { suggestSimilar } = require_suggestSimilar();
942
+ var Command2 = class extends EventEmitter {
943
+ /**
944
+ * Initialize a new `Command`.
945
+ *
946
+ * @param {string} [name]
947
+ */
948
+ constructor(name) {
949
+ super();
950
+ this.commands = [];
951
+ this.options = [];
952
+ this.parent = null;
953
+ this._allowUnknownOption = false;
954
+ this._allowExcessArguments = true;
955
+ this._args = [];
956
+ this.args = [];
957
+ this.rawArgs = [];
958
+ this.processedArgs = [];
959
+ this._scriptPath = null;
960
+ this._name = name || "";
961
+ this._optionValues = {};
962
+ this._optionValueSources = {};
963
+ this._storeOptionsAsProperties = false;
964
+ this._actionHandler = null;
965
+ this._executableHandler = false;
966
+ this._executableFile = null;
967
+ this._executableDir = null;
968
+ this._defaultCommandName = null;
969
+ this._exitCallback = null;
970
+ this._aliases = [];
971
+ this._combineFlagAndOptionalValue = true;
972
+ this._description = "";
973
+ this._summary = "";
974
+ this._argsDescription = void 0;
975
+ this._enablePositionalOptions = false;
976
+ this._passThroughOptions = false;
977
+ this._lifeCycleHooks = {};
978
+ this._showHelpAfterError = false;
979
+ this._showSuggestionAfterError = true;
980
+ this._outputConfiguration = {
981
+ writeOut: (str) => process2.stdout.write(str),
982
+ writeErr: (str) => process2.stderr.write(str),
983
+ getOutHelpWidth: () => process2.stdout.isTTY ? process2.stdout.columns : void 0,
984
+ getErrHelpWidth: () => process2.stderr.isTTY ? process2.stderr.columns : void 0,
985
+ outputError: (str, write) => write(str)
986
+ };
987
+ this._hidden = false;
988
+ this._hasHelpOption = true;
989
+ this._helpFlags = "-h, --help";
990
+ this._helpDescription = "display help for command";
991
+ this._helpShortFlag = "-h";
992
+ this._helpLongFlag = "--help";
993
+ this._addImplicitHelpCommand = void 0;
994
+ this._helpCommandName = "help";
995
+ this._helpCommandnameAndArgs = "help [command]";
996
+ this._helpCommandDescription = "display help for command";
997
+ this._helpConfiguration = {};
998
+ }
999
+ /**
1000
+ * Copy settings that are useful to have in common across root command and subcommands.
1001
+ *
1002
+ * (Used internally when adding a command using `.command()` so subcommands inherit parent settings.)
1003
+ *
1004
+ * @param {Command} sourceCommand
1005
+ * @return {Command} `this` command for chaining
1006
+ */
1007
+ copyInheritedSettings(sourceCommand) {
1008
+ this._outputConfiguration = sourceCommand._outputConfiguration;
1009
+ this._hasHelpOption = sourceCommand._hasHelpOption;
1010
+ this._helpFlags = sourceCommand._helpFlags;
1011
+ this._helpDescription = sourceCommand._helpDescription;
1012
+ this._helpShortFlag = sourceCommand._helpShortFlag;
1013
+ this._helpLongFlag = sourceCommand._helpLongFlag;
1014
+ this._helpCommandName = sourceCommand._helpCommandName;
1015
+ this._helpCommandnameAndArgs = sourceCommand._helpCommandnameAndArgs;
1016
+ this._helpCommandDescription = sourceCommand._helpCommandDescription;
1017
+ this._helpConfiguration = sourceCommand._helpConfiguration;
1018
+ this._exitCallback = sourceCommand._exitCallback;
1019
+ this._storeOptionsAsProperties = sourceCommand._storeOptionsAsProperties;
1020
+ this._combineFlagAndOptionalValue = sourceCommand._combineFlagAndOptionalValue;
1021
+ this._allowExcessArguments = sourceCommand._allowExcessArguments;
1022
+ this._enablePositionalOptions = sourceCommand._enablePositionalOptions;
1023
+ this._showHelpAfterError = sourceCommand._showHelpAfterError;
1024
+ this._showSuggestionAfterError = sourceCommand._showSuggestionAfterError;
1025
+ return this;
1026
+ }
1027
+ /**
1028
+ * Define a command.
1029
+ *
1030
+ * There are two styles of command: pay attention to where to put the description.
1031
+ *
1032
+ * @example
1033
+ * // Command implemented using action handler (description is supplied separately to `.command`)
1034
+ * program
1035
+ * .command('clone <source> [destination]')
1036
+ * .description('clone a repository into a newly created directory')
1037
+ * .action((source, destination) => {
1038
+ * console.log('clone command called');
1039
+ * });
1040
+ *
1041
+ * // Command implemented using separate executable file (description is second parameter to `.command`)
1042
+ * program
1043
+ * .command('start <service>', 'start named service')
1044
+ * .command('stop [service]', 'stop named service, or all if no name supplied');
1045
+ *
1046
+ * @param {string} nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...`
1047
+ * @param {Object|string} [actionOptsOrExecDesc] - configuration options (for action), or description (for executable)
1048
+ * @param {Object} [execOpts] - configuration options (for executable)
1049
+ * @return {Command} returns new command for action handler, or `this` for executable command
1050
+ */
1051
+ command(nameAndArgs, actionOptsOrExecDesc, execOpts) {
1052
+ let desc = actionOptsOrExecDesc;
1053
+ let opts = execOpts;
1054
+ if (typeof desc === "object" && desc !== null) {
1055
+ opts = desc;
1056
+ desc = null;
1057
+ }
1058
+ opts = opts || {};
1059
+ const [, name, args] = nameAndArgs.match(/([^ ]+) *(.*)/);
1060
+ const cmd = this.createCommand(name);
1061
+ if (desc) {
1062
+ cmd.description(desc);
1063
+ cmd._executableHandler = true;
1064
+ }
1065
+ if (opts.isDefault)
1066
+ this._defaultCommandName = cmd._name;
1067
+ cmd._hidden = !!(opts.noHelp || opts.hidden);
1068
+ cmd._executableFile = opts.executableFile || null;
1069
+ if (args)
1070
+ cmd.arguments(args);
1071
+ this.commands.push(cmd);
1072
+ cmd.parent = this;
1073
+ cmd.copyInheritedSettings(this);
1074
+ if (desc)
1075
+ return this;
1076
+ return cmd;
1077
+ }
1078
+ /**
1079
+ * Factory routine to create a new unattached command.
1080
+ *
1081
+ * See .command() for creating an attached subcommand, which uses this routine to
1082
+ * create the command. You can override createCommand to customise subcommands.
1083
+ *
1084
+ * @param {string} [name]
1085
+ * @return {Command} new command
1086
+ */
1087
+ createCommand(name) {
1088
+ return new Command2(name);
1089
+ }
1090
+ /**
1091
+ * You can customise the help with a subclass of Help by overriding createHelp,
1092
+ * or by overriding Help properties using configureHelp().
1093
+ *
1094
+ * @return {Help}
1095
+ */
1096
+ createHelp() {
1097
+ return Object.assign(new Help2(), this.configureHelp());
1098
+ }
1099
+ /**
1100
+ * You can customise the help by overriding Help properties using configureHelp(),
1101
+ * or with a subclass of Help by overriding createHelp().
1102
+ *
1103
+ * @param {Object} [configuration] - configuration options
1104
+ * @return {Command|Object} `this` command for chaining, or stored configuration
1105
+ */
1106
+ configureHelp(configuration) {
1107
+ if (configuration === void 0)
1108
+ return this._helpConfiguration;
1109
+ this._helpConfiguration = configuration;
1110
+ return this;
1111
+ }
1112
+ /**
1113
+ * The default output goes to stdout and stderr. You can customise this for special
1114
+ * applications. You can also customise the display of errors by overriding outputError.
1115
+ *
1116
+ * The configuration properties are all functions:
1117
+ *
1118
+ * // functions to change where being written, stdout and stderr
1119
+ * writeOut(str)
1120
+ * writeErr(str)
1121
+ * // matching functions to specify width for wrapping help
1122
+ * getOutHelpWidth()
1123
+ * getErrHelpWidth()
1124
+ * // functions based on what is being written out
1125
+ * outputError(str, write) // used for displaying errors, and not used for displaying help
1126
+ *
1127
+ * @param {Object} [configuration] - configuration options
1128
+ * @return {Command|Object} `this` command for chaining, or stored configuration
1129
+ */
1130
+ configureOutput(configuration) {
1131
+ if (configuration === void 0)
1132
+ return this._outputConfiguration;
1133
+ Object.assign(this._outputConfiguration, configuration);
1134
+ return this;
1135
+ }
1136
+ /**
1137
+ * Display the help or a custom message after an error occurs.
1138
+ *
1139
+ * @param {boolean|string} [displayHelp]
1140
+ * @return {Command} `this` command for chaining
1141
+ */
1142
+ showHelpAfterError(displayHelp = true) {
1143
+ if (typeof displayHelp !== "string")
1144
+ displayHelp = !!displayHelp;
1145
+ this._showHelpAfterError = displayHelp;
1146
+ return this;
1147
+ }
1148
+ /**
1149
+ * Display suggestion of similar commands for unknown commands, or options for unknown options.
1150
+ *
1151
+ * @param {boolean} [displaySuggestion]
1152
+ * @return {Command} `this` command for chaining
1153
+ */
1154
+ showSuggestionAfterError(displaySuggestion = true) {
1155
+ this._showSuggestionAfterError = !!displaySuggestion;
1156
+ return this;
1157
+ }
1158
+ /**
1159
+ * Add a prepared subcommand.
1160
+ *
1161
+ * See .command() for creating an attached subcommand which inherits settings from its parent.
1162
+ *
1163
+ * @param {Command} cmd - new subcommand
1164
+ * @param {Object} [opts] - configuration options
1165
+ * @return {Command} `this` command for chaining
1166
+ */
1167
+ addCommand(cmd, opts) {
1168
+ if (!cmd._name) {
1169
+ throw new Error(`Command passed to .addCommand() must have a name
1170
+ - specify the name in Command constructor or using .name()`);
1171
+ }
1172
+ opts = opts || {};
1173
+ if (opts.isDefault)
1174
+ this._defaultCommandName = cmd._name;
1175
+ if (opts.noHelp || opts.hidden)
1176
+ cmd._hidden = true;
1177
+ this.commands.push(cmd);
1178
+ cmd.parent = this;
1179
+ return this;
1180
+ }
1181
+ /**
1182
+ * Factory routine to create a new unattached argument.
1183
+ *
1184
+ * See .argument() for creating an attached argument, which uses this routine to
1185
+ * create the argument. You can override createArgument to return a custom argument.
1186
+ *
1187
+ * @param {string} name
1188
+ * @param {string} [description]
1189
+ * @return {Argument} new argument
1190
+ */
1191
+ createArgument(name, description) {
1192
+ return new Argument2(name, description);
1193
+ }
1194
+ /**
1195
+ * Define argument syntax for command.
1196
+ *
1197
+ * The default is that the argument is required, and you can explicitly
1198
+ * indicate this with <> around the name. Put [] around the name for an optional argument.
1199
+ *
1200
+ * @example
1201
+ * program.argument('<input-file>');
1202
+ * program.argument('[output-file]');
1203
+ *
1204
+ * @param {string} name
1205
+ * @param {string} [description]
1206
+ * @param {Function|*} [fn] - custom argument processing function
1207
+ * @param {*} [defaultValue]
1208
+ * @return {Command} `this` command for chaining
1209
+ */
1210
+ argument(name, description, fn, defaultValue) {
1211
+ const argument = this.createArgument(name, description);
1212
+ if (typeof fn === "function") {
1213
+ argument.default(defaultValue).argParser(fn);
1214
+ } else {
1215
+ argument.default(fn);
1216
+ }
1217
+ this.addArgument(argument);
1218
+ return this;
1219
+ }
1220
+ /**
1221
+ * Define argument syntax for command, adding multiple at once (without descriptions).
1222
+ *
1223
+ * See also .argument().
1224
+ *
1225
+ * @example
1226
+ * program.arguments('<cmd> [env]');
1227
+ *
1228
+ * @param {string} names
1229
+ * @return {Command} `this` command for chaining
1230
+ */
1231
+ arguments(names) {
1232
+ names.split(/ +/).forEach((detail) => {
1233
+ this.argument(detail);
1234
+ });
1235
+ return this;
1236
+ }
1237
+ /**
1238
+ * Define argument syntax for command, adding a prepared argument.
1239
+ *
1240
+ * @param {Argument} argument
1241
+ * @return {Command} `this` command for chaining
1242
+ */
1243
+ addArgument(argument) {
1244
+ const previousArgument = this._args.slice(-1)[0];
1245
+ if (previousArgument && previousArgument.variadic) {
1246
+ throw new Error(`only the last argument can be variadic '${previousArgument.name()}'`);
1247
+ }
1248
+ if (argument.required && argument.defaultValue !== void 0 && argument.parseArg === void 0) {
1249
+ throw new Error(`a default value for a required argument is never used: '${argument.name()}'`);
1250
+ }
1251
+ this._args.push(argument);
1252
+ return this;
1253
+ }
1254
+ /**
1255
+ * Override default decision whether to add implicit help command.
1256
+ *
1257
+ * addHelpCommand() // force on
1258
+ * addHelpCommand(false); // force off
1259
+ * addHelpCommand('help [cmd]', 'display help for [cmd]'); // force on with custom details
1260
+ *
1261
+ * @return {Command} `this` command for chaining
1262
+ */
1263
+ addHelpCommand(enableOrNameAndArgs, description) {
1264
+ if (enableOrNameAndArgs === false) {
1265
+ this._addImplicitHelpCommand = false;
1266
+ } else {
1267
+ this._addImplicitHelpCommand = true;
1268
+ if (typeof enableOrNameAndArgs === "string") {
1269
+ this._helpCommandName = enableOrNameAndArgs.split(" ")[0];
1270
+ this._helpCommandnameAndArgs = enableOrNameAndArgs;
1271
+ }
1272
+ this._helpCommandDescription = description || this._helpCommandDescription;
1273
+ }
1274
+ return this;
1275
+ }
1276
+ /**
1277
+ * @return {boolean}
1278
+ * @api private
1279
+ */
1280
+ _hasImplicitHelpCommand() {
1281
+ if (this._addImplicitHelpCommand === void 0) {
1282
+ return this.commands.length && !this._actionHandler && !this._findCommand("help");
1283
+ }
1284
+ return this._addImplicitHelpCommand;
1285
+ }
1286
+ /**
1287
+ * Add hook for life cycle event.
1288
+ *
1289
+ * @param {string} event
1290
+ * @param {Function} listener
1291
+ * @return {Command} `this` command for chaining
1292
+ */
1293
+ hook(event, listener) {
1294
+ const allowedValues = ["preSubcommand", "preAction", "postAction"];
1295
+ if (!allowedValues.includes(event)) {
1296
+ throw new Error(`Unexpected value for event passed to hook : '${event}'.
1297
+ Expecting one of '${allowedValues.join("', '")}'`);
1298
+ }
1299
+ if (this._lifeCycleHooks[event]) {
1300
+ this._lifeCycleHooks[event].push(listener);
1301
+ } else {
1302
+ this._lifeCycleHooks[event] = [listener];
1303
+ }
1304
+ return this;
1305
+ }
1306
+ /**
1307
+ * Register callback to use as replacement for calling process.exit.
1308
+ *
1309
+ * @param {Function} [fn] optional callback which will be passed a CommanderError, defaults to throwing
1310
+ * @return {Command} `this` command for chaining
1311
+ */
1312
+ exitOverride(fn) {
1313
+ if (fn) {
1314
+ this._exitCallback = fn;
1315
+ } else {
1316
+ this._exitCallback = (err) => {
1317
+ if (err.code !== "commander.executeSubCommandAsync") {
1318
+ throw err;
1319
+ } else {
1320
+ }
1321
+ };
1322
+ }
1323
+ return this;
1324
+ }
1325
+ /**
1326
+ * Call process.exit, and _exitCallback if defined.
1327
+ *
1328
+ * @param {number} exitCode exit code for using with process.exit
1329
+ * @param {string} code an id string representing the error
1330
+ * @param {string} message human-readable description of the error
1331
+ * @return never
1332
+ * @api private
1333
+ */
1334
+ _exit(exitCode, code, message) {
1335
+ if (this._exitCallback) {
1336
+ this._exitCallback(new CommanderError2(exitCode, code, message));
1337
+ }
1338
+ process2.exit(exitCode);
1339
+ }
1340
+ /**
1341
+ * Register callback `fn` for the command.
1342
+ *
1343
+ * @example
1344
+ * program
1345
+ * .command('serve')
1346
+ * .description('start service')
1347
+ * .action(function() {
1348
+ * // do work here
1349
+ * });
1350
+ *
1351
+ * @param {Function} fn
1352
+ * @return {Command} `this` command for chaining
1353
+ */
1354
+ action(fn) {
1355
+ const listener = (args) => {
1356
+ const expectedArgsCount = this._args.length;
1357
+ const actionArgs = args.slice(0, expectedArgsCount);
1358
+ if (this._storeOptionsAsProperties) {
1359
+ actionArgs[expectedArgsCount] = this;
1360
+ } else {
1361
+ actionArgs[expectedArgsCount] = this.opts();
1362
+ }
1363
+ actionArgs.push(this);
1364
+ return fn.apply(this, actionArgs);
1365
+ };
1366
+ this._actionHandler = listener;
1367
+ return this;
1368
+ }
1369
+ /**
1370
+ * Factory routine to create a new unattached option.
1371
+ *
1372
+ * See .option() for creating an attached option, which uses this routine to
1373
+ * create the option. You can override createOption to return a custom option.
1374
+ *
1375
+ * @param {string} flags
1376
+ * @param {string} [description]
1377
+ * @return {Option} new option
1378
+ */
1379
+ createOption(flags, description) {
1380
+ return new Option2(flags, description);
1381
+ }
1382
+ /**
1383
+ * Add an option.
1384
+ *
1385
+ * @param {Option} option
1386
+ * @return {Command} `this` command for chaining
1387
+ */
1388
+ addOption(option) {
1389
+ const oname = option.name();
1390
+ const name = option.attributeName();
1391
+ if (option.negate) {
1392
+ const positiveLongFlag = option.long.replace(/^--no-/, "--");
1393
+ if (!this._findOption(positiveLongFlag)) {
1394
+ this.setOptionValueWithSource(name, option.defaultValue === void 0 ? true : option.defaultValue, "default");
1395
+ }
1396
+ } else if (option.defaultValue !== void 0) {
1397
+ this.setOptionValueWithSource(name, option.defaultValue, "default");
1398
+ }
1399
+ this.options.push(option);
1400
+ const handleOptionValue = (val, invalidValueMessage, valueSource) => {
1401
+ if (val == null && option.presetArg !== void 0) {
1402
+ val = option.presetArg;
1403
+ }
1404
+ const oldValue = this.getOptionValue(name);
1405
+ if (val !== null && option.parseArg) {
1406
+ try {
1407
+ val = option.parseArg(val, oldValue);
1408
+ } catch (err) {
1409
+ if (err.code === "commander.invalidArgument") {
1410
+ const message = `${invalidValueMessage} ${err.message}`;
1411
+ this.error(message, { exitCode: err.exitCode, code: err.code });
1412
+ }
1413
+ throw err;
1414
+ }
1415
+ } else if (val !== null && option.variadic) {
1416
+ val = option._concatValue(val, oldValue);
1417
+ }
1418
+ if (val == null) {
1419
+ if (option.negate) {
1420
+ val = false;
1421
+ } else if (option.isBoolean() || option.optional) {
1422
+ val = true;
1423
+ } else {
1424
+ val = "";
1425
+ }
1426
+ }
1427
+ this.setOptionValueWithSource(name, val, valueSource);
1428
+ };
1429
+ this.on("option:" + oname, (val) => {
1430
+ const invalidValueMessage = `error: option '${option.flags}' argument '${val}' is invalid.`;
1431
+ handleOptionValue(val, invalidValueMessage, "cli");
1432
+ });
1433
+ if (option.envVar) {
1434
+ this.on("optionEnv:" + oname, (val) => {
1435
+ const invalidValueMessage = `error: option '${option.flags}' value '${val}' from env '${option.envVar}' is invalid.`;
1436
+ handleOptionValue(val, invalidValueMessage, "env");
1437
+ });
1438
+ }
1439
+ return this;
1440
+ }
1441
+ /**
1442
+ * Internal implementation shared by .option() and .requiredOption()
1443
+ *
1444
+ * @api private
1445
+ */
1446
+ _optionEx(config, flags, description, fn, defaultValue) {
1447
+ if (typeof flags === "object" && flags instanceof Option2) {
1448
+ throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");
1449
+ }
1450
+ const option = this.createOption(flags, description);
1451
+ option.makeOptionMandatory(!!config.mandatory);
1452
+ if (typeof fn === "function") {
1453
+ option.default(defaultValue).argParser(fn);
1454
+ } else if (fn instanceof RegExp) {
1455
+ const regex = fn;
1456
+ fn = (val, def) => {
1457
+ const m = regex.exec(val);
1458
+ return m ? m[0] : def;
1459
+ };
1460
+ option.default(defaultValue).argParser(fn);
1461
+ } else {
1462
+ option.default(fn);
1463
+ }
1464
+ return this.addOption(option);
1465
+ }
1466
+ /**
1467
+ * Define option with `flags`, `description` and optional
1468
+ * coercion `fn`.
1469
+ *
1470
+ * The `flags` string contains the short and/or long flags,
1471
+ * separated by comma, a pipe or space. The following are all valid
1472
+ * all will output this way when `--help` is used.
1473
+ *
1474
+ * "-p, --pepper"
1475
+ * "-p|--pepper"
1476
+ * "-p --pepper"
1477
+ *
1478
+ * @example
1479
+ * // simple boolean defaulting to undefined
1480
+ * program.option('-p, --pepper', 'add pepper');
1481
+ *
1482
+ * program.pepper
1483
+ * // => undefined
1484
+ *
1485
+ * --pepper
1486
+ * program.pepper
1487
+ * // => true
1488
+ *
1489
+ * // simple boolean defaulting to true (unless non-negated option is also defined)
1490
+ * program.option('-C, --no-cheese', 'remove cheese');
1491
+ *
1492
+ * program.cheese
1493
+ * // => true
1494
+ *
1495
+ * --no-cheese
1496
+ * program.cheese
1497
+ * // => false
1498
+ *
1499
+ * // required argument
1500
+ * program.option('-C, --chdir <path>', 'change the working directory');
1501
+ *
1502
+ * --chdir /tmp
1503
+ * program.chdir
1504
+ * // => "/tmp"
1505
+ *
1506
+ * // optional argument
1507
+ * program.option('-c, --cheese [type]', 'add cheese [marble]');
1508
+ *
1509
+ * @param {string} flags
1510
+ * @param {string} [description]
1511
+ * @param {Function|*} [fn] - custom option processing function or default value
1512
+ * @param {*} [defaultValue]
1513
+ * @return {Command} `this` command for chaining
1514
+ */
1515
+ option(flags, description, fn, defaultValue) {
1516
+ return this._optionEx({}, flags, description, fn, defaultValue);
1517
+ }
1518
+ /**
1519
+ * Add a required option which must have a value after parsing. This usually means
1520
+ * the option must be specified on the command line. (Otherwise the same as .option().)
1521
+ *
1522
+ * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space.
1523
+ *
1524
+ * @param {string} flags
1525
+ * @param {string} [description]
1526
+ * @param {Function|*} [fn] - custom option processing function or default value
1527
+ * @param {*} [defaultValue]
1528
+ * @return {Command} `this` command for chaining
1529
+ */
1530
+ requiredOption(flags, description, fn, defaultValue) {
1531
+ return this._optionEx({ mandatory: true }, flags, description, fn, defaultValue);
1532
+ }
1533
+ /**
1534
+ * Alter parsing of short flags with optional values.
1535
+ *
1536
+ * @example
1537
+ * // for `.option('-f,--flag [value]'):
1538
+ * program.combineFlagAndOptionalValue(true); // `-f80` is treated like `--flag=80`, this is the default behaviour
1539
+ * program.combineFlagAndOptionalValue(false) // `-fb` is treated like `-f -b`
1540
+ *
1541
+ * @param {Boolean} [combine=true] - if `true` or omitted, an optional value can be specified directly after the flag.
1542
+ */
1543
+ combineFlagAndOptionalValue(combine = true) {
1544
+ this._combineFlagAndOptionalValue = !!combine;
1545
+ return this;
1546
+ }
1547
+ /**
1548
+ * Allow unknown options on the command line.
1549
+ *
1550
+ * @param {Boolean} [allowUnknown=true] - if `true` or omitted, no error will be thrown
1551
+ * for unknown options.
1552
+ */
1553
+ allowUnknownOption(allowUnknown = true) {
1554
+ this._allowUnknownOption = !!allowUnknown;
1555
+ return this;
1556
+ }
1557
+ /**
1558
+ * Allow excess command-arguments on the command line. Pass false to make excess arguments an error.
1559
+ *
1560
+ * @param {Boolean} [allowExcess=true] - if `true` or omitted, no error will be thrown
1561
+ * for excess arguments.
1562
+ */
1563
+ allowExcessArguments(allowExcess = true) {
1564
+ this._allowExcessArguments = !!allowExcess;
1565
+ return this;
1566
+ }
1567
+ /**
1568
+ * Enable positional options. Positional means global options are specified before subcommands which lets
1569
+ * subcommands reuse the same option names, and also enables subcommands to turn on passThroughOptions.
1570
+ * The default behaviour is non-positional and global options may appear anywhere on the command line.
1571
+ *
1572
+ * @param {Boolean} [positional=true]
1573
+ */
1574
+ enablePositionalOptions(positional = true) {
1575
+ this._enablePositionalOptions = !!positional;
1576
+ return this;
1577
+ }
1578
+ /**
1579
+ * Pass through options that come after command-arguments rather than treat them as command-options,
1580
+ * so actual command-options come before command-arguments. Turning this on for a subcommand requires
1581
+ * positional options to have been enabled on the program (parent commands).
1582
+ * The default behaviour is non-positional and options may appear before or after command-arguments.
1583
+ *
1584
+ * @param {Boolean} [passThrough=true]
1585
+ * for unknown options.
1586
+ */
1587
+ passThroughOptions(passThrough = true) {
1588
+ this._passThroughOptions = !!passThrough;
1589
+ if (!!this.parent && passThrough && !this.parent._enablePositionalOptions) {
1590
+ throw new Error("passThroughOptions can not be used without turning on enablePositionalOptions for parent command(s)");
1591
+ }
1592
+ return this;
1593
+ }
1594
+ /**
1595
+ * Whether to store option values as properties on command object,
1596
+ * or store separately (specify false). In both cases the option values can be accessed using .opts().
1597
+ *
1598
+ * @param {boolean} [storeAsProperties=true]
1599
+ * @return {Command} `this` command for chaining
1600
+ */
1601
+ storeOptionsAsProperties(storeAsProperties = true) {
1602
+ this._storeOptionsAsProperties = !!storeAsProperties;
1603
+ if (this.options.length) {
1604
+ throw new Error("call .storeOptionsAsProperties() before adding options");
1605
+ }
1606
+ return this;
1607
+ }
1608
+ /**
1609
+ * Retrieve option value.
1610
+ *
1611
+ * @param {string} key
1612
+ * @return {Object} value
1613
+ */
1614
+ getOptionValue(key) {
1615
+ if (this._storeOptionsAsProperties) {
1616
+ return this[key];
1617
+ }
1618
+ return this._optionValues[key];
1619
+ }
1620
+ /**
1621
+ * Store option value.
1622
+ *
1623
+ * @param {string} key
1624
+ * @param {Object} value
1625
+ * @return {Command} `this` command for chaining
1626
+ */
1627
+ setOptionValue(key, value) {
1628
+ return this.setOptionValueWithSource(key, value, void 0);
1629
+ }
1630
+ /**
1631
+ * Store option value and where the value came from.
1632
+ *
1633
+ * @param {string} key
1634
+ * @param {Object} value
1635
+ * @param {string} source - expected values are default/config/env/cli/implied
1636
+ * @return {Command} `this` command for chaining
1637
+ */
1638
+ setOptionValueWithSource(key, value, source) {
1639
+ if (this._storeOptionsAsProperties) {
1640
+ this[key] = value;
1641
+ } else {
1642
+ this._optionValues[key] = value;
1643
+ }
1644
+ this._optionValueSources[key] = source;
1645
+ return this;
1646
+ }
1647
+ /**
1648
+ * Get source of option value.
1649
+ * Expected values are default | config | env | cli | implied
1650
+ *
1651
+ * @param {string} key
1652
+ * @return {string}
1653
+ */
1654
+ getOptionValueSource(key) {
1655
+ return this._optionValueSources[key];
1656
+ }
1657
+ /**
1658
+ * Get source of option value. See also .optsWithGlobals().
1659
+ * Expected values are default | config | env | cli | implied
1660
+ *
1661
+ * @param {string} key
1662
+ * @return {string}
1663
+ */
1664
+ getOptionValueSourceWithGlobals(key) {
1665
+ let source;
1666
+ getCommandAndParents(this).forEach((cmd) => {
1667
+ if (cmd.getOptionValueSource(key) !== void 0) {
1668
+ source = cmd.getOptionValueSource(key);
1669
+ }
1670
+ });
1671
+ return source;
1672
+ }
1673
+ /**
1674
+ * Get user arguments from implied or explicit arguments.
1675
+ * Side-effects: set _scriptPath if args included script. Used for default program name, and subcommand searches.
1676
+ *
1677
+ * @api private
1678
+ */
1679
+ _prepareUserArgs(argv, parseOptions) {
1680
+ if (argv !== void 0 && !Array.isArray(argv)) {
1681
+ throw new Error("first parameter to parse must be array or undefined");
1682
+ }
1683
+ parseOptions = parseOptions || {};
1684
+ if (argv === void 0) {
1685
+ argv = process2.argv;
1686
+ if (process2.versions && process2.versions.electron) {
1687
+ parseOptions.from = "electron";
1688
+ }
1689
+ }
1690
+ this.rawArgs = argv.slice();
1691
+ let userArgs;
1692
+ switch (parseOptions.from) {
1693
+ case void 0:
1694
+ case "node":
1695
+ this._scriptPath = argv[1];
1696
+ userArgs = argv.slice(2);
1697
+ break;
1698
+ case "electron":
1699
+ if (process2.defaultApp) {
1700
+ this._scriptPath = argv[1];
1701
+ userArgs = argv.slice(2);
1702
+ } else {
1703
+ userArgs = argv.slice(1);
1704
+ }
1705
+ break;
1706
+ case "user":
1707
+ userArgs = argv.slice(0);
1708
+ break;
1709
+ default:
1710
+ throw new Error(`unexpected parse option { from: '${parseOptions.from}' }`);
1711
+ }
1712
+ if (!this._name && this._scriptPath)
1713
+ this.nameFromFilename(this._scriptPath);
1714
+ this._name = this._name || "program";
1715
+ return userArgs;
1716
+ }
1717
+ /**
1718
+ * Parse `argv`, setting options and invoking commands when defined.
1719
+ *
1720
+ * The default expectation is that the arguments are from node and have the application as argv[0]
1721
+ * and the script being run in argv[1], with user parameters after that.
1722
+ *
1723
+ * @example
1724
+ * program.parse(process.argv);
1725
+ * program.parse(); // implicitly use process.argv and auto-detect node vs electron conventions
1726
+ * program.parse(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
1727
+ *
1728
+ * @param {string[]} [argv] - optional, defaults to process.argv
1729
+ * @param {Object} [parseOptions] - optionally specify style of options with from: node/user/electron
1730
+ * @param {string} [parseOptions.from] - where the args are from: 'node', 'user', 'electron'
1731
+ * @return {Command} `this` command for chaining
1732
+ */
1733
+ parse(argv, parseOptions) {
1734
+ const userArgs = this._prepareUserArgs(argv, parseOptions);
1735
+ this._parseCommand([], userArgs);
1736
+ return this;
1737
+ }
1738
+ /**
1739
+ * Parse `argv`, setting options and invoking commands when defined.
1740
+ *
1741
+ * Use parseAsync instead of parse if any of your action handlers are async. Returns a Promise.
1742
+ *
1743
+ * The default expectation is that the arguments are from node and have the application as argv[0]
1744
+ * and the script being run in argv[1], with user parameters after that.
1745
+ *
1746
+ * @example
1747
+ * await program.parseAsync(process.argv);
1748
+ * await program.parseAsync(); // implicitly use process.argv and auto-detect node vs electron conventions
1749
+ * await program.parseAsync(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
1750
+ *
1751
+ * @param {string[]} [argv]
1752
+ * @param {Object} [parseOptions]
1753
+ * @param {string} parseOptions.from - where the args are from: 'node', 'user', 'electron'
1754
+ * @return {Promise}
1755
+ */
1756
+ async parseAsync(argv, parseOptions) {
1757
+ const userArgs = this._prepareUserArgs(argv, parseOptions);
1758
+ await this._parseCommand([], userArgs);
1759
+ return this;
1760
+ }
1761
+ /**
1762
+ * Execute a sub-command executable.
1763
+ *
1764
+ * @api private
1765
+ */
1766
+ _executeSubCommand(subcommand, args) {
1767
+ args = args.slice();
1768
+ let launchWithNode = false;
1769
+ const sourceExt = [".js", ".ts", ".tsx", ".mjs", ".cjs"];
1770
+ function findFile(baseDir, baseName) {
1771
+ const localBin = path.resolve(baseDir, baseName);
1772
+ if (fs.existsSync(localBin))
1773
+ return localBin;
1774
+ if (sourceExt.includes(path.extname(baseName)))
1775
+ return void 0;
1776
+ const foundExt = sourceExt.find((ext) => fs.existsSync(`${localBin}${ext}`));
1777
+ if (foundExt)
1778
+ return `${localBin}${foundExt}`;
1779
+ return void 0;
1780
+ }
1781
+ this._checkForMissingMandatoryOptions();
1782
+ this._checkForConflictingOptions();
1783
+ let executableFile = subcommand._executableFile || `${this._name}-${subcommand._name}`;
1784
+ let executableDir = this._executableDir || "";
1785
+ if (this._scriptPath) {
1786
+ let resolvedScriptPath;
1787
+ try {
1788
+ resolvedScriptPath = fs.realpathSync(this._scriptPath);
1789
+ } catch (err) {
1790
+ resolvedScriptPath = this._scriptPath;
1791
+ }
1792
+ executableDir = path.resolve(path.dirname(resolvedScriptPath), executableDir);
1793
+ }
1794
+ if (executableDir) {
1795
+ let localFile = findFile(executableDir, executableFile);
1796
+ if (!localFile && !subcommand._executableFile && this._scriptPath) {
1797
+ const legacyName = path.basename(this._scriptPath, path.extname(this._scriptPath));
1798
+ if (legacyName !== this._name) {
1799
+ localFile = findFile(executableDir, `${legacyName}-${subcommand._name}`);
1800
+ }
1801
+ }
1802
+ executableFile = localFile || executableFile;
1803
+ }
1804
+ launchWithNode = sourceExt.includes(path.extname(executableFile));
1805
+ let proc;
1806
+ if (process2.platform !== "win32") {
1807
+ if (launchWithNode) {
1808
+ args.unshift(executableFile);
1809
+ args = incrementNodeInspectorPort(process2.execArgv).concat(args);
1810
+ proc = childProcess.spawn(process2.argv[0], args, { stdio: "inherit" });
1811
+ } else {
1812
+ proc = childProcess.spawn(executableFile, args, { stdio: "inherit" });
1813
+ }
1814
+ } else {
1815
+ args.unshift(executableFile);
1816
+ args = incrementNodeInspectorPort(process2.execArgv).concat(args);
1817
+ proc = childProcess.spawn(process2.execPath, args, { stdio: "inherit" });
1818
+ }
1819
+ if (!proc.killed) {
1820
+ const signals = ["SIGUSR1", "SIGUSR2", "SIGTERM", "SIGINT", "SIGHUP"];
1821
+ signals.forEach((signal) => {
1822
+ process2.on(signal, () => {
1823
+ if (proc.killed === false && proc.exitCode === null) {
1824
+ proc.kill(signal);
1825
+ }
1826
+ });
1827
+ });
1828
+ }
1829
+ const exitCallback = this._exitCallback;
1830
+ if (!exitCallback) {
1831
+ proc.on("close", process2.exit.bind(process2));
1832
+ } else {
1833
+ proc.on("close", () => {
1834
+ exitCallback(new CommanderError2(process2.exitCode || 0, "commander.executeSubCommandAsync", "(close)"));
1835
+ });
1836
+ }
1837
+ proc.on("error", (err) => {
1838
+ if (err.code === "ENOENT") {
1839
+ const executableDirMessage = executableDir ? `searched for local subcommand relative to directory '${executableDir}'` : "no directory for search for local subcommand, use .executableDir() to supply a custom directory";
1840
+ const executableMissing = `'${executableFile}' does not exist
1841
+ - if '${subcommand._name}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
1842
+ - if the default executable name is not suitable, use the executableFile option to supply a custom name or path
1843
+ - ${executableDirMessage}`;
1844
+ throw new Error(executableMissing);
1845
+ } else if (err.code === "EACCES") {
1846
+ throw new Error(`'${executableFile}' not executable`);
1847
+ }
1848
+ if (!exitCallback) {
1849
+ process2.exit(1);
1850
+ } else {
1851
+ const wrappedError = new CommanderError2(1, "commander.executeSubCommandAsync", "(error)");
1852
+ wrappedError.nestedError = err;
1853
+ exitCallback(wrappedError);
1854
+ }
1855
+ });
1856
+ this.runningCommand = proc;
1857
+ }
1858
+ /**
1859
+ * @api private
1860
+ */
1861
+ _dispatchSubcommand(commandName, operands, unknown) {
1862
+ const subCommand = this._findCommand(commandName);
1863
+ if (!subCommand)
1864
+ this.help({ error: true });
1865
+ let hookResult;
1866
+ hookResult = this._chainOrCallSubCommandHook(hookResult, subCommand, "preSubcommand");
1867
+ hookResult = this._chainOrCall(hookResult, () => {
1868
+ if (subCommand._executableHandler) {
1869
+ this._executeSubCommand(subCommand, operands.concat(unknown));
1870
+ } else {
1871
+ return subCommand._parseCommand(operands, unknown);
1872
+ }
1873
+ });
1874
+ return hookResult;
1875
+ }
1876
+ /**
1877
+ * Check this.args against expected this._args.
1878
+ *
1879
+ * @api private
1880
+ */
1881
+ _checkNumberOfArguments() {
1882
+ this._args.forEach((arg, i) => {
1883
+ if (arg.required && this.args[i] == null) {
1884
+ this.missingArgument(arg.name());
1885
+ }
1886
+ });
1887
+ if (this._args.length > 0 && this._args[this._args.length - 1].variadic) {
1888
+ return;
1889
+ }
1890
+ if (this.args.length > this._args.length) {
1891
+ this._excessArguments(this.args);
1892
+ }
1893
+ }
1894
+ /**
1895
+ * Process this.args using this._args and save as this.processedArgs!
1896
+ *
1897
+ * @api private
1898
+ */
1899
+ _processArguments() {
1900
+ const myParseArg = (argument, value, previous) => {
1901
+ let parsedValue = value;
1902
+ if (value !== null && argument.parseArg) {
1903
+ try {
1904
+ parsedValue = argument.parseArg(value, previous);
1905
+ } catch (err) {
1906
+ if (err.code === "commander.invalidArgument") {
1907
+ const message = `error: command-argument value '${value}' is invalid for argument '${argument.name()}'. ${err.message}`;
1908
+ this.error(message, { exitCode: err.exitCode, code: err.code });
1909
+ }
1910
+ throw err;
1911
+ }
1912
+ }
1913
+ return parsedValue;
1914
+ };
1915
+ this._checkNumberOfArguments();
1916
+ const processedArgs = [];
1917
+ this._args.forEach((declaredArg, index) => {
1918
+ let value = declaredArg.defaultValue;
1919
+ if (declaredArg.variadic) {
1920
+ if (index < this.args.length) {
1921
+ value = this.args.slice(index);
1922
+ if (declaredArg.parseArg) {
1923
+ value = value.reduce((processed, v) => {
1924
+ return myParseArg(declaredArg, v, processed);
1925
+ }, declaredArg.defaultValue);
1926
+ }
1927
+ } else if (value === void 0) {
1928
+ value = [];
1929
+ }
1930
+ } else if (index < this.args.length) {
1931
+ value = this.args[index];
1932
+ if (declaredArg.parseArg) {
1933
+ value = myParseArg(declaredArg, value, declaredArg.defaultValue);
1934
+ }
1935
+ }
1936
+ processedArgs[index] = value;
1937
+ });
1938
+ this.processedArgs = processedArgs;
1939
+ }
1940
+ /**
1941
+ * Once we have a promise we chain, but call synchronously until then.
1942
+ *
1943
+ * @param {Promise|undefined} promise
1944
+ * @param {Function} fn
1945
+ * @return {Promise|undefined}
1946
+ * @api private
1947
+ */
1948
+ _chainOrCall(promise, fn) {
1949
+ if (promise && promise.then && typeof promise.then === "function") {
1950
+ return promise.then(() => fn());
1951
+ }
1952
+ return fn();
1953
+ }
1954
+ /**
1955
+ *
1956
+ * @param {Promise|undefined} promise
1957
+ * @param {string} event
1958
+ * @return {Promise|undefined}
1959
+ * @api private
1960
+ */
1961
+ _chainOrCallHooks(promise, event) {
1962
+ let result = promise;
1963
+ const hooks = [];
1964
+ getCommandAndParents(this).reverse().filter((cmd) => cmd._lifeCycleHooks[event] !== void 0).forEach((hookedCommand) => {
1965
+ hookedCommand._lifeCycleHooks[event].forEach((callback) => {
1966
+ hooks.push({ hookedCommand, callback });
1967
+ });
1968
+ });
1969
+ if (event === "postAction") {
1970
+ hooks.reverse();
1971
+ }
1972
+ hooks.forEach((hookDetail) => {
1973
+ result = this._chainOrCall(result, () => {
1974
+ return hookDetail.callback(hookDetail.hookedCommand, this);
1975
+ });
1976
+ });
1977
+ return result;
1978
+ }
1979
+ /**
1980
+ *
1981
+ * @param {Promise|undefined} promise
1982
+ * @param {Command} subCommand
1983
+ * @param {string} event
1984
+ * @return {Promise|undefined}
1985
+ * @api private
1986
+ */
1987
+ _chainOrCallSubCommandHook(promise, subCommand, event) {
1988
+ let result = promise;
1989
+ if (this._lifeCycleHooks[event] !== void 0) {
1990
+ this._lifeCycleHooks[event].forEach((hook) => {
1991
+ result = this._chainOrCall(result, () => {
1992
+ return hook(this, subCommand);
1993
+ });
1994
+ });
1995
+ }
1996
+ return result;
1997
+ }
1998
+ /**
1999
+ * Process arguments in context of this command.
2000
+ * Returns action result, in case it is a promise.
2001
+ *
2002
+ * @api private
2003
+ */
2004
+ _parseCommand(operands, unknown) {
2005
+ const parsed = this.parseOptions(unknown);
2006
+ this._parseOptionsEnv();
2007
+ this._parseOptionsImplied();
2008
+ operands = operands.concat(parsed.operands);
2009
+ unknown = parsed.unknown;
2010
+ this.args = operands.concat(unknown);
2011
+ if (operands && this._findCommand(operands[0])) {
2012
+ return this._dispatchSubcommand(operands[0], operands.slice(1), unknown);
2013
+ }
2014
+ if (this._hasImplicitHelpCommand() && operands[0] === this._helpCommandName) {
2015
+ if (operands.length === 1) {
2016
+ this.help();
2017
+ }
2018
+ return this._dispatchSubcommand(operands[1], [], [this._helpLongFlag]);
2019
+ }
2020
+ if (this._defaultCommandName) {
2021
+ outputHelpIfRequested(this, unknown);
2022
+ return this._dispatchSubcommand(this._defaultCommandName, operands, unknown);
2023
+ }
2024
+ if (this.commands.length && this.args.length === 0 && !this._actionHandler && !this._defaultCommandName) {
2025
+ this.help({ error: true });
2026
+ }
2027
+ outputHelpIfRequested(this, parsed.unknown);
2028
+ this._checkForMissingMandatoryOptions();
2029
+ this._checkForConflictingOptions();
2030
+ const checkForUnknownOptions = () => {
2031
+ if (parsed.unknown.length > 0) {
2032
+ this.unknownOption(parsed.unknown[0]);
2033
+ }
2034
+ };
2035
+ const commandEvent = `command:${this.name()}`;
2036
+ if (this._actionHandler) {
2037
+ checkForUnknownOptions();
2038
+ this._processArguments();
2039
+ let actionResult;
2040
+ actionResult = this._chainOrCallHooks(actionResult, "preAction");
2041
+ actionResult = this._chainOrCall(actionResult, () => this._actionHandler(this.processedArgs));
2042
+ if (this.parent) {
2043
+ actionResult = this._chainOrCall(actionResult, () => {
2044
+ this.parent.emit(commandEvent, operands, unknown);
2045
+ });
2046
+ }
2047
+ actionResult = this._chainOrCallHooks(actionResult, "postAction");
2048
+ return actionResult;
2049
+ }
2050
+ if (this.parent && this.parent.listenerCount(commandEvent)) {
2051
+ checkForUnknownOptions();
2052
+ this._processArguments();
2053
+ this.parent.emit(commandEvent, operands, unknown);
2054
+ } else if (operands.length) {
2055
+ if (this._findCommand("*")) {
2056
+ return this._dispatchSubcommand("*", operands, unknown);
2057
+ }
2058
+ if (this.listenerCount("command:*")) {
2059
+ this.emit("command:*", operands, unknown);
2060
+ } else if (this.commands.length) {
2061
+ this.unknownCommand();
2062
+ } else {
2063
+ checkForUnknownOptions();
2064
+ this._processArguments();
2065
+ }
2066
+ } else if (this.commands.length) {
2067
+ checkForUnknownOptions();
2068
+ this.help({ error: true });
2069
+ } else {
2070
+ checkForUnknownOptions();
2071
+ this._processArguments();
2072
+ }
2073
+ }
2074
+ /**
2075
+ * Find matching command.
2076
+ *
2077
+ * @api private
2078
+ */
2079
+ _findCommand(name) {
2080
+ if (!name)
2081
+ return void 0;
2082
+ return this.commands.find((cmd) => cmd._name === name || cmd._aliases.includes(name));
2083
+ }
2084
+ /**
2085
+ * Return an option matching `arg` if any.
2086
+ *
2087
+ * @param {string} arg
2088
+ * @return {Option}
2089
+ * @api private
2090
+ */
2091
+ _findOption(arg) {
2092
+ return this.options.find((option) => option.is(arg));
2093
+ }
2094
+ /**
2095
+ * Display an error message if a mandatory option does not have a value.
2096
+ * Called after checking for help flags in leaf subcommand.
2097
+ *
2098
+ * @api private
2099
+ */
2100
+ _checkForMissingMandatoryOptions() {
2101
+ for (let cmd = this; cmd; cmd = cmd.parent) {
2102
+ cmd.options.forEach((anOption) => {
2103
+ if (anOption.mandatory && cmd.getOptionValue(anOption.attributeName()) === void 0) {
2104
+ cmd.missingMandatoryOptionValue(anOption);
2105
+ }
2106
+ });
2107
+ }
2108
+ }
2109
+ /**
2110
+ * Display an error message if conflicting options are used together in this.
2111
+ *
2112
+ * @api private
2113
+ */
2114
+ _checkForConflictingLocalOptions() {
2115
+ const definedNonDefaultOptions = this.options.filter(
2116
+ (option) => {
2117
+ const optionKey = option.attributeName();
2118
+ if (this.getOptionValue(optionKey) === void 0) {
2119
+ return false;
2120
+ }
2121
+ return this.getOptionValueSource(optionKey) !== "default";
2122
+ }
2123
+ );
2124
+ const optionsWithConflicting = definedNonDefaultOptions.filter(
2125
+ (option) => option.conflictsWith.length > 0
2126
+ );
2127
+ optionsWithConflicting.forEach((option) => {
2128
+ const conflictingAndDefined = definedNonDefaultOptions.find(
2129
+ (defined) => option.conflictsWith.includes(defined.attributeName())
2130
+ );
2131
+ if (conflictingAndDefined) {
2132
+ this._conflictingOption(option, conflictingAndDefined);
2133
+ }
2134
+ });
2135
+ }
2136
+ /**
2137
+ * Display an error message if conflicting options are used together.
2138
+ * Called after checking for help flags in leaf subcommand.
2139
+ *
2140
+ * @api private
2141
+ */
2142
+ _checkForConflictingOptions() {
2143
+ for (let cmd = this; cmd; cmd = cmd.parent) {
2144
+ cmd._checkForConflictingLocalOptions();
2145
+ }
2146
+ }
2147
+ /**
2148
+ * Parse options from `argv` removing known options,
2149
+ * and return argv split into operands and unknown arguments.
2150
+ *
2151
+ * Examples:
2152
+ *
2153
+ * argv => operands, unknown
2154
+ * --known kkk op => [op], []
2155
+ * op --known kkk => [op], []
2156
+ * sub --unknown uuu op => [sub], [--unknown uuu op]
2157
+ * sub -- --unknown uuu op => [sub --unknown uuu op], []
2158
+ *
2159
+ * @param {String[]} argv
2160
+ * @return {{operands: String[], unknown: String[]}}
2161
+ */
2162
+ parseOptions(argv) {
2163
+ const operands = [];
2164
+ const unknown = [];
2165
+ let dest = operands;
2166
+ const args = argv.slice();
2167
+ function maybeOption(arg) {
2168
+ return arg.length > 1 && arg[0] === "-";
2169
+ }
2170
+ let activeVariadicOption = null;
2171
+ while (args.length) {
2172
+ const arg = args.shift();
2173
+ if (arg === "--") {
2174
+ if (dest === unknown)
2175
+ dest.push(arg);
2176
+ dest.push(...args);
2177
+ break;
2178
+ }
2179
+ if (activeVariadicOption && !maybeOption(arg)) {
2180
+ this.emit(`option:${activeVariadicOption.name()}`, arg);
2181
+ continue;
2182
+ }
2183
+ activeVariadicOption = null;
2184
+ if (maybeOption(arg)) {
2185
+ const option = this._findOption(arg);
2186
+ if (option) {
2187
+ if (option.required) {
2188
+ const value = args.shift();
2189
+ if (value === void 0)
2190
+ this.optionMissingArgument(option);
2191
+ this.emit(`option:${option.name()}`, value);
2192
+ } else if (option.optional) {
2193
+ let value = null;
2194
+ if (args.length > 0 && !maybeOption(args[0])) {
2195
+ value = args.shift();
2196
+ }
2197
+ this.emit(`option:${option.name()}`, value);
2198
+ } else {
2199
+ this.emit(`option:${option.name()}`);
2200
+ }
2201
+ activeVariadicOption = option.variadic ? option : null;
2202
+ continue;
2203
+ }
2204
+ }
2205
+ if (arg.length > 2 && arg[0] === "-" && arg[1] !== "-") {
2206
+ const option = this._findOption(`-${arg[1]}`);
2207
+ if (option) {
2208
+ if (option.required || option.optional && this._combineFlagAndOptionalValue) {
2209
+ this.emit(`option:${option.name()}`, arg.slice(2));
2210
+ } else {
2211
+ this.emit(`option:${option.name()}`);
2212
+ args.unshift(`-${arg.slice(2)}`);
2213
+ }
2214
+ continue;
2215
+ }
2216
+ }
2217
+ if (/^--[^=]+=/.test(arg)) {
2218
+ const index = arg.indexOf("=");
2219
+ const option = this._findOption(arg.slice(0, index));
2220
+ if (option && (option.required || option.optional)) {
2221
+ this.emit(`option:${option.name()}`, arg.slice(index + 1));
2222
+ continue;
2223
+ }
2224
+ }
2225
+ if (maybeOption(arg)) {
2226
+ dest = unknown;
2227
+ }
2228
+ if ((this._enablePositionalOptions || this._passThroughOptions) && operands.length === 0 && unknown.length === 0) {
2229
+ if (this._findCommand(arg)) {
2230
+ operands.push(arg);
2231
+ if (args.length > 0)
2232
+ unknown.push(...args);
2233
+ break;
2234
+ } else if (arg === this._helpCommandName && this._hasImplicitHelpCommand()) {
2235
+ operands.push(arg);
2236
+ if (args.length > 0)
2237
+ operands.push(...args);
2238
+ break;
2239
+ } else if (this._defaultCommandName) {
2240
+ unknown.push(arg);
2241
+ if (args.length > 0)
2242
+ unknown.push(...args);
2243
+ break;
2244
+ }
2245
+ }
2246
+ if (this._passThroughOptions) {
2247
+ dest.push(arg);
2248
+ if (args.length > 0)
2249
+ dest.push(...args);
2250
+ break;
2251
+ }
2252
+ dest.push(arg);
2253
+ }
2254
+ return { operands, unknown };
2255
+ }
2256
+ /**
2257
+ * Return an object containing local option values as key-value pairs.
2258
+ *
2259
+ * @return {Object}
2260
+ */
2261
+ opts() {
2262
+ if (this._storeOptionsAsProperties) {
2263
+ const result = {};
2264
+ const len = this.options.length;
2265
+ for (let i = 0; i < len; i++) {
2266
+ const key = this.options[i].attributeName();
2267
+ result[key] = key === this._versionOptionName ? this._version : this[key];
2268
+ }
2269
+ return result;
2270
+ }
2271
+ return this._optionValues;
2272
+ }
2273
+ /**
2274
+ * Return an object containing merged local and global option values as key-value pairs.
2275
+ *
2276
+ * @return {Object}
2277
+ */
2278
+ optsWithGlobals() {
2279
+ return getCommandAndParents(this).reduce(
2280
+ (combinedOptions, cmd) => Object.assign(combinedOptions, cmd.opts()),
2281
+ {}
2282
+ );
2283
+ }
2284
+ /**
2285
+ * Display error message and exit (or call exitOverride).
2286
+ *
2287
+ * @param {string} message
2288
+ * @param {Object} [errorOptions]
2289
+ * @param {string} [errorOptions.code] - an id string representing the error
2290
+ * @param {number} [errorOptions.exitCode] - used with process.exit
2291
+ */
2292
+ error(message, errorOptions) {
2293
+ this._outputConfiguration.outputError(`${message}
2294
+ `, this._outputConfiguration.writeErr);
2295
+ if (typeof this._showHelpAfterError === "string") {
2296
+ this._outputConfiguration.writeErr(`${this._showHelpAfterError}
2297
+ `);
2298
+ } else if (this._showHelpAfterError) {
2299
+ this._outputConfiguration.writeErr("\n");
2300
+ this.outputHelp({ error: true });
2301
+ }
2302
+ const config = errorOptions || {};
2303
+ const exitCode = config.exitCode || 1;
2304
+ const code = config.code || "commander.error";
2305
+ this._exit(exitCode, code, message);
2306
+ }
2307
+ /**
2308
+ * Apply any option related environment variables, if option does
2309
+ * not have a value from cli or client code.
2310
+ *
2311
+ * @api private
2312
+ */
2313
+ _parseOptionsEnv() {
2314
+ this.options.forEach((option) => {
2315
+ if (option.envVar && option.envVar in process2.env) {
2316
+ const optionKey = option.attributeName();
2317
+ if (this.getOptionValue(optionKey) === void 0 || ["default", "config", "env"].includes(this.getOptionValueSource(optionKey))) {
2318
+ if (option.required || option.optional) {
2319
+ this.emit(`optionEnv:${option.name()}`, process2.env[option.envVar]);
2320
+ } else {
2321
+ this.emit(`optionEnv:${option.name()}`);
2322
+ }
2323
+ }
2324
+ }
2325
+ });
2326
+ }
2327
+ /**
2328
+ * Apply any implied option values, if option is undefined or default value.
2329
+ *
2330
+ * @api private
2331
+ */
2332
+ _parseOptionsImplied() {
2333
+ const dualHelper = new DualOptions(this.options);
2334
+ const hasCustomOptionValue = (optionKey) => {
2335
+ return this.getOptionValue(optionKey) !== void 0 && !["default", "implied"].includes(this.getOptionValueSource(optionKey));
2336
+ };
2337
+ this.options.filter((option) => option.implied !== void 0 && hasCustomOptionValue(option.attributeName()) && dualHelper.valueFromOption(this.getOptionValue(option.attributeName()), option)).forEach((option) => {
2338
+ Object.keys(option.implied).filter((impliedKey) => !hasCustomOptionValue(impliedKey)).forEach((impliedKey) => {
2339
+ this.setOptionValueWithSource(impliedKey, option.implied[impliedKey], "implied");
2340
+ });
2341
+ });
2342
+ }
2343
+ /**
2344
+ * Argument `name` is missing.
2345
+ *
2346
+ * @param {string} name
2347
+ * @api private
2348
+ */
2349
+ missingArgument(name) {
2350
+ const message = `error: missing required argument '${name}'`;
2351
+ this.error(message, { code: "commander.missingArgument" });
2352
+ }
2353
+ /**
2354
+ * `Option` is missing an argument.
2355
+ *
2356
+ * @param {Option} option
2357
+ * @api private
2358
+ */
2359
+ optionMissingArgument(option) {
2360
+ const message = `error: option '${option.flags}' argument missing`;
2361
+ this.error(message, { code: "commander.optionMissingArgument" });
2362
+ }
2363
+ /**
2364
+ * `Option` does not have a value, and is a mandatory option.
2365
+ *
2366
+ * @param {Option} option
2367
+ * @api private
2368
+ */
2369
+ missingMandatoryOptionValue(option) {
2370
+ const message = `error: required option '${option.flags}' not specified`;
2371
+ this.error(message, { code: "commander.missingMandatoryOptionValue" });
2372
+ }
2373
+ /**
2374
+ * `Option` conflicts with another option.
2375
+ *
2376
+ * @param {Option} option
2377
+ * @param {Option} conflictingOption
2378
+ * @api private
2379
+ */
2380
+ _conflictingOption(option, conflictingOption) {
2381
+ const findBestOptionFromValue = (option2) => {
2382
+ const optionKey = option2.attributeName();
2383
+ const optionValue = this.getOptionValue(optionKey);
2384
+ const negativeOption = this.options.find((target) => target.negate && optionKey === target.attributeName());
2385
+ const positiveOption = this.options.find((target) => !target.negate && optionKey === target.attributeName());
2386
+ if (negativeOption && (negativeOption.presetArg === void 0 && optionValue === false || negativeOption.presetArg !== void 0 && optionValue === negativeOption.presetArg)) {
2387
+ return negativeOption;
2388
+ }
2389
+ return positiveOption || option2;
2390
+ };
2391
+ const getErrorMessage = (option2) => {
2392
+ const bestOption = findBestOptionFromValue(option2);
2393
+ const optionKey = bestOption.attributeName();
2394
+ const source = this.getOptionValueSource(optionKey);
2395
+ if (source === "env") {
2396
+ return `environment variable '${bestOption.envVar}'`;
2397
+ }
2398
+ return `option '${bestOption.flags}'`;
2399
+ };
2400
+ const message = `error: ${getErrorMessage(option)} cannot be used with ${getErrorMessage(conflictingOption)}`;
2401
+ this.error(message, { code: "commander.conflictingOption" });
2402
+ }
2403
+ /**
2404
+ * Unknown option `flag`.
2405
+ *
2406
+ * @param {string} flag
2407
+ * @api private
2408
+ */
2409
+ unknownOption(flag) {
2410
+ if (this._allowUnknownOption)
2411
+ return;
2412
+ let suggestion = "";
2413
+ if (flag.startsWith("--") && this._showSuggestionAfterError) {
2414
+ let candidateFlags = [];
2415
+ let command = this;
2416
+ do {
2417
+ const moreFlags = command.createHelp().visibleOptions(command).filter((option) => option.long).map((option) => option.long);
2418
+ candidateFlags = candidateFlags.concat(moreFlags);
2419
+ command = command.parent;
2420
+ } while (command && !command._enablePositionalOptions);
2421
+ suggestion = suggestSimilar(flag, candidateFlags);
2422
+ }
2423
+ const message = `error: unknown option '${flag}'${suggestion}`;
2424
+ this.error(message, { code: "commander.unknownOption" });
2425
+ }
2426
+ /**
2427
+ * Excess arguments, more than expected.
2428
+ *
2429
+ * @param {string[]} receivedArgs
2430
+ * @api private
2431
+ */
2432
+ _excessArguments(receivedArgs) {
2433
+ if (this._allowExcessArguments)
2434
+ return;
2435
+ const expected = this._args.length;
2436
+ const s = expected === 1 ? "" : "s";
2437
+ const forSubcommand = this.parent ? ` for '${this.name()}'` : "";
2438
+ const message = `error: too many arguments${forSubcommand}. Expected ${expected} argument${s} but got ${receivedArgs.length}.`;
2439
+ this.error(message, { code: "commander.excessArguments" });
2440
+ }
2441
+ /**
2442
+ * Unknown command.
2443
+ *
2444
+ * @api private
2445
+ */
2446
+ unknownCommand() {
2447
+ const unknownName = this.args[0];
2448
+ let suggestion = "";
2449
+ if (this._showSuggestionAfterError) {
2450
+ const candidateNames = [];
2451
+ this.createHelp().visibleCommands(this).forEach((command) => {
2452
+ candidateNames.push(command.name());
2453
+ if (command.alias())
2454
+ candidateNames.push(command.alias());
2455
+ });
2456
+ suggestion = suggestSimilar(unknownName, candidateNames);
2457
+ }
2458
+ const message = `error: unknown command '${unknownName}'${suggestion}`;
2459
+ this.error(message, { code: "commander.unknownCommand" });
2460
+ }
2461
+ /**
2462
+ * Set the program version to `str`.
2463
+ *
2464
+ * This method auto-registers the "-V, --version" flag
2465
+ * which will print the version number when passed.
2466
+ *
2467
+ * You can optionally supply the flags and description to override the defaults.
2468
+ *
2469
+ * @param {string} str
2470
+ * @param {string} [flags]
2471
+ * @param {string} [description]
2472
+ * @return {this | string} `this` command for chaining, or version string if no arguments
2473
+ */
2474
+ version(str, flags, description) {
2475
+ if (str === void 0)
2476
+ return this._version;
2477
+ this._version = str;
2478
+ flags = flags || "-V, --version";
2479
+ description = description || "output the version number";
2480
+ const versionOption = this.createOption(flags, description);
2481
+ this._versionOptionName = versionOption.attributeName();
2482
+ this.options.push(versionOption);
2483
+ this.on("option:" + versionOption.name(), () => {
2484
+ this._outputConfiguration.writeOut(`${str}
2485
+ `);
2486
+ this._exit(0, "commander.version", str);
2487
+ });
2488
+ return this;
2489
+ }
2490
+ /**
2491
+ * Set the description.
2492
+ *
2493
+ * @param {string} [str]
2494
+ * @param {Object} [argsDescription]
2495
+ * @return {string|Command}
2496
+ */
2497
+ description(str, argsDescription) {
2498
+ if (str === void 0 && argsDescription === void 0)
2499
+ return this._description;
2500
+ this._description = str;
2501
+ if (argsDescription) {
2502
+ this._argsDescription = argsDescription;
2503
+ }
2504
+ return this;
2505
+ }
2506
+ /**
2507
+ * Set the summary. Used when listed as subcommand of parent.
2508
+ *
2509
+ * @param {string} [str]
2510
+ * @return {string|Command}
2511
+ */
2512
+ summary(str) {
2513
+ if (str === void 0)
2514
+ return this._summary;
2515
+ this._summary = str;
2516
+ return this;
2517
+ }
2518
+ /**
2519
+ * Set an alias for the command.
2520
+ *
2521
+ * You may call more than once to add multiple aliases. Only the first alias is shown in the auto-generated help.
2522
+ *
2523
+ * @param {string} [alias]
2524
+ * @return {string|Command}
2525
+ */
2526
+ alias(alias) {
2527
+ if (alias === void 0)
2528
+ return this._aliases[0];
2529
+ let command = this;
2530
+ if (this.commands.length !== 0 && this.commands[this.commands.length - 1]._executableHandler) {
2531
+ command = this.commands[this.commands.length - 1];
2532
+ }
2533
+ if (alias === command._name)
2534
+ throw new Error("Command alias can't be the same as its name");
2535
+ command._aliases.push(alias);
2536
+ return this;
2537
+ }
2538
+ /**
2539
+ * Set aliases for the command.
2540
+ *
2541
+ * Only the first alias is shown in the auto-generated help.
2542
+ *
2543
+ * @param {string[]} [aliases]
2544
+ * @return {string[]|Command}
2545
+ */
2546
+ aliases(aliases) {
2547
+ if (aliases === void 0)
2548
+ return this._aliases;
2549
+ aliases.forEach((alias) => this.alias(alias));
2550
+ return this;
2551
+ }
2552
+ /**
2553
+ * Set / get the command usage `str`.
2554
+ *
2555
+ * @param {string} [str]
2556
+ * @return {String|Command}
2557
+ */
2558
+ usage(str) {
2559
+ if (str === void 0) {
2560
+ if (this._usage)
2561
+ return this._usage;
2562
+ const args = this._args.map((arg) => {
2563
+ return humanReadableArgName(arg);
2564
+ });
2565
+ return [].concat(
2566
+ this.options.length || this._hasHelpOption ? "[options]" : [],
2567
+ this.commands.length ? "[command]" : [],
2568
+ this._args.length ? args : []
2569
+ ).join(" ");
2570
+ }
2571
+ this._usage = str;
2572
+ return this;
2573
+ }
2574
+ /**
2575
+ * Get or set the name of the command.
2576
+ *
2577
+ * @param {string} [str]
2578
+ * @return {string|Command}
2579
+ */
2580
+ name(str) {
2581
+ if (str === void 0)
2582
+ return this._name;
2583
+ this._name = str;
2584
+ return this;
2585
+ }
2586
+ /**
2587
+ * Set the name of the command from script filename, such as process.argv[1],
2588
+ * or require.main.filename, or __filename.
2589
+ *
2590
+ * (Used internally and public although not documented in README.)
2591
+ *
2592
+ * @example
2593
+ * program.nameFromFilename(require.main.filename);
2594
+ *
2595
+ * @param {string} filename
2596
+ * @return {Command}
2597
+ */
2598
+ nameFromFilename(filename) {
2599
+ this._name = path.basename(filename, path.extname(filename));
2600
+ return this;
2601
+ }
2602
+ /**
2603
+ * Get or set the directory for searching for executable subcommands of this command.
2604
+ *
2605
+ * @example
2606
+ * program.executableDir(__dirname);
2607
+ * // or
2608
+ * program.executableDir('subcommands');
2609
+ *
2610
+ * @param {string} [path]
2611
+ * @return {string|Command}
2612
+ */
2613
+ executableDir(path2) {
2614
+ if (path2 === void 0)
2615
+ return this._executableDir;
2616
+ this._executableDir = path2;
2617
+ return this;
2618
+ }
2619
+ /**
2620
+ * Return program help documentation.
2621
+ *
2622
+ * @param {{ error: boolean }} [contextOptions] - pass {error:true} to wrap for stderr instead of stdout
2623
+ * @return {string}
2624
+ */
2625
+ helpInformation(contextOptions) {
2626
+ const helper = this.createHelp();
2627
+ if (helper.helpWidth === void 0) {
2628
+ helper.helpWidth = contextOptions && contextOptions.error ? this._outputConfiguration.getErrHelpWidth() : this._outputConfiguration.getOutHelpWidth();
2629
+ }
2630
+ return helper.formatHelp(this, helper);
2631
+ }
2632
+ /**
2633
+ * @api private
2634
+ */
2635
+ _getHelpContext(contextOptions) {
2636
+ contextOptions = contextOptions || {};
2637
+ const context = { error: !!contextOptions.error };
2638
+ let write;
2639
+ if (context.error) {
2640
+ write = (arg) => this._outputConfiguration.writeErr(arg);
2641
+ } else {
2642
+ write = (arg) => this._outputConfiguration.writeOut(arg);
2643
+ }
2644
+ context.write = contextOptions.write || write;
2645
+ context.command = this;
2646
+ return context;
2647
+ }
2648
+ /**
2649
+ * Output help information for this command.
2650
+ *
2651
+ * Outputs built-in help, and custom text added using `.addHelpText()`.
2652
+ *
2653
+ * @param {{ error: boolean } | Function} [contextOptions] - pass {error:true} to write to stderr instead of stdout
2654
+ */
2655
+ outputHelp(contextOptions) {
2656
+ let deprecatedCallback;
2657
+ if (typeof contextOptions === "function") {
2658
+ deprecatedCallback = contextOptions;
2659
+ contextOptions = void 0;
2660
+ }
2661
+ const context = this._getHelpContext(contextOptions);
2662
+ getCommandAndParents(this).reverse().forEach((command) => command.emit("beforeAllHelp", context));
2663
+ this.emit("beforeHelp", context);
2664
+ let helpInformation = this.helpInformation(context);
2665
+ if (deprecatedCallback) {
2666
+ helpInformation = deprecatedCallback(helpInformation);
2667
+ if (typeof helpInformation !== "string" && !Buffer.isBuffer(helpInformation)) {
2668
+ throw new Error("outputHelp callback must return a string or a Buffer");
2669
+ }
2670
+ }
2671
+ context.write(helpInformation);
2672
+ this.emit(this._helpLongFlag);
2673
+ this.emit("afterHelp", context);
2674
+ getCommandAndParents(this).forEach((command) => command.emit("afterAllHelp", context));
2675
+ }
2676
+ /**
2677
+ * You can pass in flags and a description to override the help
2678
+ * flags and help description for your command. Pass in false to
2679
+ * disable the built-in help option.
2680
+ *
2681
+ * @param {string | boolean} [flags]
2682
+ * @param {string} [description]
2683
+ * @return {Command} `this` command for chaining
2684
+ */
2685
+ helpOption(flags, description) {
2686
+ if (typeof flags === "boolean") {
2687
+ this._hasHelpOption = flags;
2688
+ return this;
2689
+ }
2690
+ this._helpFlags = flags || this._helpFlags;
2691
+ this._helpDescription = description || this._helpDescription;
2692
+ const helpFlags = splitOptionFlags(this._helpFlags);
2693
+ this._helpShortFlag = helpFlags.shortFlag;
2694
+ this._helpLongFlag = helpFlags.longFlag;
2695
+ return this;
2696
+ }
2697
+ /**
2698
+ * Output help information and exit.
2699
+ *
2700
+ * Outputs built-in help, and custom text added using `.addHelpText()`.
2701
+ *
2702
+ * @param {{ error: boolean }} [contextOptions] - pass {error:true} to write to stderr instead of stdout
2703
+ */
2704
+ help(contextOptions) {
2705
+ this.outputHelp(contextOptions);
2706
+ let exitCode = process2.exitCode || 0;
2707
+ if (exitCode === 0 && contextOptions && typeof contextOptions !== "function" && contextOptions.error) {
2708
+ exitCode = 1;
2709
+ }
2710
+ this._exit(exitCode, "commander.help", "(outputHelp)");
2711
+ }
2712
+ /**
2713
+ * Add additional text to be displayed with the built-in help.
2714
+ *
2715
+ * Position is 'before' or 'after' to affect just this command,
2716
+ * and 'beforeAll' or 'afterAll' to affect this command and all its subcommands.
2717
+ *
2718
+ * @param {string} position - before or after built-in help
2719
+ * @param {string | Function} text - string to add, or a function returning a string
2720
+ * @return {Command} `this` command for chaining
2721
+ */
2722
+ addHelpText(position, text) {
2723
+ const allowedValues = ["beforeAll", "before", "after", "afterAll"];
2724
+ if (!allowedValues.includes(position)) {
2725
+ throw new Error(`Unexpected value for position to addHelpText.
2726
+ Expecting one of '${allowedValues.join("', '")}'`);
2727
+ }
2728
+ const helpEvent = `${position}Help`;
2729
+ this.on(helpEvent, (context) => {
2730
+ let helpStr;
2731
+ if (typeof text === "function") {
2732
+ helpStr = text({ error: context.error, command: context.command });
2733
+ } else {
2734
+ helpStr = text;
2735
+ }
2736
+ if (helpStr) {
2737
+ context.write(`${helpStr}
2738
+ `);
2739
+ }
2740
+ });
2741
+ return this;
2742
+ }
2743
+ };
2744
+ function outputHelpIfRequested(cmd, args) {
2745
+ const helpOption = cmd._hasHelpOption && args.find((arg) => arg === cmd._helpLongFlag || arg === cmd._helpShortFlag);
2746
+ if (helpOption) {
2747
+ cmd.outputHelp();
2748
+ cmd._exit(0, "commander.helpDisplayed", "(outputHelp)");
2749
+ }
2750
+ }
2751
+ function incrementNodeInspectorPort(args) {
2752
+ return args.map((arg) => {
2753
+ if (!arg.startsWith("--inspect")) {
2754
+ return arg;
2755
+ }
2756
+ let debugOption;
2757
+ let debugHost = "127.0.0.1";
2758
+ let debugPort = "9229";
2759
+ let match;
2760
+ if ((match = arg.match(/^(--inspect(-brk)?)$/)) !== null) {
2761
+ debugOption = match[1];
2762
+ } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/)) !== null) {
2763
+ debugOption = match[1];
2764
+ if (/^\d+$/.test(match[3])) {
2765
+ debugPort = match[3];
2766
+ } else {
2767
+ debugHost = match[3];
2768
+ }
2769
+ } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/)) !== null) {
2770
+ debugOption = match[1];
2771
+ debugHost = match[3];
2772
+ debugPort = match[4];
2773
+ }
2774
+ if (debugOption && debugPort !== "0") {
2775
+ return `${debugOption}=${debugHost}:${parseInt(debugPort) + 1}`;
2776
+ }
2777
+ return arg;
2778
+ });
2779
+ }
2780
+ function getCommandAndParents(startCommand) {
2781
+ const result = [];
2782
+ for (let command = startCommand; command; command = command.parent) {
2783
+ result.push(command);
2784
+ }
2785
+ return result;
2786
+ }
2787
+ exports.Command = Command2;
2788
+ }
2789
+ });
2790
+
2791
+ // node_modules/commander/index.js
2792
+ var require_commander = __commonJS({
2793
+ "node_modules/commander/index.js"(exports, module2) {
2794
+ var { Argument: Argument2 } = require_argument();
2795
+ var { Command: Command2 } = require_command();
2796
+ var { CommanderError: CommanderError2, InvalidArgumentError: InvalidArgumentError2 } = require_error();
2797
+ var { Help: Help2 } = require_help();
2798
+ var { Option: Option2 } = require_option();
2799
+ exports = module2.exports = new Command2();
2800
+ exports.program = exports;
2801
+ exports.Argument = Argument2;
2802
+ exports.Command = Command2;
2803
+ exports.CommanderError = CommanderError2;
2804
+ exports.Help = Help2;
2805
+ exports.InvalidArgumentError = InvalidArgumentError2;
2806
+ exports.InvalidOptionArgumentError = InvalidArgumentError2;
2807
+ exports.Option = Option2;
2808
+ }
2809
+ });
2810
+
2811
+ // src/index.ts
2812
+ var import_child_process = require("child_process");
2813
+ var import_promises = require("fs/promises");
2814
+
2815
+ // node_modules/commander/esm.mjs
2816
+ var import_index = __toESM(require_commander(), 1);
2817
+ var {
2818
+ program,
2819
+ createCommand,
2820
+ createArgument,
2821
+ createOption,
2822
+ CommanderError,
2823
+ InvalidArgumentError,
2824
+ InvalidOptionArgumentError,
2825
+ // deprecated old name
2826
+ Command,
2827
+ Argument,
2828
+ Option,
2829
+ Help
2830
+ } = import_index.default;
2831
+
2832
+ // src/eslintConfig.json
2833
+ var eslintConfig_default = {
2834
+ extends: "@bharper7/eslint-config"
2835
+ };
2836
+
2837
+ // src/index.ts
2838
+ var program2 = new Command();
2839
+ program2.command("init").option("-d, --directory <directory>", "Directory name for project").action(init);
2840
+ program2.parseAsync(process.argv);
2841
+ async function init(opts) {
2842
+ exec(`mkdir ${opts.directory}`);
2843
+ exec("mkdir src", opts.directory);
2844
+ exec("new-item index.ts", `${opts.directory}/src`);
2845
+ exec("git init", opts.directory);
2846
+ exec("echo 'node_modules' 'dist' > .gitignore", opts.directory);
2847
+ exec("npm init -y", opts.directory);
2848
+ const packageJson = JSON.parse((await (0, import_promises.readFile)(`${opts.directory}/package.json`)).toString());
2849
+ packageJson.scripts = {
2850
+ "start": "node src/index.js",
2851
+ "build": "tsc"
2852
+ };
2853
+ await (0, import_promises.writeFile)(`${opts.directory}/package.json`, JSON.stringify(packageJson, null, 2));
2854
+ const devDependencies = [
2855
+ "typescript",
2856
+ "@types/node",
2857
+ "@total-typescript/ts-reset",
2858
+ "eslint",
2859
+ "@bharper7/eslint-config",
2860
+ "@typescript-eslint/eslint-plugin",
2861
+ "eslint-plugin-import"
2862
+ ].join(" ");
2863
+ exec(`npm i -D ${devDependencies}`, opts.directory);
2864
+ exec("tsc --init", opts.directory);
2865
+ await (0, import_promises.writeFile)(`${opts.directory}/.eslintrc.json`, JSON.stringify(eslintConfig_default));
2866
+ exec("echo 'node_modules' 'dist' > .eslintignore", opts.directory);
2867
+ }
2868
+ function exec(command, cwd) {
2869
+ return (0, import_child_process.execSync)(command, {
2870
+ cwd,
2871
+ shell: "powershell.exe"
2872
+ });
2873
+ }