notion-github 0.1.3 → 0.1.5

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