codeorbit 0.10.2 → 0.10.4

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