@hanzo/dev 1.0.0

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