sentinel-scanner 1.0.0-alpha.1

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