hive-intelligence 0.1.1 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (84) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +112 -77
  3. package/bin/hive.js +25 -0
  4. package/build/alias-INGXWFCG.js +41 -0
  5. package/build/alias-INGXWFCG.js.map +1 -0
  6. package/build/auth-PVT4GTAD.js +233 -0
  7. package/build/auth-PVT4GTAD.js.map +1 -0
  8. package/build/cache-US4LSZPI.js +52 -0
  9. package/build/cache-US4LSZPI.js.map +1 -0
  10. package/build/chunk-FAFUYZQS.js +280 -0
  11. package/build/chunk-FAFUYZQS.js.map +1 -0
  12. package/build/chunk-IWBWPHYY.js +212 -0
  13. package/build/chunk-IWBWPHYY.js.map +1 -0
  14. package/build/chunk-LBTLYTZS.js +115 -0
  15. package/build/chunk-LBTLYTZS.js.map +1 -0
  16. package/build/chunk-N43VRMVB.js +3108 -0
  17. package/build/chunk-N43VRMVB.js.map +1 -0
  18. package/build/chunk-NEKSTV6P.js +911 -0
  19. package/build/chunk-NEKSTV6P.js.map +1 -0
  20. package/build/chunk-OK3LSM73.js +22 -0
  21. package/build/chunk-OK3LSM73.js.map +1 -0
  22. package/build/chunk-QMRVH5ZP.js +44 -0
  23. package/build/chunk-QMRVH5ZP.js.map +1 -0
  24. package/build/chunk-WKVZVQTG.js +66 -0
  25. package/build/chunk-WKVZVQTG.js.map +1 -0
  26. package/build/chunk-XQJ6PB2L.js +95 -0
  27. package/build/chunk-XQJ6PB2L.js.map +1 -0
  28. package/build/cli.js +3858 -0
  29. package/build/cli.js.map +1 -0
  30. package/build/completion-N35TWBLT.js +274 -0
  31. package/build/completion-N35TWBLT.js.map +1 -0
  32. package/build/config-2VDB2ZHE.js +100 -0
  33. package/build/config-2VDB2ZHE.js.map +1 -0
  34. package/build/config-dir-IEOID7Q6.js +31 -0
  35. package/build/config-dir-IEOID7Q6.js.map +1 -0
  36. package/build/doctor-GYP6IHPP.js +231 -0
  37. package/build/doctor-GYP6IHPP.js.map +1 -0
  38. package/build/errors-HRGXEUZR.js +17 -0
  39. package/build/errors-HRGXEUZR.js.map +1 -0
  40. package/build/format-4OIUGZKY.js +43 -0
  41. package/build/format-4OIUGZKY.js.map +1 -0
  42. package/build/init-YOJK6CH2.js +102 -0
  43. package/build/init-YOJK6CH2.js.map +1 -0
  44. package/build/namespace-GWTS6U6J.js +13 -0
  45. package/build/namespace-GWTS6U6J.js.map +1 -0
  46. package/build/open-FUXYIHFO.js +37 -0
  47. package/build/open-FUXYIHFO.js.map +1 -0
  48. package/build/output-6TJ3JTZ7.js +41 -0
  49. package/build/output-6TJ3JTZ7.js.map +1 -0
  50. package/build/server.js +14763 -0
  51. package/build/server.js.map +1 -0
  52. package/build/telemetry-KNWMQURH.js +18 -0
  53. package/build/telemetry-KNWMQURH.js.map +1 -0
  54. package/build/tools-4W3GGCUC.js +178 -0
  55. package/build/tools-4W3GGCUC.js.map +1 -0
  56. package/build/version-3TZ3U4IR.js +9 -0
  57. package/build/version-3TZ3U4IR.js.map +1 -0
  58. package/build/watch-P2QWGFYV.js +67 -0
  59. package/build/watch-P2QWGFYV.js.map +1 -0
  60. package/package.json +56 -15
  61. package/.env,example +0 -1
  62. package/dist/client.d.ts +0 -7
  63. package/dist/client.js +0 -52
  64. package/dist/errors.d.ts +0 -7
  65. package/dist/errors.js +0 -15
  66. package/dist/index.d.ts +0 -3
  67. package/dist/index.js +0 -20
  68. package/dist/types.d.ts +0 -19
  69. package/dist/types.js +0 -2
  70. package/example.ts +0 -35
  71. package/jest.config.js +0 -7
  72. package/src/client.js +0 -52
  73. package/src/client.ts +0 -42
  74. package/src/errors.js +0 -15
  75. package/src/errors.ts +0 -11
  76. package/src/index.js +0 -20
  77. package/src/index.ts +0 -5
  78. package/src/types.js +0 -2
  79. package/src/types.ts +0 -21
  80. package/tests/client.test.js +0 -28
  81. package/tests/client.test.ts +0 -18
  82. package/tests/hive.test.js +0 -69
  83. package/tests/hive.test.ts +0 -63
  84. package/tsconfig.json +0 -117
package/build/cli.js ADDED
@@ -0,0 +1,3858 @@
1
+ #!/usr/bin/env node
2
+ import { createRequire } from 'node:module'; const require = createRequire(import.meta.url);
3
+ import {
4
+ executeTool
5
+ } from "./chunk-N43VRMVB.js";
6
+ import "./chunk-WKVZVQTG.js";
7
+ import "./chunk-LBTLYTZS.js";
8
+ import {
9
+ CLI_VERSION
10
+ } from "./chunk-OK3LSM73.js";
11
+ import {
12
+ red,
13
+ setOutputOptions
14
+ } from "./chunk-FAFUYZQS.js";
15
+ import {
16
+ ensureConfigDir,
17
+ getConfigDir,
18
+ readJsonFile,
19
+ setCliFlags,
20
+ writeJsonFile
21
+ } from "./chunk-XQJ6PB2L.js";
22
+ import {
23
+ ExitCode
24
+ } from "./chunk-IWBWPHYY.js";
25
+ import {
26
+ NAMESPACE
27
+ } from "./chunk-NEKSTV6P.js";
28
+ import {
29
+ __commonJS,
30
+ __require,
31
+ __toESM
32
+ } from "./chunk-QMRVH5ZP.js";
33
+
34
+ // node_modules/commander/lib/error.js
35
+ var require_error = __commonJS({
36
+ "node_modules/commander/lib/error.js"(exports) {
37
+ "use strict";
38
+ var CommanderError2 = class extends Error {
39
+ /**
40
+ * Constructs the CommanderError class
41
+ * @param {number} exitCode suggested exit code which could be used with process.exit
42
+ * @param {string} code an id string representing the error
43
+ * @param {string} message human-readable description of the error
44
+ */
45
+ constructor(exitCode, code, message) {
46
+ super(message);
47
+ Error.captureStackTrace(this, this.constructor);
48
+ this.name = this.constructor.name;
49
+ this.code = code;
50
+ this.exitCode = exitCode;
51
+ this.nestedError = void 0;
52
+ }
53
+ };
54
+ var InvalidArgumentError2 = class extends CommanderError2 {
55
+ /**
56
+ * Constructs the InvalidArgumentError class
57
+ * @param {string} [message] explanation of why argument is invalid
58
+ */
59
+ constructor(message) {
60
+ super(1, "commander.invalidArgument", message);
61
+ Error.captureStackTrace(this, this.constructor);
62
+ this.name = this.constructor.name;
63
+ }
64
+ };
65
+ exports.CommanderError = CommanderError2;
66
+ exports.InvalidArgumentError = InvalidArgumentError2;
67
+ }
68
+ });
69
+
70
+ // node_modules/commander/lib/argument.js
71
+ var require_argument = __commonJS({
72
+ "node_modules/commander/lib/argument.js"(exports) {
73
+ "use strict";
74
+ var { InvalidArgumentError: InvalidArgumentError2 } = require_error();
75
+ var Argument2 = class {
76
+ /**
77
+ * Initialize a new command argument with the given name and description.
78
+ * The default is that the argument is required, and you can explicitly
79
+ * indicate this with <> around the name. Put [] around the name for an optional argument.
80
+ *
81
+ * @param {string} name
82
+ * @param {string} [description]
83
+ */
84
+ constructor(name, description) {
85
+ this.description = description || "";
86
+ this.variadic = false;
87
+ this.parseArg = void 0;
88
+ this.defaultValue = void 0;
89
+ this.defaultValueDescription = void 0;
90
+ this.argChoices = void 0;
91
+ switch (name[0]) {
92
+ case "<":
93
+ this.required = true;
94
+ this._name = name.slice(1, -1);
95
+ break;
96
+ case "[":
97
+ this.required = false;
98
+ this._name = name.slice(1, -1);
99
+ break;
100
+ default:
101
+ this.required = true;
102
+ this._name = name;
103
+ break;
104
+ }
105
+ if (this._name.endsWith("...")) {
106
+ this.variadic = true;
107
+ this._name = this._name.slice(0, -3);
108
+ }
109
+ }
110
+ /**
111
+ * Return argument name.
112
+ *
113
+ * @return {string}
114
+ */
115
+ name() {
116
+ return this._name;
117
+ }
118
+ /**
119
+ * @package
120
+ */
121
+ _collectValue(value, previous) {
122
+ if (previous === this.defaultValue || !Array.isArray(previous)) {
123
+ return [value];
124
+ }
125
+ previous.push(value);
126
+ return previous;
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._collectValue(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.minWidthToWrap = 40;
208
+ this.sortSubcommands = false;
209
+ this.sortOptions = false;
210
+ this.showGlobalOptions = false;
211
+ }
212
+ /**
213
+ * prepareContext is called by Commander after applying overrides from `Command.configureHelp()`
214
+ * and just before calling `formatHelp()`.
215
+ *
216
+ * Commander just uses the helpWidth and the rest is provided for optional use by more complex subclasses.
217
+ *
218
+ * @param {{ error?: boolean, helpWidth?: number, outputHasColors?: boolean }} contextOptions
219
+ */
220
+ prepareContext(contextOptions) {
221
+ this.helpWidth = this.helpWidth ?? contextOptions.helpWidth ?? 80;
222
+ }
223
+ /**
224
+ * Get an array of the visible subcommands. Includes a placeholder for the implicit help command, if there is one.
225
+ *
226
+ * @param {Command} cmd
227
+ * @returns {Command[]}
228
+ */
229
+ visibleCommands(cmd) {
230
+ const visibleCommands = cmd.commands.filter((cmd2) => !cmd2._hidden);
231
+ const helpCommand = cmd._getHelpCommand();
232
+ if (helpCommand && !helpCommand._hidden) {
233
+ visibleCommands.push(helpCommand);
234
+ }
235
+ if (this.sortSubcommands) {
236
+ visibleCommands.sort((a, b) => {
237
+ return a.name().localeCompare(b.name());
238
+ });
239
+ }
240
+ return visibleCommands;
241
+ }
242
+ /**
243
+ * Compare options for sort.
244
+ *
245
+ * @param {Option} a
246
+ * @param {Option} b
247
+ * @returns {number}
248
+ */
249
+ compareOptions(a, b) {
250
+ const getSortKey = (option) => {
251
+ return option.short ? option.short.replace(/^-/, "") : option.long.replace(/^--/, "");
252
+ };
253
+ return getSortKey(a).localeCompare(getSortKey(b));
254
+ }
255
+ /**
256
+ * Get an array of the visible options. Includes a placeholder for the implicit help option, if there is one.
257
+ *
258
+ * @param {Command} cmd
259
+ * @returns {Option[]}
260
+ */
261
+ visibleOptions(cmd) {
262
+ const visibleOptions = cmd.options.filter((option) => !option.hidden);
263
+ const helpOption = cmd._getHelpOption();
264
+ if (helpOption && !helpOption.hidden) {
265
+ const removeShort = helpOption.short && cmd._findOption(helpOption.short);
266
+ const removeLong = helpOption.long && cmd._findOption(helpOption.long);
267
+ if (!removeShort && !removeLong) {
268
+ visibleOptions.push(helpOption);
269
+ } else if (helpOption.long && !removeLong) {
270
+ visibleOptions.push(
271
+ cmd.createOption(helpOption.long, helpOption.description)
272
+ );
273
+ } else if (helpOption.short && !removeShort) {
274
+ visibleOptions.push(
275
+ cmd.createOption(helpOption.short, helpOption.description)
276
+ );
277
+ }
278
+ }
279
+ if (this.sortOptions) {
280
+ visibleOptions.sort(this.compareOptions);
281
+ }
282
+ return visibleOptions;
283
+ }
284
+ /**
285
+ * Get an array of the visible global options. (Not including help.)
286
+ *
287
+ * @param {Command} cmd
288
+ * @returns {Option[]}
289
+ */
290
+ visibleGlobalOptions(cmd) {
291
+ if (!this.showGlobalOptions) return [];
292
+ const globalOptions = [];
293
+ for (let ancestorCmd = cmd.parent; ancestorCmd; ancestorCmd = ancestorCmd.parent) {
294
+ const visibleOptions = ancestorCmd.options.filter(
295
+ (option) => !option.hidden
296
+ );
297
+ globalOptions.push(...visibleOptions);
298
+ }
299
+ if (this.sortOptions) {
300
+ globalOptions.sort(this.compareOptions);
301
+ }
302
+ return globalOptions;
303
+ }
304
+ /**
305
+ * Get an array of the arguments if any have a description.
306
+ *
307
+ * @param {Command} cmd
308
+ * @returns {Argument[]}
309
+ */
310
+ visibleArguments(cmd) {
311
+ if (cmd._argsDescription) {
312
+ cmd.registeredArguments.forEach((argument) => {
313
+ argument.description = argument.description || cmd._argsDescription[argument.name()] || "";
314
+ });
315
+ }
316
+ if (cmd.registeredArguments.find((argument) => argument.description)) {
317
+ return cmd.registeredArguments;
318
+ }
319
+ return [];
320
+ }
321
+ /**
322
+ * Get the command term to show in the list of subcommands.
323
+ *
324
+ * @param {Command} cmd
325
+ * @returns {string}
326
+ */
327
+ subcommandTerm(cmd) {
328
+ const args = cmd.registeredArguments.map((arg) => humanReadableArgName(arg)).join(" ");
329
+ return cmd._name + (cmd._aliases[0] ? "|" + cmd._aliases[0] : "") + (cmd.options.length ? " [options]" : "") + // simplistic check for non-help option
330
+ (args ? " " + args : "");
331
+ }
332
+ /**
333
+ * Get the option term to show in the list of options.
334
+ *
335
+ * @param {Option} option
336
+ * @returns {string}
337
+ */
338
+ optionTerm(option) {
339
+ return option.flags;
340
+ }
341
+ /**
342
+ * Get the argument term to show in the list of arguments.
343
+ *
344
+ * @param {Argument} argument
345
+ * @returns {string}
346
+ */
347
+ argumentTerm(argument) {
348
+ return argument.name();
349
+ }
350
+ /**
351
+ * Get the longest command term length.
352
+ *
353
+ * @param {Command} cmd
354
+ * @param {Help} helper
355
+ * @returns {number}
356
+ */
357
+ longestSubcommandTermLength(cmd, helper) {
358
+ return helper.visibleCommands(cmd).reduce((max, command) => {
359
+ return Math.max(
360
+ max,
361
+ this.displayWidth(
362
+ helper.styleSubcommandTerm(helper.subcommandTerm(command))
363
+ )
364
+ );
365
+ }, 0);
366
+ }
367
+ /**
368
+ * Get the longest option term length.
369
+ *
370
+ * @param {Command} cmd
371
+ * @param {Help} helper
372
+ * @returns {number}
373
+ */
374
+ longestOptionTermLength(cmd, helper) {
375
+ return helper.visibleOptions(cmd).reduce((max, option) => {
376
+ return Math.max(
377
+ max,
378
+ this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option)))
379
+ );
380
+ }, 0);
381
+ }
382
+ /**
383
+ * Get the longest global option term length.
384
+ *
385
+ * @param {Command} cmd
386
+ * @param {Help} helper
387
+ * @returns {number}
388
+ */
389
+ longestGlobalOptionTermLength(cmd, helper) {
390
+ return helper.visibleGlobalOptions(cmd).reduce((max, option) => {
391
+ return Math.max(
392
+ max,
393
+ this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option)))
394
+ );
395
+ }, 0);
396
+ }
397
+ /**
398
+ * Get the longest argument term length.
399
+ *
400
+ * @param {Command} cmd
401
+ * @param {Help} helper
402
+ * @returns {number}
403
+ */
404
+ longestArgumentTermLength(cmd, helper) {
405
+ return helper.visibleArguments(cmd).reduce((max, argument) => {
406
+ return Math.max(
407
+ max,
408
+ this.displayWidth(
409
+ helper.styleArgumentTerm(helper.argumentTerm(argument))
410
+ )
411
+ );
412
+ }, 0);
413
+ }
414
+ /**
415
+ * Get the command usage to be displayed at the top of the built-in help.
416
+ *
417
+ * @param {Command} cmd
418
+ * @returns {string}
419
+ */
420
+ commandUsage(cmd) {
421
+ let cmdName = cmd._name;
422
+ if (cmd._aliases[0]) {
423
+ cmdName = cmdName + "|" + cmd._aliases[0];
424
+ }
425
+ let ancestorCmdNames = "";
426
+ for (let ancestorCmd = cmd.parent; ancestorCmd; ancestorCmd = ancestorCmd.parent) {
427
+ ancestorCmdNames = ancestorCmd.name() + " " + ancestorCmdNames;
428
+ }
429
+ return ancestorCmdNames + cmdName + " " + cmd.usage();
430
+ }
431
+ /**
432
+ * Get the description for the command.
433
+ *
434
+ * @param {Command} cmd
435
+ * @returns {string}
436
+ */
437
+ commandDescription(cmd) {
438
+ return cmd.description();
439
+ }
440
+ /**
441
+ * Get the subcommand summary to show in the list of subcommands.
442
+ * (Fallback to description for backwards compatibility.)
443
+ *
444
+ * @param {Command} cmd
445
+ * @returns {string}
446
+ */
447
+ subcommandDescription(cmd) {
448
+ return cmd.summary() || cmd.description();
449
+ }
450
+ /**
451
+ * Get the option description to show in the list of options.
452
+ *
453
+ * @param {Option} option
454
+ * @return {string}
455
+ */
456
+ optionDescription(option) {
457
+ const extraInfo = [];
458
+ if (option.argChoices) {
459
+ extraInfo.push(
460
+ // use stringify to match the display of the default value
461
+ `choices: ${option.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`
462
+ );
463
+ }
464
+ if (option.defaultValue !== void 0) {
465
+ const showDefault = option.required || option.optional || option.isBoolean() && typeof option.defaultValue === "boolean";
466
+ if (showDefault) {
467
+ extraInfo.push(
468
+ `default: ${option.defaultValueDescription || JSON.stringify(option.defaultValue)}`
469
+ );
470
+ }
471
+ }
472
+ if (option.presetArg !== void 0 && option.optional) {
473
+ extraInfo.push(`preset: ${JSON.stringify(option.presetArg)}`);
474
+ }
475
+ if (option.envVar !== void 0) {
476
+ extraInfo.push(`env: ${option.envVar}`);
477
+ }
478
+ if (extraInfo.length > 0) {
479
+ const extraDescription = `(${extraInfo.join(", ")})`;
480
+ if (option.description) {
481
+ return `${option.description} ${extraDescription}`;
482
+ }
483
+ return extraDescription;
484
+ }
485
+ return option.description;
486
+ }
487
+ /**
488
+ * Get the argument description to show in the list of arguments.
489
+ *
490
+ * @param {Argument} argument
491
+ * @return {string}
492
+ */
493
+ argumentDescription(argument) {
494
+ const extraInfo = [];
495
+ if (argument.argChoices) {
496
+ extraInfo.push(
497
+ // use stringify to match the display of the default value
498
+ `choices: ${argument.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`
499
+ );
500
+ }
501
+ if (argument.defaultValue !== void 0) {
502
+ extraInfo.push(
503
+ `default: ${argument.defaultValueDescription || JSON.stringify(argument.defaultValue)}`
504
+ );
505
+ }
506
+ if (extraInfo.length > 0) {
507
+ const extraDescription = `(${extraInfo.join(", ")})`;
508
+ if (argument.description) {
509
+ return `${argument.description} ${extraDescription}`;
510
+ }
511
+ return extraDescription;
512
+ }
513
+ return argument.description;
514
+ }
515
+ /**
516
+ * Format a list of items, given a heading and an array of formatted items.
517
+ *
518
+ * @param {string} heading
519
+ * @param {string[]} items
520
+ * @param {Help} helper
521
+ * @returns string[]
522
+ */
523
+ formatItemList(heading, items, helper) {
524
+ if (items.length === 0) return [];
525
+ return [helper.styleTitle(heading), ...items, ""];
526
+ }
527
+ /**
528
+ * Group items by their help group heading.
529
+ *
530
+ * @param {Command[] | Option[]} unsortedItems
531
+ * @param {Command[] | Option[]} visibleItems
532
+ * @param {Function} getGroup
533
+ * @returns {Map<string, Command[] | Option[]>}
534
+ */
535
+ groupItems(unsortedItems, visibleItems, getGroup) {
536
+ const result = /* @__PURE__ */ new Map();
537
+ unsortedItems.forEach((item) => {
538
+ const group = getGroup(item);
539
+ if (!result.has(group)) result.set(group, []);
540
+ });
541
+ visibleItems.forEach((item) => {
542
+ const group = getGroup(item);
543
+ if (!result.has(group)) {
544
+ result.set(group, []);
545
+ }
546
+ result.get(group).push(item);
547
+ });
548
+ return result;
549
+ }
550
+ /**
551
+ * Generate the built-in help text.
552
+ *
553
+ * @param {Command} cmd
554
+ * @param {Help} helper
555
+ * @returns {string}
556
+ */
557
+ formatHelp(cmd, helper) {
558
+ const termWidth = helper.padWidth(cmd, helper);
559
+ const helpWidth = helper.helpWidth ?? 80;
560
+ function callFormatItem(term, description) {
561
+ return helper.formatItem(term, termWidth, description, helper);
562
+ }
563
+ let output = [
564
+ `${helper.styleTitle("Usage:")} ${helper.styleUsage(helper.commandUsage(cmd))}`,
565
+ ""
566
+ ];
567
+ const commandDescription = helper.commandDescription(cmd);
568
+ if (commandDescription.length > 0) {
569
+ output = output.concat([
570
+ helper.boxWrap(
571
+ helper.styleCommandDescription(commandDescription),
572
+ helpWidth
573
+ ),
574
+ ""
575
+ ]);
576
+ }
577
+ const argumentList = helper.visibleArguments(cmd).map((argument) => {
578
+ return callFormatItem(
579
+ helper.styleArgumentTerm(helper.argumentTerm(argument)),
580
+ helper.styleArgumentDescription(helper.argumentDescription(argument))
581
+ );
582
+ });
583
+ output = output.concat(
584
+ this.formatItemList("Arguments:", argumentList, helper)
585
+ );
586
+ const optionGroups = this.groupItems(
587
+ cmd.options,
588
+ helper.visibleOptions(cmd),
589
+ (option) => option.helpGroupHeading ?? "Options:"
590
+ );
591
+ optionGroups.forEach((options, group) => {
592
+ const optionList = options.map((option) => {
593
+ return callFormatItem(
594
+ helper.styleOptionTerm(helper.optionTerm(option)),
595
+ helper.styleOptionDescription(helper.optionDescription(option))
596
+ );
597
+ });
598
+ output = output.concat(this.formatItemList(group, optionList, helper));
599
+ });
600
+ if (helper.showGlobalOptions) {
601
+ const globalOptionList = helper.visibleGlobalOptions(cmd).map((option) => {
602
+ return callFormatItem(
603
+ helper.styleOptionTerm(helper.optionTerm(option)),
604
+ helper.styleOptionDescription(helper.optionDescription(option))
605
+ );
606
+ });
607
+ output = output.concat(
608
+ this.formatItemList("Global Options:", globalOptionList, helper)
609
+ );
610
+ }
611
+ const commandGroups = this.groupItems(
612
+ cmd.commands,
613
+ helper.visibleCommands(cmd),
614
+ (sub) => sub.helpGroup() || "Commands:"
615
+ );
616
+ commandGroups.forEach((commands, group) => {
617
+ const commandList = commands.map((sub) => {
618
+ return callFormatItem(
619
+ helper.styleSubcommandTerm(helper.subcommandTerm(sub)),
620
+ helper.styleSubcommandDescription(helper.subcommandDescription(sub))
621
+ );
622
+ });
623
+ output = output.concat(this.formatItemList(group, commandList, helper));
624
+ });
625
+ return output.join("\n");
626
+ }
627
+ /**
628
+ * Return display width of string, ignoring ANSI escape sequences. Used in padding and wrapping calculations.
629
+ *
630
+ * @param {string} str
631
+ * @returns {number}
632
+ */
633
+ displayWidth(str) {
634
+ return stripColor(str).length;
635
+ }
636
+ /**
637
+ * Style the title for displaying in the help. Called with 'Usage:', 'Options:', etc.
638
+ *
639
+ * @param {string} str
640
+ * @returns {string}
641
+ */
642
+ styleTitle(str) {
643
+ return str;
644
+ }
645
+ styleUsage(str) {
646
+ return str.split(" ").map((word) => {
647
+ if (word === "[options]") return this.styleOptionText(word);
648
+ if (word === "[command]") return this.styleSubcommandText(word);
649
+ if (word[0] === "[" || word[0] === "<")
650
+ return this.styleArgumentText(word);
651
+ return this.styleCommandText(word);
652
+ }).join(" ");
653
+ }
654
+ styleCommandDescription(str) {
655
+ return this.styleDescriptionText(str);
656
+ }
657
+ styleOptionDescription(str) {
658
+ return this.styleDescriptionText(str);
659
+ }
660
+ styleSubcommandDescription(str) {
661
+ return this.styleDescriptionText(str);
662
+ }
663
+ styleArgumentDescription(str) {
664
+ return this.styleDescriptionText(str);
665
+ }
666
+ styleDescriptionText(str) {
667
+ return str;
668
+ }
669
+ styleOptionTerm(str) {
670
+ return this.styleOptionText(str);
671
+ }
672
+ styleSubcommandTerm(str) {
673
+ return str.split(" ").map((word) => {
674
+ if (word === "[options]") return this.styleOptionText(word);
675
+ if (word[0] === "[" || word[0] === "<")
676
+ return this.styleArgumentText(word);
677
+ return this.styleSubcommandText(word);
678
+ }).join(" ");
679
+ }
680
+ styleArgumentTerm(str) {
681
+ return this.styleArgumentText(str);
682
+ }
683
+ styleOptionText(str) {
684
+ return str;
685
+ }
686
+ styleArgumentText(str) {
687
+ return str;
688
+ }
689
+ styleSubcommandText(str) {
690
+ return str;
691
+ }
692
+ styleCommandText(str) {
693
+ return str;
694
+ }
695
+ /**
696
+ * Calculate the pad width from the maximum term length.
697
+ *
698
+ * @param {Command} cmd
699
+ * @param {Help} helper
700
+ * @returns {number}
701
+ */
702
+ padWidth(cmd, helper) {
703
+ return Math.max(
704
+ helper.longestOptionTermLength(cmd, helper),
705
+ helper.longestGlobalOptionTermLength(cmd, helper),
706
+ helper.longestSubcommandTermLength(cmd, helper),
707
+ helper.longestArgumentTermLength(cmd, helper)
708
+ );
709
+ }
710
+ /**
711
+ * Detect manually wrapped and indented strings by checking for line break followed by whitespace.
712
+ *
713
+ * @param {string} str
714
+ * @returns {boolean}
715
+ */
716
+ preformatted(str) {
717
+ return /\n[^\S\r\n]/.test(str);
718
+ }
719
+ /**
720
+ * Format the "item", which consists of a term and description. Pad the term and wrap the description, indenting the following lines.
721
+ *
722
+ * So "TTT", 5, "DDD DDDD DD DDD" might be formatted for this.helpWidth=17 like so:
723
+ * TTT DDD DDDD
724
+ * DD DDD
725
+ *
726
+ * @param {string} term
727
+ * @param {number} termWidth
728
+ * @param {string} description
729
+ * @param {Help} helper
730
+ * @returns {string}
731
+ */
732
+ formatItem(term, termWidth, description, helper) {
733
+ const itemIndent = 2;
734
+ const itemIndentStr = " ".repeat(itemIndent);
735
+ if (!description) return itemIndentStr + term;
736
+ const paddedTerm = term.padEnd(
737
+ termWidth + term.length - helper.displayWidth(term)
738
+ );
739
+ const spacerWidth = 2;
740
+ const helpWidth = this.helpWidth ?? 80;
741
+ const remainingWidth = helpWidth - termWidth - spacerWidth - itemIndent;
742
+ let formattedDescription;
743
+ if (remainingWidth < this.minWidthToWrap || helper.preformatted(description)) {
744
+ formattedDescription = description;
745
+ } else {
746
+ const wrappedDescription = helper.boxWrap(description, remainingWidth);
747
+ formattedDescription = wrappedDescription.replace(
748
+ /\n/g,
749
+ "\n" + " ".repeat(termWidth + spacerWidth)
750
+ );
751
+ }
752
+ return itemIndentStr + paddedTerm + " ".repeat(spacerWidth) + formattedDescription.replace(/\n/g, `
753
+ ${itemIndentStr}`);
754
+ }
755
+ /**
756
+ * Wrap a string at whitespace, preserving existing line breaks.
757
+ * Wrapping is skipped if the width is less than `minWidthToWrap`.
758
+ *
759
+ * @param {string} str
760
+ * @param {number} width
761
+ * @returns {string}
762
+ */
763
+ boxWrap(str, width) {
764
+ if (width < this.minWidthToWrap) return str;
765
+ const rawLines = str.split(/\r\n|\n/);
766
+ const chunkPattern = /[\s]*[^\s]+/g;
767
+ const wrappedLines = [];
768
+ rawLines.forEach((line) => {
769
+ const chunks = line.match(chunkPattern);
770
+ if (chunks === null) {
771
+ wrappedLines.push("");
772
+ return;
773
+ }
774
+ let sumChunks = [chunks.shift()];
775
+ let sumWidth = this.displayWidth(sumChunks[0]);
776
+ chunks.forEach((chunk) => {
777
+ const visibleWidth = this.displayWidth(chunk);
778
+ if (sumWidth + visibleWidth <= width) {
779
+ sumChunks.push(chunk);
780
+ sumWidth += visibleWidth;
781
+ return;
782
+ }
783
+ wrappedLines.push(sumChunks.join(""));
784
+ const nextChunk = chunk.trimStart();
785
+ sumChunks = [nextChunk];
786
+ sumWidth = this.displayWidth(nextChunk);
787
+ });
788
+ wrappedLines.push(sumChunks.join(""));
789
+ });
790
+ return wrappedLines.join("\n");
791
+ }
792
+ };
793
+ function stripColor(str) {
794
+ const sgrPattern = /\x1b\[\d*(;\d*)*m/g;
795
+ return str.replace(sgrPattern, "");
796
+ }
797
+ exports.Help = Help2;
798
+ exports.stripColor = stripColor;
799
+ }
800
+ });
801
+
802
+ // node_modules/commander/lib/option.js
803
+ var require_option = __commonJS({
804
+ "node_modules/commander/lib/option.js"(exports) {
805
+ "use strict";
806
+ var { InvalidArgumentError: InvalidArgumentError2 } = require_error();
807
+ var Option2 = class {
808
+ /**
809
+ * Initialize a new `Option` with the given `flags` and `description`.
810
+ *
811
+ * @param {string} flags
812
+ * @param {string} [description]
813
+ */
814
+ constructor(flags, description) {
815
+ this.flags = flags;
816
+ this.description = description || "";
817
+ this.required = flags.includes("<");
818
+ this.optional = flags.includes("[");
819
+ this.variadic = /\w\.\.\.[>\]]$/.test(flags);
820
+ this.mandatory = false;
821
+ const optionFlags = splitOptionFlags(flags);
822
+ this.short = optionFlags.shortFlag;
823
+ this.long = optionFlags.longFlag;
824
+ this.negate = false;
825
+ if (this.long) {
826
+ this.negate = this.long.startsWith("--no-");
827
+ }
828
+ this.defaultValue = void 0;
829
+ this.defaultValueDescription = void 0;
830
+ this.presetArg = void 0;
831
+ this.envVar = void 0;
832
+ this.parseArg = void 0;
833
+ this.hidden = false;
834
+ this.argChoices = void 0;
835
+ this.conflictsWith = [];
836
+ this.implied = void 0;
837
+ this.helpGroupHeading = void 0;
838
+ }
839
+ /**
840
+ * Set the default value, and optionally supply the description to be displayed in the help.
841
+ *
842
+ * @param {*} value
843
+ * @param {string} [description]
844
+ * @return {Option}
845
+ */
846
+ default(value, description) {
847
+ this.defaultValue = value;
848
+ this.defaultValueDescription = description;
849
+ return this;
850
+ }
851
+ /**
852
+ * Preset to use when option used without option-argument, especially optional but also boolean and negated.
853
+ * The custom processing (parseArg) is called.
854
+ *
855
+ * @example
856
+ * new Option('--color').default('GREYSCALE').preset('RGB');
857
+ * new Option('--donate [amount]').preset('20').argParser(parseFloat);
858
+ *
859
+ * @param {*} arg
860
+ * @return {Option}
861
+ */
862
+ preset(arg) {
863
+ this.presetArg = arg;
864
+ return this;
865
+ }
866
+ /**
867
+ * Add option name(s) that conflict with this option.
868
+ * An error will be displayed if conflicting options are found during parsing.
869
+ *
870
+ * @example
871
+ * new Option('--rgb').conflicts('cmyk');
872
+ * new Option('--js').conflicts(['ts', 'jsx']);
873
+ *
874
+ * @param {(string | string[])} names
875
+ * @return {Option}
876
+ */
877
+ conflicts(names) {
878
+ this.conflictsWith = this.conflictsWith.concat(names);
879
+ return this;
880
+ }
881
+ /**
882
+ * Specify implied option values for when this option is set and the implied options are not.
883
+ *
884
+ * The custom processing (parseArg) is not called on the implied values.
885
+ *
886
+ * @example
887
+ * program
888
+ * .addOption(new Option('--log', 'write logging information to file'))
889
+ * .addOption(new Option('--trace', 'log extra details').implies({ log: 'trace.txt' }));
890
+ *
891
+ * @param {object} impliedOptionValues
892
+ * @return {Option}
893
+ */
894
+ implies(impliedOptionValues) {
895
+ let newImplied = impliedOptionValues;
896
+ if (typeof impliedOptionValues === "string") {
897
+ newImplied = { [impliedOptionValues]: true };
898
+ }
899
+ this.implied = Object.assign(this.implied || {}, newImplied);
900
+ return this;
901
+ }
902
+ /**
903
+ * Set environment variable to check for option value.
904
+ *
905
+ * An environment variable is only used if when processed the current option value is
906
+ * undefined, or the source of the current value is 'default' or 'config' or 'env'.
907
+ *
908
+ * @param {string} name
909
+ * @return {Option}
910
+ */
911
+ env(name) {
912
+ this.envVar = name;
913
+ return this;
914
+ }
915
+ /**
916
+ * Set the custom handler for processing CLI option arguments into option values.
917
+ *
918
+ * @param {Function} [fn]
919
+ * @return {Option}
920
+ */
921
+ argParser(fn) {
922
+ this.parseArg = fn;
923
+ return this;
924
+ }
925
+ /**
926
+ * Whether the option is mandatory and must have a value after parsing.
927
+ *
928
+ * @param {boolean} [mandatory=true]
929
+ * @return {Option}
930
+ */
931
+ makeOptionMandatory(mandatory = true) {
932
+ this.mandatory = !!mandatory;
933
+ return this;
934
+ }
935
+ /**
936
+ * Hide option in help.
937
+ *
938
+ * @param {boolean} [hide=true]
939
+ * @return {Option}
940
+ */
941
+ hideHelp(hide = true) {
942
+ this.hidden = !!hide;
943
+ return this;
944
+ }
945
+ /**
946
+ * @package
947
+ */
948
+ _collectValue(value, previous) {
949
+ if (previous === this.defaultValue || !Array.isArray(previous)) {
950
+ return [value];
951
+ }
952
+ previous.push(value);
953
+ return previous;
954
+ }
955
+ /**
956
+ * Only allow option value to be one of choices.
957
+ *
958
+ * @param {string[]} values
959
+ * @return {Option}
960
+ */
961
+ choices(values) {
962
+ this.argChoices = values.slice();
963
+ this.parseArg = (arg, previous) => {
964
+ if (!this.argChoices.includes(arg)) {
965
+ throw new InvalidArgumentError2(
966
+ `Allowed choices are ${this.argChoices.join(", ")}.`
967
+ );
968
+ }
969
+ if (this.variadic) {
970
+ return this._collectValue(arg, previous);
971
+ }
972
+ return arg;
973
+ };
974
+ return this;
975
+ }
976
+ /**
977
+ * Return option name.
978
+ *
979
+ * @return {string}
980
+ */
981
+ name() {
982
+ if (this.long) {
983
+ return this.long.replace(/^--/, "");
984
+ }
985
+ return this.short.replace(/^-/, "");
986
+ }
987
+ /**
988
+ * Return option name, in a camelcase format that can be used
989
+ * as an object attribute key.
990
+ *
991
+ * @return {string}
992
+ */
993
+ attributeName() {
994
+ if (this.negate) {
995
+ return camelcase(this.name().replace(/^no-/, ""));
996
+ }
997
+ return camelcase(this.name());
998
+ }
999
+ /**
1000
+ * Set the help group heading.
1001
+ *
1002
+ * @param {string} heading
1003
+ * @return {Option}
1004
+ */
1005
+ helpGroup(heading) {
1006
+ this.helpGroupHeading = heading;
1007
+ return this;
1008
+ }
1009
+ /**
1010
+ * Check if `arg` matches the short or long flag.
1011
+ *
1012
+ * @param {string} arg
1013
+ * @return {boolean}
1014
+ * @package
1015
+ */
1016
+ is(arg) {
1017
+ return this.short === arg || this.long === arg;
1018
+ }
1019
+ /**
1020
+ * Return whether a boolean option.
1021
+ *
1022
+ * Options are one of boolean, negated, required argument, or optional argument.
1023
+ *
1024
+ * @return {boolean}
1025
+ * @package
1026
+ */
1027
+ isBoolean() {
1028
+ return !this.required && !this.optional && !this.negate;
1029
+ }
1030
+ };
1031
+ var DualOptions = class {
1032
+ /**
1033
+ * @param {Option[]} options
1034
+ */
1035
+ constructor(options) {
1036
+ this.positiveOptions = /* @__PURE__ */ new Map();
1037
+ this.negativeOptions = /* @__PURE__ */ new Map();
1038
+ this.dualOptions = /* @__PURE__ */ new Set();
1039
+ options.forEach((option) => {
1040
+ if (option.negate) {
1041
+ this.negativeOptions.set(option.attributeName(), option);
1042
+ } else {
1043
+ this.positiveOptions.set(option.attributeName(), option);
1044
+ }
1045
+ });
1046
+ this.negativeOptions.forEach((value, key) => {
1047
+ if (this.positiveOptions.has(key)) {
1048
+ this.dualOptions.add(key);
1049
+ }
1050
+ });
1051
+ }
1052
+ /**
1053
+ * Did the value come from the option, and not from possible matching dual option?
1054
+ *
1055
+ * @param {*} value
1056
+ * @param {Option} option
1057
+ * @returns {boolean}
1058
+ */
1059
+ valueFromOption(value, option) {
1060
+ const optionKey = option.attributeName();
1061
+ if (!this.dualOptions.has(optionKey)) return true;
1062
+ const preset = this.negativeOptions.get(optionKey).presetArg;
1063
+ const negativeValue = preset !== void 0 ? preset : false;
1064
+ return option.negate === (negativeValue === value);
1065
+ }
1066
+ };
1067
+ function camelcase(str) {
1068
+ return str.split("-").reduce((str2, word) => {
1069
+ return str2 + word[0].toUpperCase() + word.slice(1);
1070
+ });
1071
+ }
1072
+ function splitOptionFlags(flags) {
1073
+ let shortFlag;
1074
+ let longFlag;
1075
+ const shortFlagExp = /^-[^-]$/;
1076
+ const longFlagExp = /^--[^-]/;
1077
+ const flagParts = flags.split(/[ |,]+/).concat("guard");
1078
+ if (shortFlagExp.test(flagParts[0])) shortFlag = flagParts.shift();
1079
+ if (longFlagExp.test(flagParts[0])) longFlag = flagParts.shift();
1080
+ if (!shortFlag && shortFlagExp.test(flagParts[0]))
1081
+ shortFlag = flagParts.shift();
1082
+ if (!shortFlag && longFlagExp.test(flagParts[0])) {
1083
+ shortFlag = longFlag;
1084
+ longFlag = flagParts.shift();
1085
+ }
1086
+ if (flagParts[0].startsWith("-")) {
1087
+ const unsupportedFlag = flagParts[0];
1088
+ const baseError = `option creation failed due to '${unsupportedFlag}' in option flags '${flags}'`;
1089
+ if (/^-[^-][^-]/.test(unsupportedFlag))
1090
+ throw new Error(
1091
+ `${baseError}
1092
+ - a short flag is a single dash and a single character
1093
+ - either use a single dash and a single character (for a short flag)
1094
+ - or use a double dash for a long option (and can have two, like '--ws, --workspace')`
1095
+ );
1096
+ if (shortFlagExp.test(unsupportedFlag))
1097
+ throw new Error(`${baseError}
1098
+ - too many short flags`);
1099
+ if (longFlagExp.test(unsupportedFlag))
1100
+ throw new Error(`${baseError}
1101
+ - too many long flags`);
1102
+ throw new Error(`${baseError}
1103
+ - unrecognised flag format`);
1104
+ }
1105
+ if (shortFlag === void 0 && longFlag === void 0)
1106
+ throw new Error(
1107
+ `option creation failed due to no flags found in '${flags}'.`
1108
+ );
1109
+ return { shortFlag, longFlag };
1110
+ }
1111
+ exports.Option = Option2;
1112
+ exports.DualOptions = DualOptions;
1113
+ }
1114
+ });
1115
+
1116
+ // node_modules/commander/lib/suggestSimilar.js
1117
+ var require_suggestSimilar = __commonJS({
1118
+ "node_modules/commander/lib/suggestSimilar.js"(exports) {
1119
+ "use strict";
1120
+ var maxDistance = 3;
1121
+ function editDistance(a, b) {
1122
+ if (Math.abs(a.length - b.length) > maxDistance)
1123
+ return Math.max(a.length, b.length);
1124
+ const d = [];
1125
+ for (let i = 0; i <= a.length; i++) {
1126
+ d[i] = [i];
1127
+ }
1128
+ for (let j = 0; j <= b.length; j++) {
1129
+ d[0][j] = j;
1130
+ }
1131
+ for (let j = 1; j <= b.length; j++) {
1132
+ for (let i = 1; i <= a.length; i++) {
1133
+ let cost = 1;
1134
+ if (a[i - 1] === b[j - 1]) {
1135
+ cost = 0;
1136
+ } else {
1137
+ cost = 1;
1138
+ }
1139
+ d[i][j] = Math.min(
1140
+ d[i - 1][j] + 1,
1141
+ // deletion
1142
+ d[i][j - 1] + 1,
1143
+ // insertion
1144
+ d[i - 1][j - 1] + cost
1145
+ // substitution
1146
+ );
1147
+ if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) {
1148
+ d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1);
1149
+ }
1150
+ }
1151
+ }
1152
+ return d[a.length][b.length];
1153
+ }
1154
+ function suggestSimilar(word, candidates) {
1155
+ if (!candidates || candidates.length === 0) return "";
1156
+ candidates = Array.from(new Set(candidates));
1157
+ const searchingOptions = word.startsWith("--");
1158
+ if (searchingOptions) {
1159
+ word = word.slice(2);
1160
+ candidates = candidates.map((candidate) => candidate.slice(2));
1161
+ }
1162
+ let similar = [];
1163
+ let bestDistance = maxDistance;
1164
+ const minSimilarity = 0.4;
1165
+ candidates.forEach((candidate) => {
1166
+ if (candidate.length <= 1) return;
1167
+ const distance = editDistance(word, candidate);
1168
+ const length = Math.max(word.length, candidate.length);
1169
+ const similarity = (length - distance) / length;
1170
+ if (similarity > minSimilarity) {
1171
+ if (distance < bestDistance) {
1172
+ bestDistance = distance;
1173
+ similar = [candidate];
1174
+ } else if (distance === bestDistance) {
1175
+ similar.push(candidate);
1176
+ }
1177
+ }
1178
+ });
1179
+ similar.sort((a, b) => a.localeCompare(b));
1180
+ if (searchingOptions) {
1181
+ similar = similar.map((candidate) => `--${candidate}`);
1182
+ }
1183
+ if (similar.length > 1) {
1184
+ return `
1185
+ (Did you mean one of ${similar.join(", ")}?)`;
1186
+ }
1187
+ if (similar.length === 1) {
1188
+ return `
1189
+ (Did you mean ${similar[0]}?)`;
1190
+ }
1191
+ return "";
1192
+ }
1193
+ exports.suggestSimilar = suggestSimilar;
1194
+ }
1195
+ });
1196
+
1197
+ // node_modules/commander/lib/command.js
1198
+ var require_command = __commonJS({
1199
+ "node_modules/commander/lib/command.js"(exports) {
1200
+ "use strict";
1201
+ var EventEmitter = __require("events").EventEmitter;
1202
+ var childProcess = __require("child_process");
1203
+ var path = __require("path");
1204
+ var fs = __require("fs");
1205
+ var process2 = __require("process");
1206
+ var { Argument: Argument2, humanReadableArgName } = require_argument();
1207
+ var { CommanderError: CommanderError2 } = require_error();
1208
+ var { Help: Help2, stripColor } = require_help();
1209
+ var { Option: Option2, DualOptions } = require_option();
1210
+ var { suggestSimilar } = require_suggestSimilar();
1211
+ var Command2 = class _Command extends EventEmitter {
1212
+ /**
1213
+ * Initialize a new `Command`.
1214
+ *
1215
+ * @param {string} [name]
1216
+ */
1217
+ constructor(name) {
1218
+ super();
1219
+ this.commands = [];
1220
+ this.options = [];
1221
+ this.parent = null;
1222
+ this._allowUnknownOption = false;
1223
+ this._allowExcessArguments = false;
1224
+ this.registeredArguments = [];
1225
+ this._args = this.registeredArguments;
1226
+ this.args = [];
1227
+ this.rawArgs = [];
1228
+ this.processedArgs = [];
1229
+ this._scriptPath = null;
1230
+ this._name = name || "";
1231
+ this._optionValues = {};
1232
+ this._optionValueSources = {};
1233
+ this._storeOptionsAsProperties = false;
1234
+ this._actionHandler = null;
1235
+ this._executableHandler = false;
1236
+ this._executableFile = null;
1237
+ this._executableDir = null;
1238
+ this._defaultCommandName = null;
1239
+ this._exitCallback = null;
1240
+ this._aliases = [];
1241
+ this._combineFlagAndOptionalValue = true;
1242
+ this._description = "";
1243
+ this._summary = "";
1244
+ this._argsDescription = void 0;
1245
+ this._enablePositionalOptions = false;
1246
+ this._passThroughOptions = false;
1247
+ this._lifeCycleHooks = {};
1248
+ this._showHelpAfterError = false;
1249
+ this._showSuggestionAfterError = true;
1250
+ this._savedState = null;
1251
+ this._outputConfiguration = {
1252
+ writeOut: (str) => process2.stdout.write(str),
1253
+ writeErr: (str) => process2.stderr.write(str),
1254
+ outputError: (str, write) => write(str),
1255
+ getOutHelpWidth: () => process2.stdout.isTTY ? process2.stdout.columns : void 0,
1256
+ getErrHelpWidth: () => process2.stderr.isTTY ? process2.stderr.columns : void 0,
1257
+ getOutHasColors: () => useColor() ?? (process2.stdout.isTTY && process2.stdout.hasColors?.()),
1258
+ getErrHasColors: () => useColor() ?? (process2.stderr.isTTY && process2.stderr.hasColors?.()),
1259
+ stripColor: (str) => stripColor(str)
1260
+ };
1261
+ this._hidden = false;
1262
+ this._helpOption = void 0;
1263
+ this._addImplicitHelpCommand = void 0;
1264
+ this._helpCommand = void 0;
1265
+ this._helpConfiguration = {};
1266
+ this._helpGroupHeading = void 0;
1267
+ this._defaultCommandGroup = void 0;
1268
+ this._defaultOptionGroup = void 0;
1269
+ }
1270
+ /**
1271
+ * Copy settings that are useful to have in common across root command and subcommands.
1272
+ *
1273
+ * (Used internally when adding a command using `.command()` so subcommands inherit parent settings.)
1274
+ *
1275
+ * @param {Command} sourceCommand
1276
+ * @return {Command} `this` command for chaining
1277
+ */
1278
+ copyInheritedSettings(sourceCommand) {
1279
+ this._outputConfiguration = sourceCommand._outputConfiguration;
1280
+ this._helpOption = sourceCommand._helpOption;
1281
+ this._helpCommand = sourceCommand._helpCommand;
1282
+ this._helpConfiguration = sourceCommand._helpConfiguration;
1283
+ this._exitCallback = sourceCommand._exitCallback;
1284
+ this._storeOptionsAsProperties = sourceCommand._storeOptionsAsProperties;
1285
+ this._combineFlagAndOptionalValue = sourceCommand._combineFlagAndOptionalValue;
1286
+ this._allowExcessArguments = sourceCommand._allowExcessArguments;
1287
+ this._enablePositionalOptions = sourceCommand._enablePositionalOptions;
1288
+ this._showHelpAfterError = sourceCommand._showHelpAfterError;
1289
+ this._showSuggestionAfterError = sourceCommand._showSuggestionAfterError;
1290
+ return this;
1291
+ }
1292
+ /**
1293
+ * @returns {Command[]}
1294
+ * @private
1295
+ */
1296
+ _getCommandAndAncestors() {
1297
+ const result = [];
1298
+ for (let command = this; command; command = command.parent) {
1299
+ result.push(command);
1300
+ }
1301
+ return result;
1302
+ }
1303
+ /**
1304
+ * Define a command.
1305
+ *
1306
+ * There are two styles of command: pay attention to where to put the description.
1307
+ *
1308
+ * @example
1309
+ * // Command implemented using action handler (description is supplied separately to `.command`)
1310
+ * program
1311
+ * .command('clone <source> [destination]')
1312
+ * .description('clone a repository into a newly created directory')
1313
+ * .action((source, destination) => {
1314
+ * console.log('clone command called');
1315
+ * });
1316
+ *
1317
+ * // Command implemented using separate executable file (description is second parameter to `.command`)
1318
+ * program
1319
+ * .command('start <service>', 'start named service')
1320
+ * .command('stop [service]', 'stop named service, or all if no name supplied');
1321
+ *
1322
+ * @param {string} nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...`
1323
+ * @param {(object | string)} [actionOptsOrExecDesc] - configuration options (for action), or description (for executable)
1324
+ * @param {object} [execOpts] - configuration options (for executable)
1325
+ * @return {Command} returns new command for action handler, or `this` for executable command
1326
+ */
1327
+ command(nameAndArgs, actionOptsOrExecDesc, execOpts) {
1328
+ let desc = actionOptsOrExecDesc;
1329
+ let opts = execOpts;
1330
+ if (typeof desc === "object" && desc !== null) {
1331
+ opts = desc;
1332
+ desc = null;
1333
+ }
1334
+ opts = opts || {};
1335
+ const [, name, args] = nameAndArgs.match(/([^ ]+) *(.*)/);
1336
+ const cmd = this.createCommand(name);
1337
+ if (desc) {
1338
+ cmd.description(desc);
1339
+ cmd._executableHandler = true;
1340
+ }
1341
+ if (opts.isDefault) this._defaultCommandName = cmd._name;
1342
+ cmd._hidden = !!(opts.noHelp || opts.hidden);
1343
+ cmd._executableFile = opts.executableFile || null;
1344
+ if (args) cmd.arguments(args);
1345
+ this._registerCommand(cmd);
1346
+ cmd.parent = this;
1347
+ cmd.copyInheritedSettings(this);
1348
+ if (desc) return this;
1349
+ return cmd;
1350
+ }
1351
+ /**
1352
+ * Factory routine to create a new unattached command.
1353
+ *
1354
+ * See .command() for creating an attached subcommand, which uses this routine to
1355
+ * create the command. You can override createCommand to customise subcommands.
1356
+ *
1357
+ * @param {string} [name]
1358
+ * @return {Command} new command
1359
+ */
1360
+ createCommand(name) {
1361
+ return new _Command(name);
1362
+ }
1363
+ /**
1364
+ * You can customise the help with a subclass of Help by overriding createHelp,
1365
+ * or by overriding Help properties using configureHelp().
1366
+ *
1367
+ * @return {Help}
1368
+ */
1369
+ createHelp() {
1370
+ return Object.assign(new Help2(), this.configureHelp());
1371
+ }
1372
+ /**
1373
+ * You can customise the help by overriding Help properties using configureHelp(),
1374
+ * or with a subclass of Help by overriding createHelp().
1375
+ *
1376
+ * @param {object} [configuration] - configuration options
1377
+ * @return {(Command | object)} `this` command for chaining, or stored configuration
1378
+ */
1379
+ configureHelp(configuration) {
1380
+ if (configuration === void 0) return this._helpConfiguration;
1381
+ this._helpConfiguration = configuration;
1382
+ return this;
1383
+ }
1384
+ /**
1385
+ * The default output goes to stdout and stderr. You can customise this for special
1386
+ * applications. You can also customise the display of errors by overriding outputError.
1387
+ *
1388
+ * The configuration properties are all functions:
1389
+ *
1390
+ * // change how output being written, defaults to stdout and stderr
1391
+ * writeOut(str)
1392
+ * writeErr(str)
1393
+ * // change how output being written for errors, defaults to writeErr
1394
+ * outputError(str, write) // used for displaying errors and not used for displaying help
1395
+ * // specify width for wrapping help
1396
+ * getOutHelpWidth()
1397
+ * getErrHelpWidth()
1398
+ * // color support, currently only used with Help
1399
+ * getOutHasColors()
1400
+ * getErrHasColors()
1401
+ * stripColor() // used to remove ANSI escape codes if output does not have colors
1402
+ *
1403
+ * @param {object} [configuration] - configuration options
1404
+ * @return {(Command | object)} `this` command for chaining, or stored configuration
1405
+ */
1406
+ configureOutput(configuration) {
1407
+ if (configuration === void 0) return this._outputConfiguration;
1408
+ this._outputConfiguration = {
1409
+ ...this._outputConfiguration,
1410
+ ...configuration
1411
+ };
1412
+ return this;
1413
+ }
1414
+ /**
1415
+ * Display the help or a custom message after an error occurs.
1416
+ *
1417
+ * @param {(boolean|string)} [displayHelp]
1418
+ * @return {Command} `this` command for chaining
1419
+ */
1420
+ showHelpAfterError(displayHelp = true) {
1421
+ if (typeof displayHelp !== "string") displayHelp = !!displayHelp;
1422
+ this._showHelpAfterError = displayHelp;
1423
+ return this;
1424
+ }
1425
+ /**
1426
+ * Display suggestion of similar commands for unknown commands, or options for unknown options.
1427
+ *
1428
+ * @param {boolean} [displaySuggestion]
1429
+ * @return {Command} `this` command for chaining
1430
+ */
1431
+ showSuggestionAfterError(displaySuggestion = true) {
1432
+ this._showSuggestionAfterError = !!displaySuggestion;
1433
+ return this;
1434
+ }
1435
+ /**
1436
+ * Add a prepared subcommand.
1437
+ *
1438
+ * See .command() for creating an attached subcommand which inherits settings from its parent.
1439
+ *
1440
+ * @param {Command} cmd - new subcommand
1441
+ * @param {object} [opts] - configuration options
1442
+ * @return {Command} `this` command for chaining
1443
+ */
1444
+ addCommand(cmd, opts) {
1445
+ if (!cmd._name) {
1446
+ throw new Error(`Command passed to .addCommand() must have a name
1447
+ - specify the name in Command constructor or using .name()`);
1448
+ }
1449
+ opts = opts || {};
1450
+ if (opts.isDefault) this._defaultCommandName = cmd._name;
1451
+ if (opts.noHelp || opts.hidden) cmd._hidden = true;
1452
+ this._registerCommand(cmd);
1453
+ cmd.parent = this;
1454
+ cmd._checkForBrokenPassThrough();
1455
+ return this;
1456
+ }
1457
+ /**
1458
+ * Factory routine to create a new unattached argument.
1459
+ *
1460
+ * See .argument() for creating an attached argument, which uses this routine to
1461
+ * create the argument. You can override createArgument to return a custom argument.
1462
+ *
1463
+ * @param {string} name
1464
+ * @param {string} [description]
1465
+ * @return {Argument} new argument
1466
+ */
1467
+ createArgument(name, description) {
1468
+ return new Argument2(name, description);
1469
+ }
1470
+ /**
1471
+ * Define argument syntax for command.
1472
+ *
1473
+ * The default is that the argument is required, and you can explicitly
1474
+ * indicate this with <> around the name. Put [] around the name for an optional argument.
1475
+ *
1476
+ * @example
1477
+ * program.argument('<input-file>');
1478
+ * program.argument('[output-file]');
1479
+ *
1480
+ * @param {string} name
1481
+ * @param {string} [description]
1482
+ * @param {(Function|*)} [parseArg] - custom argument processing function or default value
1483
+ * @param {*} [defaultValue]
1484
+ * @return {Command} `this` command for chaining
1485
+ */
1486
+ argument(name, description, parseArg, defaultValue) {
1487
+ const argument = this.createArgument(name, description);
1488
+ if (typeof parseArg === "function") {
1489
+ argument.default(defaultValue).argParser(parseArg);
1490
+ } else {
1491
+ argument.default(parseArg);
1492
+ }
1493
+ this.addArgument(argument);
1494
+ return this;
1495
+ }
1496
+ /**
1497
+ * Define argument syntax for command, adding multiple at once (without descriptions).
1498
+ *
1499
+ * See also .argument().
1500
+ *
1501
+ * @example
1502
+ * program.arguments('<cmd> [env]');
1503
+ *
1504
+ * @param {string} names
1505
+ * @return {Command} `this` command for chaining
1506
+ */
1507
+ arguments(names) {
1508
+ names.trim().split(/ +/).forEach((detail) => {
1509
+ this.argument(detail);
1510
+ });
1511
+ return this;
1512
+ }
1513
+ /**
1514
+ * Define argument syntax for command, adding a prepared argument.
1515
+ *
1516
+ * @param {Argument} argument
1517
+ * @return {Command} `this` command for chaining
1518
+ */
1519
+ addArgument(argument) {
1520
+ const previousArgument = this.registeredArguments.slice(-1)[0];
1521
+ if (previousArgument?.variadic) {
1522
+ throw new Error(
1523
+ `only the last argument can be variadic '${previousArgument.name()}'`
1524
+ );
1525
+ }
1526
+ if (argument.required && argument.defaultValue !== void 0 && argument.parseArg === void 0) {
1527
+ throw new Error(
1528
+ `a default value for a required argument is never used: '${argument.name()}'`
1529
+ );
1530
+ }
1531
+ this.registeredArguments.push(argument);
1532
+ return this;
1533
+ }
1534
+ /**
1535
+ * Customise or override default help command. By default a help command is automatically added if your command has subcommands.
1536
+ *
1537
+ * @example
1538
+ * program.helpCommand('help [cmd]');
1539
+ * program.helpCommand('help [cmd]', 'show help');
1540
+ * program.helpCommand(false); // suppress default help command
1541
+ * program.helpCommand(true); // add help command even if no subcommands
1542
+ *
1543
+ * @param {string|boolean} enableOrNameAndArgs - enable with custom name and/or arguments, or boolean to override whether added
1544
+ * @param {string} [description] - custom description
1545
+ * @return {Command} `this` command for chaining
1546
+ */
1547
+ helpCommand(enableOrNameAndArgs, description) {
1548
+ if (typeof enableOrNameAndArgs === "boolean") {
1549
+ this._addImplicitHelpCommand = enableOrNameAndArgs;
1550
+ if (enableOrNameAndArgs && this._defaultCommandGroup) {
1551
+ this._initCommandGroup(this._getHelpCommand());
1552
+ }
1553
+ return this;
1554
+ }
1555
+ const nameAndArgs = enableOrNameAndArgs ?? "help [command]";
1556
+ const [, helpName, helpArgs] = nameAndArgs.match(/([^ ]+) *(.*)/);
1557
+ const helpDescription = description ?? "display help for command";
1558
+ const helpCommand = this.createCommand(helpName);
1559
+ helpCommand.helpOption(false);
1560
+ if (helpArgs) helpCommand.arguments(helpArgs);
1561
+ if (helpDescription) helpCommand.description(helpDescription);
1562
+ this._addImplicitHelpCommand = true;
1563
+ this._helpCommand = helpCommand;
1564
+ if (enableOrNameAndArgs || description) this._initCommandGroup(helpCommand);
1565
+ return this;
1566
+ }
1567
+ /**
1568
+ * Add prepared custom help command.
1569
+ *
1570
+ * @param {(Command|string|boolean)} helpCommand - custom help command, or deprecated enableOrNameAndArgs as for `.helpCommand()`
1571
+ * @param {string} [deprecatedDescription] - deprecated custom description used with custom name only
1572
+ * @return {Command} `this` command for chaining
1573
+ */
1574
+ addHelpCommand(helpCommand, deprecatedDescription) {
1575
+ if (typeof helpCommand !== "object") {
1576
+ this.helpCommand(helpCommand, deprecatedDescription);
1577
+ return this;
1578
+ }
1579
+ this._addImplicitHelpCommand = true;
1580
+ this._helpCommand = helpCommand;
1581
+ this._initCommandGroup(helpCommand);
1582
+ return this;
1583
+ }
1584
+ /**
1585
+ * Lazy create help command.
1586
+ *
1587
+ * @return {(Command|null)}
1588
+ * @package
1589
+ */
1590
+ _getHelpCommand() {
1591
+ const hasImplicitHelpCommand = this._addImplicitHelpCommand ?? (this.commands.length && !this._actionHandler && !this._findCommand("help"));
1592
+ if (hasImplicitHelpCommand) {
1593
+ if (this._helpCommand === void 0) {
1594
+ this.helpCommand(void 0, void 0);
1595
+ }
1596
+ return this._helpCommand;
1597
+ }
1598
+ return null;
1599
+ }
1600
+ /**
1601
+ * Add hook for life cycle event.
1602
+ *
1603
+ * @param {string} event
1604
+ * @param {Function} listener
1605
+ * @return {Command} `this` command for chaining
1606
+ */
1607
+ hook(event, listener) {
1608
+ const allowedValues = ["preSubcommand", "preAction", "postAction"];
1609
+ if (!allowedValues.includes(event)) {
1610
+ throw new Error(`Unexpected value for event passed to hook : '${event}'.
1611
+ Expecting one of '${allowedValues.join("', '")}'`);
1612
+ }
1613
+ if (this._lifeCycleHooks[event]) {
1614
+ this._lifeCycleHooks[event].push(listener);
1615
+ } else {
1616
+ this._lifeCycleHooks[event] = [listener];
1617
+ }
1618
+ return this;
1619
+ }
1620
+ /**
1621
+ * Register callback to use as replacement for calling process.exit.
1622
+ *
1623
+ * @param {Function} [fn] optional callback which will be passed a CommanderError, defaults to throwing
1624
+ * @return {Command} `this` command for chaining
1625
+ */
1626
+ exitOverride(fn) {
1627
+ if (fn) {
1628
+ this._exitCallback = fn;
1629
+ } else {
1630
+ this._exitCallback = (err) => {
1631
+ if (err.code !== "commander.executeSubCommandAsync") {
1632
+ throw err;
1633
+ } else {
1634
+ }
1635
+ };
1636
+ }
1637
+ return this;
1638
+ }
1639
+ /**
1640
+ * Call process.exit, and _exitCallback if defined.
1641
+ *
1642
+ * @param {number} exitCode exit code for using with process.exit
1643
+ * @param {string} code an id string representing the error
1644
+ * @param {string} message human-readable description of the error
1645
+ * @return never
1646
+ * @private
1647
+ */
1648
+ _exit(exitCode, code, message) {
1649
+ if (this._exitCallback) {
1650
+ this._exitCallback(new CommanderError2(exitCode, code, message));
1651
+ }
1652
+ process2.exit(exitCode);
1653
+ }
1654
+ /**
1655
+ * Register callback `fn` for the command.
1656
+ *
1657
+ * @example
1658
+ * program
1659
+ * .command('serve')
1660
+ * .description('start service')
1661
+ * .action(function() {
1662
+ * // do work here
1663
+ * });
1664
+ *
1665
+ * @param {Function} fn
1666
+ * @return {Command} `this` command for chaining
1667
+ */
1668
+ action(fn) {
1669
+ const listener = (args) => {
1670
+ const expectedArgsCount = this.registeredArguments.length;
1671
+ const actionArgs = args.slice(0, expectedArgsCount);
1672
+ if (this._storeOptionsAsProperties) {
1673
+ actionArgs[expectedArgsCount] = this;
1674
+ } else {
1675
+ actionArgs[expectedArgsCount] = this.opts();
1676
+ }
1677
+ actionArgs.push(this);
1678
+ return fn.apply(this, actionArgs);
1679
+ };
1680
+ this._actionHandler = listener;
1681
+ return this;
1682
+ }
1683
+ /**
1684
+ * Factory routine to create a new unattached option.
1685
+ *
1686
+ * See .option() for creating an attached option, which uses this routine to
1687
+ * create the option. You can override createOption to return a custom option.
1688
+ *
1689
+ * @param {string} flags
1690
+ * @param {string} [description]
1691
+ * @return {Option} new option
1692
+ */
1693
+ createOption(flags, description) {
1694
+ return new Option2(flags, description);
1695
+ }
1696
+ /**
1697
+ * Wrap parseArgs to catch 'commander.invalidArgument'.
1698
+ *
1699
+ * @param {(Option | Argument)} target
1700
+ * @param {string} value
1701
+ * @param {*} previous
1702
+ * @param {string} invalidArgumentMessage
1703
+ * @private
1704
+ */
1705
+ _callParseArg(target, value, previous, invalidArgumentMessage) {
1706
+ try {
1707
+ return target.parseArg(value, previous);
1708
+ } catch (err) {
1709
+ if (err.code === "commander.invalidArgument") {
1710
+ const message = `${invalidArgumentMessage} ${err.message}`;
1711
+ this.error(message, { exitCode: err.exitCode, code: err.code });
1712
+ }
1713
+ throw err;
1714
+ }
1715
+ }
1716
+ /**
1717
+ * Check for option flag conflicts.
1718
+ * Register option if no conflicts found, or throw on conflict.
1719
+ *
1720
+ * @param {Option} option
1721
+ * @private
1722
+ */
1723
+ _registerOption(option) {
1724
+ const matchingOption = option.short && this._findOption(option.short) || option.long && this._findOption(option.long);
1725
+ if (matchingOption) {
1726
+ const matchingFlag = option.long && this._findOption(option.long) ? option.long : option.short;
1727
+ throw new Error(`Cannot add option '${option.flags}'${this._name && ` to command '${this._name}'`} due to conflicting flag '${matchingFlag}'
1728
+ - already used by option '${matchingOption.flags}'`);
1729
+ }
1730
+ this._initOptionGroup(option);
1731
+ this.options.push(option);
1732
+ }
1733
+ /**
1734
+ * Check for command name and alias conflicts with existing commands.
1735
+ * Register command if no conflicts found, or throw on conflict.
1736
+ *
1737
+ * @param {Command} command
1738
+ * @private
1739
+ */
1740
+ _registerCommand(command) {
1741
+ const knownBy = (cmd) => {
1742
+ return [cmd.name()].concat(cmd.aliases());
1743
+ };
1744
+ const alreadyUsed = knownBy(command).find(
1745
+ (name) => this._findCommand(name)
1746
+ );
1747
+ if (alreadyUsed) {
1748
+ const existingCmd = knownBy(this._findCommand(alreadyUsed)).join("|");
1749
+ const newCmd = knownBy(command).join("|");
1750
+ throw new Error(
1751
+ `cannot add command '${newCmd}' as already have command '${existingCmd}'`
1752
+ );
1753
+ }
1754
+ this._initCommandGroup(command);
1755
+ this.commands.push(command);
1756
+ }
1757
+ /**
1758
+ * Add an option.
1759
+ *
1760
+ * @param {Option} option
1761
+ * @return {Command} `this` command for chaining
1762
+ */
1763
+ addOption(option) {
1764
+ this._registerOption(option);
1765
+ const oname = option.name();
1766
+ const name = option.attributeName();
1767
+ if (option.negate) {
1768
+ const positiveLongFlag = option.long.replace(/^--no-/, "--");
1769
+ if (!this._findOption(positiveLongFlag)) {
1770
+ this.setOptionValueWithSource(
1771
+ name,
1772
+ option.defaultValue === void 0 ? true : option.defaultValue,
1773
+ "default"
1774
+ );
1775
+ }
1776
+ } else if (option.defaultValue !== void 0) {
1777
+ this.setOptionValueWithSource(name, option.defaultValue, "default");
1778
+ }
1779
+ const handleOptionValue = (val, invalidValueMessage, valueSource) => {
1780
+ if (val == null && option.presetArg !== void 0) {
1781
+ val = option.presetArg;
1782
+ }
1783
+ const oldValue = this.getOptionValue(name);
1784
+ if (val !== null && option.parseArg) {
1785
+ val = this._callParseArg(option, val, oldValue, invalidValueMessage);
1786
+ } else if (val !== null && option.variadic) {
1787
+ val = option._collectValue(val, oldValue);
1788
+ }
1789
+ if (val == null) {
1790
+ if (option.negate) {
1791
+ val = false;
1792
+ } else if (option.isBoolean() || option.optional) {
1793
+ val = true;
1794
+ } else {
1795
+ val = "";
1796
+ }
1797
+ }
1798
+ this.setOptionValueWithSource(name, val, valueSource);
1799
+ };
1800
+ this.on("option:" + oname, (val) => {
1801
+ const invalidValueMessage = `error: option '${option.flags}' argument '${val}' is invalid.`;
1802
+ handleOptionValue(val, invalidValueMessage, "cli");
1803
+ });
1804
+ if (option.envVar) {
1805
+ this.on("optionEnv:" + oname, (val) => {
1806
+ const invalidValueMessage = `error: option '${option.flags}' value '${val}' from env '${option.envVar}' is invalid.`;
1807
+ handleOptionValue(val, invalidValueMessage, "env");
1808
+ });
1809
+ }
1810
+ return this;
1811
+ }
1812
+ /**
1813
+ * Internal implementation shared by .option() and .requiredOption()
1814
+ *
1815
+ * @return {Command} `this` command for chaining
1816
+ * @private
1817
+ */
1818
+ _optionEx(config, flags, description, fn, defaultValue) {
1819
+ if (typeof flags === "object" && flags instanceof Option2) {
1820
+ throw new Error(
1821
+ "To add an Option object use addOption() instead of option() or requiredOption()"
1822
+ );
1823
+ }
1824
+ const option = this.createOption(flags, description);
1825
+ option.makeOptionMandatory(!!config.mandatory);
1826
+ if (typeof fn === "function") {
1827
+ option.default(defaultValue).argParser(fn);
1828
+ } else if (fn instanceof RegExp) {
1829
+ const regex = fn;
1830
+ fn = (val, def) => {
1831
+ const m = regex.exec(val);
1832
+ return m ? m[0] : def;
1833
+ };
1834
+ option.default(defaultValue).argParser(fn);
1835
+ } else {
1836
+ option.default(fn);
1837
+ }
1838
+ return this.addOption(option);
1839
+ }
1840
+ /**
1841
+ * Define option with `flags`, `description`, and optional argument parsing function or `defaultValue` or both.
1842
+ *
1843
+ * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space. A required
1844
+ * option-argument is indicated by `<>` and an optional option-argument by `[]`.
1845
+ *
1846
+ * See the README for more details, and see also addOption() and requiredOption().
1847
+ *
1848
+ * @example
1849
+ * program
1850
+ * .option('-p, --pepper', 'add pepper')
1851
+ * .option('--pt, --pizza-type <TYPE>', 'type of pizza') // required option-argument
1852
+ * .option('-c, --cheese [CHEESE]', 'add extra cheese', 'mozzarella') // optional option-argument with default
1853
+ * .option('-t, --tip <VALUE>', 'add tip to purchase cost', parseFloat) // custom parse function
1854
+ *
1855
+ * @param {string} flags
1856
+ * @param {string} [description]
1857
+ * @param {(Function|*)} [parseArg] - custom option processing function or default value
1858
+ * @param {*} [defaultValue]
1859
+ * @return {Command} `this` command for chaining
1860
+ */
1861
+ option(flags, description, parseArg, defaultValue) {
1862
+ return this._optionEx({}, flags, description, parseArg, defaultValue);
1863
+ }
1864
+ /**
1865
+ * Add a required option which must have a value after parsing. This usually means
1866
+ * the option must be specified on the command line. (Otherwise the same as .option().)
1867
+ *
1868
+ * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space.
1869
+ *
1870
+ * @param {string} flags
1871
+ * @param {string} [description]
1872
+ * @param {(Function|*)} [parseArg] - custom option processing function or default value
1873
+ * @param {*} [defaultValue]
1874
+ * @return {Command} `this` command for chaining
1875
+ */
1876
+ requiredOption(flags, description, parseArg, defaultValue) {
1877
+ return this._optionEx(
1878
+ { mandatory: true },
1879
+ flags,
1880
+ description,
1881
+ parseArg,
1882
+ defaultValue
1883
+ );
1884
+ }
1885
+ /**
1886
+ * Alter parsing of short flags with optional values.
1887
+ *
1888
+ * @example
1889
+ * // for `.option('-f,--flag [value]'):
1890
+ * program.combineFlagAndOptionalValue(true); // `-f80` is treated like `--flag=80`, this is the default behaviour
1891
+ * program.combineFlagAndOptionalValue(false) // `-fb` is treated like `-f -b`
1892
+ *
1893
+ * @param {boolean} [combine] - if `true` or omitted, an optional value can be specified directly after the flag.
1894
+ * @return {Command} `this` command for chaining
1895
+ */
1896
+ combineFlagAndOptionalValue(combine = true) {
1897
+ this._combineFlagAndOptionalValue = !!combine;
1898
+ return this;
1899
+ }
1900
+ /**
1901
+ * Allow unknown options on the command line.
1902
+ *
1903
+ * @param {boolean} [allowUnknown] - if `true` or omitted, no error will be thrown for unknown options.
1904
+ * @return {Command} `this` command for chaining
1905
+ */
1906
+ allowUnknownOption(allowUnknown = true) {
1907
+ this._allowUnknownOption = !!allowUnknown;
1908
+ return this;
1909
+ }
1910
+ /**
1911
+ * Allow excess command-arguments on the command line. Pass false to make excess arguments an error.
1912
+ *
1913
+ * @param {boolean} [allowExcess] - if `true` or omitted, no error will be thrown for excess arguments.
1914
+ * @return {Command} `this` command for chaining
1915
+ */
1916
+ allowExcessArguments(allowExcess = true) {
1917
+ this._allowExcessArguments = !!allowExcess;
1918
+ return this;
1919
+ }
1920
+ /**
1921
+ * Enable positional options. Positional means global options are specified before subcommands which lets
1922
+ * subcommands reuse the same option names, and also enables subcommands to turn on passThroughOptions.
1923
+ * The default behaviour is non-positional and global options may appear anywhere on the command line.
1924
+ *
1925
+ * @param {boolean} [positional]
1926
+ * @return {Command} `this` command for chaining
1927
+ */
1928
+ enablePositionalOptions(positional = true) {
1929
+ this._enablePositionalOptions = !!positional;
1930
+ return this;
1931
+ }
1932
+ /**
1933
+ * Pass through options that come after command-arguments rather than treat them as command-options,
1934
+ * so actual command-options come before command-arguments. Turning this on for a subcommand requires
1935
+ * positional options to have been enabled on the program (parent commands).
1936
+ * The default behaviour is non-positional and options may appear before or after command-arguments.
1937
+ *
1938
+ * @param {boolean} [passThrough] for unknown options.
1939
+ * @return {Command} `this` command for chaining
1940
+ */
1941
+ passThroughOptions(passThrough = true) {
1942
+ this._passThroughOptions = !!passThrough;
1943
+ this._checkForBrokenPassThrough();
1944
+ return this;
1945
+ }
1946
+ /**
1947
+ * @private
1948
+ */
1949
+ _checkForBrokenPassThrough() {
1950
+ if (this.parent && this._passThroughOptions && !this.parent._enablePositionalOptions) {
1951
+ throw new Error(
1952
+ `passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`
1953
+ );
1954
+ }
1955
+ }
1956
+ /**
1957
+ * Whether to store option values as properties on command object,
1958
+ * or store separately (specify false). In both cases the option values can be accessed using .opts().
1959
+ *
1960
+ * @param {boolean} [storeAsProperties=true]
1961
+ * @return {Command} `this` command for chaining
1962
+ */
1963
+ storeOptionsAsProperties(storeAsProperties = true) {
1964
+ if (this.options.length) {
1965
+ throw new Error("call .storeOptionsAsProperties() before adding options");
1966
+ }
1967
+ if (Object.keys(this._optionValues).length) {
1968
+ throw new Error(
1969
+ "call .storeOptionsAsProperties() before setting option values"
1970
+ );
1971
+ }
1972
+ this._storeOptionsAsProperties = !!storeAsProperties;
1973
+ return this;
1974
+ }
1975
+ /**
1976
+ * Retrieve option value.
1977
+ *
1978
+ * @param {string} key
1979
+ * @return {object} value
1980
+ */
1981
+ getOptionValue(key) {
1982
+ if (this._storeOptionsAsProperties) {
1983
+ return this[key];
1984
+ }
1985
+ return this._optionValues[key];
1986
+ }
1987
+ /**
1988
+ * Store option value.
1989
+ *
1990
+ * @param {string} key
1991
+ * @param {object} value
1992
+ * @return {Command} `this` command for chaining
1993
+ */
1994
+ setOptionValue(key, value) {
1995
+ return this.setOptionValueWithSource(key, value, void 0);
1996
+ }
1997
+ /**
1998
+ * Store option value and where the value came from.
1999
+ *
2000
+ * @param {string} key
2001
+ * @param {object} value
2002
+ * @param {string} source - expected values are default/config/env/cli/implied
2003
+ * @return {Command} `this` command for chaining
2004
+ */
2005
+ setOptionValueWithSource(key, value, source) {
2006
+ if (this._storeOptionsAsProperties) {
2007
+ this[key] = value;
2008
+ } else {
2009
+ this._optionValues[key] = value;
2010
+ }
2011
+ this._optionValueSources[key] = source;
2012
+ return this;
2013
+ }
2014
+ /**
2015
+ * Get source of option value.
2016
+ * Expected values are default | config | env | cli | implied
2017
+ *
2018
+ * @param {string} key
2019
+ * @return {string}
2020
+ */
2021
+ getOptionValueSource(key) {
2022
+ return this._optionValueSources[key];
2023
+ }
2024
+ /**
2025
+ * Get source of option value. See also .optsWithGlobals().
2026
+ * Expected values are default | config | env | cli | implied
2027
+ *
2028
+ * @param {string} key
2029
+ * @return {string}
2030
+ */
2031
+ getOptionValueSourceWithGlobals(key) {
2032
+ let source;
2033
+ this._getCommandAndAncestors().forEach((cmd) => {
2034
+ if (cmd.getOptionValueSource(key) !== void 0) {
2035
+ source = cmd.getOptionValueSource(key);
2036
+ }
2037
+ });
2038
+ return source;
2039
+ }
2040
+ /**
2041
+ * Get user arguments from implied or explicit arguments.
2042
+ * Side-effects: set _scriptPath if args included script. Used for default program name, and subcommand searches.
2043
+ *
2044
+ * @private
2045
+ */
2046
+ _prepareUserArgs(argv, parseOptions) {
2047
+ if (argv !== void 0 && !Array.isArray(argv)) {
2048
+ throw new Error("first parameter to parse must be array or undefined");
2049
+ }
2050
+ parseOptions = parseOptions || {};
2051
+ if (argv === void 0 && parseOptions.from === void 0) {
2052
+ if (process2.versions?.electron) {
2053
+ parseOptions.from = "electron";
2054
+ }
2055
+ const execArgv = process2.execArgv ?? [];
2056
+ if (execArgv.includes("-e") || execArgv.includes("--eval") || execArgv.includes("-p") || execArgv.includes("--print")) {
2057
+ parseOptions.from = "eval";
2058
+ }
2059
+ }
2060
+ if (argv === void 0) {
2061
+ argv = process2.argv;
2062
+ }
2063
+ this.rawArgs = argv.slice();
2064
+ let userArgs;
2065
+ switch (parseOptions.from) {
2066
+ case void 0:
2067
+ case "node":
2068
+ this._scriptPath = argv[1];
2069
+ userArgs = argv.slice(2);
2070
+ break;
2071
+ case "electron":
2072
+ if (process2.defaultApp) {
2073
+ this._scriptPath = argv[1];
2074
+ userArgs = argv.slice(2);
2075
+ } else {
2076
+ userArgs = argv.slice(1);
2077
+ }
2078
+ break;
2079
+ case "user":
2080
+ userArgs = argv.slice(0);
2081
+ break;
2082
+ case "eval":
2083
+ userArgs = argv.slice(1);
2084
+ break;
2085
+ default:
2086
+ throw new Error(
2087
+ `unexpected parse option { from: '${parseOptions.from}' }`
2088
+ );
2089
+ }
2090
+ if (!this._name && this._scriptPath)
2091
+ this.nameFromFilename(this._scriptPath);
2092
+ this._name = this._name || "program";
2093
+ return userArgs;
2094
+ }
2095
+ /**
2096
+ * Parse `argv`, setting options and invoking commands when defined.
2097
+ *
2098
+ * Use parseAsync instead of parse if any of your action handlers are async.
2099
+ *
2100
+ * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!
2101
+ *
2102
+ * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:
2103
+ * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that
2104
+ * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged
2105
+ * - `'user'`: just user arguments
2106
+ *
2107
+ * @example
2108
+ * program.parse(); // parse process.argv and auto-detect electron and special node flags
2109
+ * program.parse(process.argv); // assume argv[0] is app and argv[1] is script
2110
+ * program.parse(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
2111
+ *
2112
+ * @param {string[]} [argv] - optional, defaults to process.argv
2113
+ * @param {object} [parseOptions] - optionally specify style of options with from: node/user/electron
2114
+ * @param {string} [parseOptions.from] - where the args are from: 'node', 'user', 'electron'
2115
+ * @return {Command} `this` command for chaining
2116
+ */
2117
+ parse(argv, parseOptions) {
2118
+ this._prepareForParse();
2119
+ const userArgs = this._prepareUserArgs(argv, parseOptions);
2120
+ this._parseCommand([], userArgs);
2121
+ return this;
2122
+ }
2123
+ /**
2124
+ * Parse `argv`, setting options and invoking commands when defined.
2125
+ *
2126
+ * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!
2127
+ *
2128
+ * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:
2129
+ * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that
2130
+ * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged
2131
+ * - `'user'`: just user arguments
2132
+ *
2133
+ * @example
2134
+ * await program.parseAsync(); // parse process.argv and auto-detect electron and special node flags
2135
+ * await program.parseAsync(process.argv); // assume argv[0] is app and argv[1] is script
2136
+ * await program.parseAsync(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
2137
+ *
2138
+ * @param {string[]} [argv]
2139
+ * @param {object} [parseOptions]
2140
+ * @param {string} parseOptions.from - where the args are from: 'node', 'user', 'electron'
2141
+ * @return {Promise}
2142
+ */
2143
+ async parseAsync(argv, parseOptions) {
2144
+ this._prepareForParse();
2145
+ const userArgs = this._prepareUserArgs(argv, parseOptions);
2146
+ await this._parseCommand([], userArgs);
2147
+ return this;
2148
+ }
2149
+ _prepareForParse() {
2150
+ if (this._savedState === null) {
2151
+ this.saveStateBeforeParse();
2152
+ } else {
2153
+ this.restoreStateBeforeParse();
2154
+ }
2155
+ }
2156
+ /**
2157
+ * Called the first time parse is called to save state and allow a restore before subsequent calls to parse.
2158
+ * Not usually called directly, but available for subclasses to save their custom state.
2159
+ *
2160
+ * This is called in a lazy way. Only commands used in parsing chain will have state saved.
2161
+ */
2162
+ saveStateBeforeParse() {
2163
+ this._savedState = {
2164
+ // name is stable if supplied by author, but may be unspecified for root command and deduced during parsing
2165
+ _name: this._name,
2166
+ // option values before parse have default values (including false for negated options)
2167
+ // shallow clones
2168
+ _optionValues: { ...this._optionValues },
2169
+ _optionValueSources: { ...this._optionValueSources }
2170
+ };
2171
+ }
2172
+ /**
2173
+ * Restore state before parse for calls after the first.
2174
+ * Not usually called directly, but available for subclasses to save their custom state.
2175
+ *
2176
+ * This is called in a lazy way. Only commands used in parsing chain will have state restored.
2177
+ */
2178
+ restoreStateBeforeParse() {
2179
+ if (this._storeOptionsAsProperties)
2180
+ throw new Error(`Can not call parse again when storeOptionsAsProperties is true.
2181
+ - either make a new Command for each call to parse, or stop storing options as properties`);
2182
+ this._name = this._savedState._name;
2183
+ this._scriptPath = null;
2184
+ this.rawArgs = [];
2185
+ this._optionValues = { ...this._savedState._optionValues };
2186
+ this._optionValueSources = { ...this._savedState._optionValueSources };
2187
+ this.args = [];
2188
+ this.processedArgs = [];
2189
+ }
2190
+ /**
2191
+ * Throw if expected executable is missing. Add lots of help for author.
2192
+ *
2193
+ * @param {string} executableFile
2194
+ * @param {string} executableDir
2195
+ * @param {string} subcommandName
2196
+ */
2197
+ _checkForMissingExecutable(executableFile, executableDir, subcommandName) {
2198
+ if (fs.existsSync(executableFile)) return;
2199
+ 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";
2200
+ const executableMissing = `'${executableFile}' does not exist
2201
+ - if '${subcommandName}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
2202
+ - if the default executable name is not suitable, use the executableFile option to supply a custom name or path
2203
+ - ${executableDirMessage}`;
2204
+ throw new Error(executableMissing);
2205
+ }
2206
+ /**
2207
+ * Execute a sub-command executable.
2208
+ *
2209
+ * @private
2210
+ */
2211
+ _executeSubCommand(subcommand, args) {
2212
+ args = args.slice();
2213
+ let launchWithNode = false;
2214
+ const sourceExt = [".js", ".ts", ".tsx", ".mjs", ".cjs"];
2215
+ function findFile(baseDir, baseName) {
2216
+ const localBin = path.resolve(baseDir, baseName);
2217
+ if (fs.existsSync(localBin)) return localBin;
2218
+ if (sourceExt.includes(path.extname(baseName))) return void 0;
2219
+ const foundExt = sourceExt.find(
2220
+ (ext) => fs.existsSync(`${localBin}${ext}`)
2221
+ );
2222
+ if (foundExt) return `${localBin}${foundExt}`;
2223
+ return void 0;
2224
+ }
2225
+ this._checkForMissingMandatoryOptions();
2226
+ this._checkForConflictingOptions();
2227
+ let executableFile = subcommand._executableFile || `${this._name}-${subcommand._name}`;
2228
+ let executableDir = this._executableDir || "";
2229
+ if (this._scriptPath) {
2230
+ let resolvedScriptPath;
2231
+ try {
2232
+ resolvedScriptPath = fs.realpathSync(this._scriptPath);
2233
+ } catch {
2234
+ resolvedScriptPath = this._scriptPath;
2235
+ }
2236
+ executableDir = path.resolve(
2237
+ path.dirname(resolvedScriptPath),
2238
+ executableDir
2239
+ );
2240
+ }
2241
+ if (executableDir) {
2242
+ let localFile = findFile(executableDir, executableFile);
2243
+ if (!localFile && !subcommand._executableFile && this._scriptPath) {
2244
+ const legacyName = path.basename(
2245
+ this._scriptPath,
2246
+ path.extname(this._scriptPath)
2247
+ );
2248
+ if (legacyName !== this._name) {
2249
+ localFile = findFile(
2250
+ executableDir,
2251
+ `${legacyName}-${subcommand._name}`
2252
+ );
2253
+ }
2254
+ }
2255
+ executableFile = localFile || executableFile;
2256
+ }
2257
+ launchWithNode = sourceExt.includes(path.extname(executableFile));
2258
+ let proc;
2259
+ if (process2.platform !== "win32") {
2260
+ if (launchWithNode) {
2261
+ args.unshift(executableFile);
2262
+ args = incrementNodeInspectorPort(process2.execArgv).concat(args);
2263
+ proc = childProcess.spawn(process2.argv[0], args, { stdio: "inherit" });
2264
+ } else {
2265
+ proc = childProcess.spawn(executableFile, args, { stdio: "inherit" });
2266
+ }
2267
+ } else {
2268
+ this._checkForMissingExecutable(
2269
+ executableFile,
2270
+ executableDir,
2271
+ subcommand._name
2272
+ );
2273
+ args.unshift(executableFile);
2274
+ args = incrementNodeInspectorPort(process2.execArgv).concat(args);
2275
+ proc = childProcess.spawn(process2.execPath, args, { stdio: "inherit" });
2276
+ }
2277
+ if (!proc.killed) {
2278
+ const signals = ["SIGUSR1", "SIGUSR2", "SIGTERM", "SIGINT", "SIGHUP"];
2279
+ signals.forEach((signal) => {
2280
+ process2.on(signal, () => {
2281
+ if (proc.killed === false && proc.exitCode === null) {
2282
+ proc.kill(signal);
2283
+ }
2284
+ });
2285
+ });
2286
+ }
2287
+ const exitCallback = this._exitCallback;
2288
+ proc.on("close", (code) => {
2289
+ code = code ?? 1;
2290
+ if (!exitCallback) {
2291
+ process2.exit(code);
2292
+ } else {
2293
+ exitCallback(
2294
+ new CommanderError2(
2295
+ code,
2296
+ "commander.executeSubCommandAsync",
2297
+ "(close)"
2298
+ )
2299
+ );
2300
+ }
2301
+ });
2302
+ proc.on("error", (err) => {
2303
+ if (err.code === "ENOENT") {
2304
+ this._checkForMissingExecutable(
2305
+ executableFile,
2306
+ executableDir,
2307
+ subcommand._name
2308
+ );
2309
+ } else if (err.code === "EACCES") {
2310
+ throw new Error(`'${executableFile}' not executable`);
2311
+ }
2312
+ if (!exitCallback) {
2313
+ process2.exit(1);
2314
+ } else {
2315
+ const wrappedError = new CommanderError2(
2316
+ 1,
2317
+ "commander.executeSubCommandAsync",
2318
+ "(error)"
2319
+ );
2320
+ wrappedError.nestedError = err;
2321
+ exitCallback(wrappedError);
2322
+ }
2323
+ });
2324
+ this.runningCommand = proc;
2325
+ }
2326
+ /**
2327
+ * @private
2328
+ */
2329
+ _dispatchSubcommand(commandName, operands, unknown) {
2330
+ const subCommand = this._findCommand(commandName);
2331
+ if (!subCommand) this.help({ error: true });
2332
+ subCommand._prepareForParse();
2333
+ let promiseChain;
2334
+ promiseChain = this._chainOrCallSubCommandHook(
2335
+ promiseChain,
2336
+ subCommand,
2337
+ "preSubcommand"
2338
+ );
2339
+ promiseChain = this._chainOrCall(promiseChain, () => {
2340
+ if (subCommand._executableHandler) {
2341
+ this._executeSubCommand(subCommand, operands.concat(unknown));
2342
+ } else {
2343
+ return subCommand._parseCommand(operands, unknown);
2344
+ }
2345
+ });
2346
+ return promiseChain;
2347
+ }
2348
+ /**
2349
+ * Invoke help directly if possible, or dispatch if necessary.
2350
+ * e.g. help foo
2351
+ *
2352
+ * @private
2353
+ */
2354
+ _dispatchHelpCommand(subcommandName) {
2355
+ if (!subcommandName) {
2356
+ this.help();
2357
+ }
2358
+ const subCommand = this._findCommand(subcommandName);
2359
+ if (subCommand && !subCommand._executableHandler) {
2360
+ subCommand.help();
2361
+ }
2362
+ return this._dispatchSubcommand(
2363
+ subcommandName,
2364
+ [],
2365
+ [this._getHelpOption()?.long ?? this._getHelpOption()?.short ?? "--help"]
2366
+ );
2367
+ }
2368
+ /**
2369
+ * Check this.args against expected this.registeredArguments.
2370
+ *
2371
+ * @private
2372
+ */
2373
+ _checkNumberOfArguments() {
2374
+ this.registeredArguments.forEach((arg, i) => {
2375
+ if (arg.required && this.args[i] == null) {
2376
+ this.missingArgument(arg.name());
2377
+ }
2378
+ });
2379
+ if (this.registeredArguments.length > 0 && this.registeredArguments[this.registeredArguments.length - 1].variadic) {
2380
+ return;
2381
+ }
2382
+ if (this.args.length > this.registeredArguments.length) {
2383
+ this._excessArguments(this.args);
2384
+ }
2385
+ }
2386
+ /**
2387
+ * Process this.args using this.registeredArguments and save as this.processedArgs!
2388
+ *
2389
+ * @private
2390
+ */
2391
+ _processArguments() {
2392
+ const myParseArg = (argument, value, previous) => {
2393
+ let parsedValue = value;
2394
+ if (value !== null && argument.parseArg) {
2395
+ const invalidValueMessage = `error: command-argument value '${value}' is invalid for argument '${argument.name()}'.`;
2396
+ parsedValue = this._callParseArg(
2397
+ argument,
2398
+ value,
2399
+ previous,
2400
+ invalidValueMessage
2401
+ );
2402
+ }
2403
+ return parsedValue;
2404
+ };
2405
+ this._checkNumberOfArguments();
2406
+ const processedArgs = [];
2407
+ this.registeredArguments.forEach((declaredArg, index) => {
2408
+ let value = declaredArg.defaultValue;
2409
+ if (declaredArg.variadic) {
2410
+ if (index < this.args.length) {
2411
+ value = this.args.slice(index);
2412
+ if (declaredArg.parseArg) {
2413
+ value = value.reduce((processed, v) => {
2414
+ return myParseArg(declaredArg, v, processed);
2415
+ }, declaredArg.defaultValue);
2416
+ }
2417
+ } else if (value === void 0) {
2418
+ value = [];
2419
+ }
2420
+ } else if (index < this.args.length) {
2421
+ value = this.args[index];
2422
+ if (declaredArg.parseArg) {
2423
+ value = myParseArg(declaredArg, value, declaredArg.defaultValue);
2424
+ }
2425
+ }
2426
+ processedArgs[index] = value;
2427
+ });
2428
+ this.processedArgs = processedArgs;
2429
+ }
2430
+ /**
2431
+ * Once we have a promise we chain, but call synchronously until then.
2432
+ *
2433
+ * @param {(Promise|undefined)} promise
2434
+ * @param {Function} fn
2435
+ * @return {(Promise|undefined)}
2436
+ * @private
2437
+ */
2438
+ _chainOrCall(promise, fn) {
2439
+ if (promise?.then && typeof promise.then === "function") {
2440
+ return promise.then(() => fn());
2441
+ }
2442
+ return fn();
2443
+ }
2444
+ /**
2445
+ *
2446
+ * @param {(Promise|undefined)} promise
2447
+ * @param {string} event
2448
+ * @return {(Promise|undefined)}
2449
+ * @private
2450
+ */
2451
+ _chainOrCallHooks(promise, event) {
2452
+ let result = promise;
2453
+ const hooks = [];
2454
+ this._getCommandAndAncestors().reverse().filter((cmd) => cmd._lifeCycleHooks[event] !== void 0).forEach((hookedCommand) => {
2455
+ hookedCommand._lifeCycleHooks[event].forEach((callback) => {
2456
+ hooks.push({ hookedCommand, callback });
2457
+ });
2458
+ });
2459
+ if (event === "postAction") {
2460
+ hooks.reverse();
2461
+ }
2462
+ hooks.forEach((hookDetail) => {
2463
+ result = this._chainOrCall(result, () => {
2464
+ return hookDetail.callback(hookDetail.hookedCommand, this);
2465
+ });
2466
+ });
2467
+ return result;
2468
+ }
2469
+ /**
2470
+ *
2471
+ * @param {(Promise|undefined)} promise
2472
+ * @param {Command} subCommand
2473
+ * @param {string} event
2474
+ * @return {(Promise|undefined)}
2475
+ * @private
2476
+ */
2477
+ _chainOrCallSubCommandHook(promise, subCommand, event) {
2478
+ let result = promise;
2479
+ if (this._lifeCycleHooks[event] !== void 0) {
2480
+ this._lifeCycleHooks[event].forEach((hook) => {
2481
+ result = this._chainOrCall(result, () => {
2482
+ return hook(this, subCommand);
2483
+ });
2484
+ });
2485
+ }
2486
+ return result;
2487
+ }
2488
+ /**
2489
+ * Process arguments in context of this command.
2490
+ * Returns action result, in case it is a promise.
2491
+ *
2492
+ * @private
2493
+ */
2494
+ _parseCommand(operands, unknown) {
2495
+ const parsed = this.parseOptions(unknown);
2496
+ this._parseOptionsEnv();
2497
+ this._parseOptionsImplied();
2498
+ operands = operands.concat(parsed.operands);
2499
+ unknown = parsed.unknown;
2500
+ this.args = operands.concat(unknown);
2501
+ if (operands && this._findCommand(operands[0])) {
2502
+ return this._dispatchSubcommand(operands[0], operands.slice(1), unknown);
2503
+ }
2504
+ if (this._getHelpCommand() && operands[0] === this._getHelpCommand().name()) {
2505
+ return this._dispatchHelpCommand(operands[1]);
2506
+ }
2507
+ if (this._defaultCommandName) {
2508
+ this._outputHelpIfRequested(unknown);
2509
+ return this._dispatchSubcommand(
2510
+ this._defaultCommandName,
2511
+ operands,
2512
+ unknown
2513
+ );
2514
+ }
2515
+ if (this.commands.length && this.args.length === 0 && !this._actionHandler && !this._defaultCommandName) {
2516
+ this.help({ error: true });
2517
+ }
2518
+ this._outputHelpIfRequested(parsed.unknown);
2519
+ this._checkForMissingMandatoryOptions();
2520
+ this._checkForConflictingOptions();
2521
+ const checkForUnknownOptions = () => {
2522
+ if (parsed.unknown.length > 0) {
2523
+ this.unknownOption(parsed.unknown[0]);
2524
+ }
2525
+ };
2526
+ const commandEvent = `command:${this.name()}`;
2527
+ if (this._actionHandler) {
2528
+ checkForUnknownOptions();
2529
+ this._processArguments();
2530
+ let promiseChain;
2531
+ promiseChain = this._chainOrCallHooks(promiseChain, "preAction");
2532
+ promiseChain = this._chainOrCall(
2533
+ promiseChain,
2534
+ () => this._actionHandler(this.processedArgs)
2535
+ );
2536
+ if (this.parent) {
2537
+ promiseChain = this._chainOrCall(promiseChain, () => {
2538
+ this.parent.emit(commandEvent, operands, unknown);
2539
+ });
2540
+ }
2541
+ promiseChain = this._chainOrCallHooks(promiseChain, "postAction");
2542
+ return promiseChain;
2543
+ }
2544
+ if (this.parent?.listenerCount(commandEvent)) {
2545
+ checkForUnknownOptions();
2546
+ this._processArguments();
2547
+ this.parent.emit(commandEvent, operands, unknown);
2548
+ } else if (operands.length) {
2549
+ if (this._findCommand("*")) {
2550
+ return this._dispatchSubcommand("*", operands, unknown);
2551
+ }
2552
+ if (this.listenerCount("command:*")) {
2553
+ this.emit("command:*", operands, unknown);
2554
+ } else if (this.commands.length) {
2555
+ this.unknownCommand();
2556
+ } else {
2557
+ checkForUnknownOptions();
2558
+ this._processArguments();
2559
+ }
2560
+ } else if (this.commands.length) {
2561
+ checkForUnknownOptions();
2562
+ this.help({ error: true });
2563
+ } else {
2564
+ checkForUnknownOptions();
2565
+ this._processArguments();
2566
+ }
2567
+ }
2568
+ /**
2569
+ * Find matching command.
2570
+ *
2571
+ * @private
2572
+ * @return {Command | undefined}
2573
+ */
2574
+ _findCommand(name) {
2575
+ if (!name) return void 0;
2576
+ return this.commands.find(
2577
+ (cmd) => cmd._name === name || cmd._aliases.includes(name)
2578
+ );
2579
+ }
2580
+ /**
2581
+ * Return an option matching `arg` if any.
2582
+ *
2583
+ * @param {string} arg
2584
+ * @return {Option}
2585
+ * @package
2586
+ */
2587
+ _findOption(arg) {
2588
+ return this.options.find((option) => option.is(arg));
2589
+ }
2590
+ /**
2591
+ * Display an error message if a mandatory option does not have a value.
2592
+ * Called after checking for help flags in leaf subcommand.
2593
+ *
2594
+ * @private
2595
+ */
2596
+ _checkForMissingMandatoryOptions() {
2597
+ this._getCommandAndAncestors().forEach((cmd) => {
2598
+ cmd.options.forEach((anOption) => {
2599
+ if (anOption.mandatory && cmd.getOptionValue(anOption.attributeName()) === void 0) {
2600
+ cmd.missingMandatoryOptionValue(anOption);
2601
+ }
2602
+ });
2603
+ });
2604
+ }
2605
+ /**
2606
+ * Display an error message if conflicting options are used together in this.
2607
+ *
2608
+ * @private
2609
+ */
2610
+ _checkForConflictingLocalOptions() {
2611
+ const definedNonDefaultOptions = this.options.filter((option) => {
2612
+ const optionKey = option.attributeName();
2613
+ if (this.getOptionValue(optionKey) === void 0) {
2614
+ return false;
2615
+ }
2616
+ return this.getOptionValueSource(optionKey) !== "default";
2617
+ });
2618
+ const optionsWithConflicting = definedNonDefaultOptions.filter(
2619
+ (option) => option.conflictsWith.length > 0
2620
+ );
2621
+ optionsWithConflicting.forEach((option) => {
2622
+ const conflictingAndDefined = definedNonDefaultOptions.find(
2623
+ (defined) => option.conflictsWith.includes(defined.attributeName())
2624
+ );
2625
+ if (conflictingAndDefined) {
2626
+ this._conflictingOption(option, conflictingAndDefined);
2627
+ }
2628
+ });
2629
+ }
2630
+ /**
2631
+ * Display an error message if conflicting options are used together.
2632
+ * Called after checking for help flags in leaf subcommand.
2633
+ *
2634
+ * @private
2635
+ */
2636
+ _checkForConflictingOptions() {
2637
+ this._getCommandAndAncestors().forEach((cmd) => {
2638
+ cmd._checkForConflictingLocalOptions();
2639
+ });
2640
+ }
2641
+ /**
2642
+ * Parse options from `argv` removing known options,
2643
+ * and return argv split into operands and unknown arguments.
2644
+ *
2645
+ * Side effects: modifies command by storing options. Does not reset state if called again.
2646
+ *
2647
+ * Examples:
2648
+ *
2649
+ * argv => operands, unknown
2650
+ * --known kkk op => [op], []
2651
+ * op --known kkk => [op], []
2652
+ * sub --unknown uuu op => [sub], [--unknown uuu op]
2653
+ * sub -- --unknown uuu op => [sub --unknown uuu op], []
2654
+ *
2655
+ * @param {string[]} args
2656
+ * @return {{operands: string[], unknown: string[]}}
2657
+ */
2658
+ parseOptions(args) {
2659
+ const operands = [];
2660
+ const unknown = [];
2661
+ let dest = operands;
2662
+ function maybeOption(arg) {
2663
+ return arg.length > 1 && arg[0] === "-";
2664
+ }
2665
+ const negativeNumberArg = (arg) => {
2666
+ if (!/^-(\d+|\d*\.\d+)(e[+-]?\d+)?$/.test(arg)) return false;
2667
+ return !this._getCommandAndAncestors().some(
2668
+ (cmd) => cmd.options.map((opt) => opt.short).some((short) => /^-\d$/.test(short))
2669
+ );
2670
+ };
2671
+ let activeVariadicOption = null;
2672
+ let activeGroup = null;
2673
+ let i = 0;
2674
+ while (i < args.length || activeGroup) {
2675
+ const arg = activeGroup ?? args[i++];
2676
+ activeGroup = null;
2677
+ if (arg === "--") {
2678
+ if (dest === unknown) dest.push(arg);
2679
+ dest.push(...args.slice(i));
2680
+ break;
2681
+ }
2682
+ if (activeVariadicOption && (!maybeOption(arg) || negativeNumberArg(arg))) {
2683
+ this.emit(`option:${activeVariadicOption.name()}`, arg);
2684
+ continue;
2685
+ }
2686
+ activeVariadicOption = null;
2687
+ if (maybeOption(arg)) {
2688
+ const option = this._findOption(arg);
2689
+ if (option) {
2690
+ if (option.required) {
2691
+ const value = args[i++];
2692
+ if (value === void 0) this.optionMissingArgument(option);
2693
+ this.emit(`option:${option.name()}`, value);
2694
+ } else if (option.optional) {
2695
+ let value = null;
2696
+ if (i < args.length && (!maybeOption(args[i]) || negativeNumberArg(args[i]))) {
2697
+ value = args[i++];
2698
+ }
2699
+ this.emit(`option:${option.name()}`, value);
2700
+ } else {
2701
+ this.emit(`option:${option.name()}`);
2702
+ }
2703
+ activeVariadicOption = option.variadic ? option : null;
2704
+ continue;
2705
+ }
2706
+ }
2707
+ if (arg.length > 2 && arg[0] === "-" && arg[1] !== "-") {
2708
+ const option = this._findOption(`-${arg[1]}`);
2709
+ if (option) {
2710
+ if (option.required || option.optional && this._combineFlagAndOptionalValue) {
2711
+ this.emit(`option:${option.name()}`, arg.slice(2));
2712
+ } else {
2713
+ this.emit(`option:${option.name()}`);
2714
+ activeGroup = `-${arg.slice(2)}`;
2715
+ }
2716
+ continue;
2717
+ }
2718
+ }
2719
+ if (/^--[^=]+=/.test(arg)) {
2720
+ const index = arg.indexOf("=");
2721
+ const option = this._findOption(arg.slice(0, index));
2722
+ if (option && (option.required || option.optional)) {
2723
+ this.emit(`option:${option.name()}`, arg.slice(index + 1));
2724
+ continue;
2725
+ }
2726
+ }
2727
+ if (dest === operands && maybeOption(arg) && !(this.commands.length === 0 && negativeNumberArg(arg))) {
2728
+ dest = unknown;
2729
+ }
2730
+ if ((this._enablePositionalOptions || this._passThroughOptions) && operands.length === 0 && unknown.length === 0) {
2731
+ if (this._findCommand(arg)) {
2732
+ operands.push(arg);
2733
+ unknown.push(...args.slice(i));
2734
+ break;
2735
+ } else if (this._getHelpCommand() && arg === this._getHelpCommand().name()) {
2736
+ operands.push(arg, ...args.slice(i));
2737
+ break;
2738
+ } else if (this._defaultCommandName) {
2739
+ unknown.push(arg, ...args.slice(i));
2740
+ break;
2741
+ }
2742
+ }
2743
+ if (this._passThroughOptions) {
2744
+ dest.push(arg, ...args.slice(i));
2745
+ break;
2746
+ }
2747
+ dest.push(arg);
2748
+ }
2749
+ return { operands, unknown };
2750
+ }
2751
+ /**
2752
+ * Return an object containing local option values as key-value pairs.
2753
+ *
2754
+ * @return {object}
2755
+ */
2756
+ opts() {
2757
+ if (this._storeOptionsAsProperties) {
2758
+ const result = {};
2759
+ const len = this.options.length;
2760
+ for (let i = 0; i < len; i++) {
2761
+ const key = this.options[i].attributeName();
2762
+ result[key] = key === this._versionOptionName ? this._version : this[key];
2763
+ }
2764
+ return result;
2765
+ }
2766
+ return this._optionValues;
2767
+ }
2768
+ /**
2769
+ * Return an object containing merged local and global option values as key-value pairs.
2770
+ *
2771
+ * @return {object}
2772
+ */
2773
+ optsWithGlobals() {
2774
+ return this._getCommandAndAncestors().reduce(
2775
+ (combinedOptions, cmd) => Object.assign(combinedOptions, cmd.opts()),
2776
+ {}
2777
+ );
2778
+ }
2779
+ /**
2780
+ * Display error message and exit (or call exitOverride).
2781
+ *
2782
+ * @param {string} message
2783
+ * @param {object} [errorOptions]
2784
+ * @param {string} [errorOptions.code] - an id string representing the error
2785
+ * @param {number} [errorOptions.exitCode] - used with process.exit
2786
+ */
2787
+ error(message, errorOptions) {
2788
+ this._outputConfiguration.outputError(
2789
+ `${message}
2790
+ `,
2791
+ this._outputConfiguration.writeErr
2792
+ );
2793
+ if (typeof this._showHelpAfterError === "string") {
2794
+ this._outputConfiguration.writeErr(`${this._showHelpAfterError}
2795
+ `);
2796
+ } else if (this._showHelpAfterError) {
2797
+ this._outputConfiguration.writeErr("\n");
2798
+ this.outputHelp({ error: true });
2799
+ }
2800
+ const config = errorOptions || {};
2801
+ const exitCode = config.exitCode || 1;
2802
+ const code = config.code || "commander.error";
2803
+ this._exit(exitCode, code, message);
2804
+ }
2805
+ /**
2806
+ * Apply any option related environment variables, if option does
2807
+ * not have a value from cli or client code.
2808
+ *
2809
+ * @private
2810
+ */
2811
+ _parseOptionsEnv() {
2812
+ this.options.forEach((option) => {
2813
+ if (option.envVar && option.envVar in process2.env) {
2814
+ const optionKey = option.attributeName();
2815
+ if (this.getOptionValue(optionKey) === void 0 || ["default", "config", "env"].includes(
2816
+ this.getOptionValueSource(optionKey)
2817
+ )) {
2818
+ if (option.required || option.optional) {
2819
+ this.emit(`optionEnv:${option.name()}`, process2.env[option.envVar]);
2820
+ } else {
2821
+ this.emit(`optionEnv:${option.name()}`);
2822
+ }
2823
+ }
2824
+ }
2825
+ });
2826
+ }
2827
+ /**
2828
+ * Apply any implied option values, if option is undefined or default value.
2829
+ *
2830
+ * @private
2831
+ */
2832
+ _parseOptionsImplied() {
2833
+ const dualHelper = new DualOptions(this.options);
2834
+ const hasCustomOptionValue = (optionKey) => {
2835
+ return this.getOptionValue(optionKey) !== void 0 && !["default", "implied"].includes(this.getOptionValueSource(optionKey));
2836
+ };
2837
+ this.options.filter(
2838
+ (option) => option.implied !== void 0 && hasCustomOptionValue(option.attributeName()) && dualHelper.valueFromOption(
2839
+ this.getOptionValue(option.attributeName()),
2840
+ option
2841
+ )
2842
+ ).forEach((option) => {
2843
+ Object.keys(option.implied).filter((impliedKey) => !hasCustomOptionValue(impliedKey)).forEach((impliedKey) => {
2844
+ this.setOptionValueWithSource(
2845
+ impliedKey,
2846
+ option.implied[impliedKey],
2847
+ "implied"
2848
+ );
2849
+ });
2850
+ });
2851
+ }
2852
+ /**
2853
+ * Argument `name` is missing.
2854
+ *
2855
+ * @param {string} name
2856
+ * @private
2857
+ */
2858
+ missingArgument(name) {
2859
+ const message = `error: missing required argument '${name}'`;
2860
+ this.error(message, { code: "commander.missingArgument" });
2861
+ }
2862
+ /**
2863
+ * `Option` is missing an argument.
2864
+ *
2865
+ * @param {Option} option
2866
+ * @private
2867
+ */
2868
+ optionMissingArgument(option) {
2869
+ const message = `error: option '${option.flags}' argument missing`;
2870
+ this.error(message, { code: "commander.optionMissingArgument" });
2871
+ }
2872
+ /**
2873
+ * `Option` does not have a value, and is a mandatory option.
2874
+ *
2875
+ * @param {Option} option
2876
+ * @private
2877
+ */
2878
+ missingMandatoryOptionValue(option) {
2879
+ const message = `error: required option '${option.flags}' not specified`;
2880
+ this.error(message, { code: "commander.missingMandatoryOptionValue" });
2881
+ }
2882
+ /**
2883
+ * `Option` conflicts with another option.
2884
+ *
2885
+ * @param {Option} option
2886
+ * @param {Option} conflictingOption
2887
+ * @private
2888
+ */
2889
+ _conflictingOption(option, conflictingOption) {
2890
+ const findBestOptionFromValue = (option2) => {
2891
+ const optionKey = option2.attributeName();
2892
+ const optionValue = this.getOptionValue(optionKey);
2893
+ const negativeOption = this.options.find(
2894
+ (target) => target.negate && optionKey === target.attributeName()
2895
+ );
2896
+ const positiveOption = this.options.find(
2897
+ (target) => !target.negate && optionKey === target.attributeName()
2898
+ );
2899
+ if (negativeOption && (negativeOption.presetArg === void 0 && optionValue === false || negativeOption.presetArg !== void 0 && optionValue === negativeOption.presetArg)) {
2900
+ return negativeOption;
2901
+ }
2902
+ return positiveOption || option2;
2903
+ };
2904
+ const getErrorMessage = (option2) => {
2905
+ const bestOption = findBestOptionFromValue(option2);
2906
+ const optionKey = bestOption.attributeName();
2907
+ const source = this.getOptionValueSource(optionKey);
2908
+ if (source === "env") {
2909
+ return `environment variable '${bestOption.envVar}'`;
2910
+ }
2911
+ return `option '${bestOption.flags}'`;
2912
+ };
2913
+ const message = `error: ${getErrorMessage(option)} cannot be used with ${getErrorMessage(conflictingOption)}`;
2914
+ this.error(message, { code: "commander.conflictingOption" });
2915
+ }
2916
+ /**
2917
+ * Unknown option `flag`.
2918
+ *
2919
+ * @param {string} flag
2920
+ * @private
2921
+ */
2922
+ unknownOption(flag) {
2923
+ if (this._allowUnknownOption) return;
2924
+ let suggestion = "";
2925
+ if (flag.startsWith("--") && this._showSuggestionAfterError) {
2926
+ let candidateFlags = [];
2927
+ let command = this;
2928
+ do {
2929
+ const moreFlags = command.createHelp().visibleOptions(command).filter((option) => option.long).map((option) => option.long);
2930
+ candidateFlags = candidateFlags.concat(moreFlags);
2931
+ command = command.parent;
2932
+ } while (command && !command._enablePositionalOptions);
2933
+ suggestion = suggestSimilar(flag, candidateFlags);
2934
+ }
2935
+ const message = `error: unknown option '${flag}'${suggestion}`;
2936
+ this.error(message, { code: "commander.unknownOption" });
2937
+ }
2938
+ /**
2939
+ * Excess arguments, more than expected.
2940
+ *
2941
+ * @param {string[]} receivedArgs
2942
+ * @private
2943
+ */
2944
+ _excessArguments(receivedArgs) {
2945
+ if (this._allowExcessArguments) return;
2946
+ const expected = this.registeredArguments.length;
2947
+ const s = expected === 1 ? "" : "s";
2948
+ const forSubcommand = this.parent ? ` for '${this.name()}'` : "";
2949
+ const message = `error: too many arguments${forSubcommand}. Expected ${expected} argument${s} but got ${receivedArgs.length}.`;
2950
+ this.error(message, { code: "commander.excessArguments" });
2951
+ }
2952
+ /**
2953
+ * Unknown command.
2954
+ *
2955
+ * @private
2956
+ */
2957
+ unknownCommand() {
2958
+ const unknownName = this.args[0];
2959
+ let suggestion = "";
2960
+ if (this._showSuggestionAfterError) {
2961
+ const candidateNames = [];
2962
+ this.createHelp().visibleCommands(this).forEach((command) => {
2963
+ candidateNames.push(command.name());
2964
+ if (command.alias()) candidateNames.push(command.alias());
2965
+ });
2966
+ suggestion = suggestSimilar(unknownName, candidateNames);
2967
+ }
2968
+ const message = `error: unknown command '${unknownName}'${suggestion}`;
2969
+ this.error(message, { code: "commander.unknownCommand" });
2970
+ }
2971
+ /**
2972
+ * Get or set the program version.
2973
+ *
2974
+ * This method auto-registers the "-V, --version" option which will print the version number.
2975
+ *
2976
+ * You can optionally supply the flags and description to override the defaults.
2977
+ *
2978
+ * @param {string} [str]
2979
+ * @param {string} [flags]
2980
+ * @param {string} [description]
2981
+ * @return {(this | string | undefined)} `this` command for chaining, or version string if no arguments
2982
+ */
2983
+ version(str, flags, description) {
2984
+ if (str === void 0) return this._version;
2985
+ this._version = str;
2986
+ flags = flags || "-V, --version";
2987
+ description = description || "output the version number";
2988
+ const versionOption = this.createOption(flags, description);
2989
+ this._versionOptionName = versionOption.attributeName();
2990
+ this._registerOption(versionOption);
2991
+ this.on("option:" + versionOption.name(), () => {
2992
+ this._outputConfiguration.writeOut(`${str}
2993
+ `);
2994
+ this._exit(0, "commander.version", str);
2995
+ });
2996
+ return this;
2997
+ }
2998
+ /**
2999
+ * Set the description.
3000
+ *
3001
+ * @param {string} [str]
3002
+ * @param {object} [argsDescription]
3003
+ * @return {(string|Command)}
3004
+ */
3005
+ description(str, argsDescription) {
3006
+ if (str === void 0 && argsDescription === void 0)
3007
+ return this._description;
3008
+ this._description = str;
3009
+ if (argsDescription) {
3010
+ this._argsDescription = argsDescription;
3011
+ }
3012
+ return this;
3013
+ }
3014
+ /**
3015
+ * Set the summary. Used when listed as subcommand of parent.
3016
+ *
3017
+ * @param {string} [str]
3018
+ * @return {(string|Command)}
3019
+ */
3020
+ summary(str) {
3021
+ if (str === void 0) return this._summary;
3022
+ this._summary = str;
3023
+ return this;
3024
+ }
3025
+ /**
3026
+ * Set an alias for the command.
3027
+ *
3028
+ * You may call more than once to add multiple aliases. Only the first alias is shown in the auto-generated help.
3029
+ *
3030
+ * @param {string} [alias]
3031
+ * @return {(string|Command)}
3032
+ */
3033
+ alias(alias) {
3034
+ if (alias === void 0) return this._aliases[0];
3035
+ let command = this;
3036
+ if (this.commands.length !== 0 && this.commands[this.commands.length - 1]._executableHandler) {
3037
+ command = this.commands[this.commands.length - 1];
3038
+ }
3039
+ if (alias === command._name)
3040
+ throw new Error("Command alias can't be the same as its name");
3041
+ const matchingCommand = this.parent?._findCommand(alias);
3042
+ if (matchingCommand) {
3043
+ const existingCmd = [matchingCommand.name()].concat(matchingCommand.aliases()).join("|");
3044
+ throw new Error(
3045
+ `cannot add alias '${alias}' to command '${this.name()}' as already have command '${existingCmd}'`
3046
+ );
3047
+ }
3048
+ command._aliases.push(alias);
3049
+ return this;
3050
+ }
3051
+ /**
3052
+ * Set aliases for the command.
3053
+ *
3054
+ * Only the first alias is shown in the auto-generated help.
3055
+ *
3056
+ * @param {string[]} [aliases]
3057
+ * @return {(string[]|Command)}
3058
+ */
3059
+ aliases(aliases) {
3060
+ if (aliases === void 0) return this._aliases;
3061
+ aliases.forEach((alias) => this.alias(alias));
3062
+ return this;
3063
+ }
3064
+ /**
3065
+ * Set / get the command usage `str`.
3066
+ *
3067
+ * @param {string} [str]
3068
+ * @return {(string|Command)}
3069
+ */
3070
+ usage(str) {
3071
+ if (str === void 0) {
3072
+ if (this._usage) return this._usage;
3073
+ const args = this.registeredArguments.map((arg) => {
3074
+ return humanReadableArgName(arg);
3075
+ });
3076
+ return [].concat(
3077
+ this.options.length || this._helpOption !== null ? "[options]" : [],
3078
+ this.commands.length ? "[command]" : [],
3079
+ this.registeredArguments.length ? args : []
3080
+ ).join(" ");
3081
+ }
3082
+ this._usage = str;
3083
+ return this;
3084
+ }
3085
+ /**
3086
+ * Get or set the name of the command.
3087
+ *
3088
+ * @param {string} [str]
3089
+ * @return {(string|Command)}
3090
+ */
3091
+ name(str) {
3092
+ if (str === void 0) return this._name;
3093
+ this._name = str;
3094
+ return this;
3095
+ }
3096
+ /**
3097
+ * Set/get the help group heading for this subcommand in parent command's help.
3098
+ *
3099
+ * @param {string} [heading]
3100
+ * @return {Command | string}
3101
+ */
3102
+ helpGroup(heading) {
3103
+ if (heading === void 0) return this._helpGroupHeading ?? "";
3104
+ this._helpGroupHeading = heading;
3105
+ return this;
3106
+ }
3107
+ /**
3108
+ * Set/get the default help group heading for subcommands added to this command.
3109
+ * (This does not override a group set directly on the subcommand using .helpGroup().)
3110
+ *
3111
+ * @example
3112
+ * program.commandsGroup('Development Commands:);
3113
+ * program.command('watch')...
3114
+ * program.command('lint')...
3115
+ * ...
3116
+ *
3117
+ * @param {string} [heading]
3118
+ * @returns {Command | string}
3119
+ */
3120
+ commandsGroup(heading) {
3121
+ if (heading === void 0) return this._defaultCommandGroup ?? "";
3122
+ this._defaultCommandGroup = heading;
3123
+ return this;
3124
+ }
3125
+ /**
3126
+ * Set/get the default help group heading for options added to this command.
3127
+ * (This does not override a group set directly on the option using .helpGroup().)
3128
+ *
3129
+ * @example
3130
+ * program
3131
+ * .optionsGroup('Development Options:')
3132
+ * .option('-d, --debug', 'output extra debugging')
3133
+ * .option('-p, --profile', 'output profiling information')
3134
+ *
3135
+ * @param {string} [heading]
3136
+ * @returns {Command | string}
3137
+ */
3138
+ optionsGroup(heading) {
3139
+ if (heading === void 0) return this._defaultOptionGroup ?? "";
3140
+ this._defaultOptionGroup = heading;
3141
+ return this;
3142
+ }
3143
+ /**
3144
+ * @param {Option} option
3145
+ * @private
3146
+ */
3147
+ _initOptionGroup(option) {
3148
+ if (this._defaultOptionGroup && !option.helpGroupHeading)
3149
+ option.helpGroup(this._defaultOptionGroup);
3150
+ }
3151
+ /**
3152
+ * @param {Command} cmd
3153
+ * @private
3154
+ */
3155
+ _initCommandGroup(cmd) {
3156
+ if (this._defaultCommandGroup && !cmd.helpGroup())
3157
+ cmd.helpGroup(this._defaultCommandGroup);
3158
+ }
3159
+ /**
3160
+ * Set the name of the command from script filename, such as process.argv[1],
3161
+ * or require.main.filename, or __filename.
3162
+ *
3163
+ * (Used internally and public although not documented in README.)
3164
+ *
3165
+ * @example
3166
+ * program.nameFromFilename(require.main.filename);
3167
+ *
3168
+ * @param {string} filename
3169
+ * @return {Command}
3170
+ */
3171
+ nameFromFilename(filename) {
3172
+ this._name = path.basename(filename, path.extname(filename));
3173
+ return this;
3174
+ }
3175
+ /**
3176
+ * Get or set the directory for searching for executable subcommands of this command.
3177
+ *
3178
+ * @example
3179
+ * program.executableDir(__dirname);
3180
+ * // or
3181
+ * program.executableDir('subcommands');
3182
+ *
3183
+ * @param {string} [path]
3184
+ * @return {(string|null|Command)}
3185
+ */
3186
+ executableDir(path2) {
3187
+ if (path2 === void 0) return this._executableDir;
3188
+ this._executableDir = path2;
3189
+ return this;
3190
+ }
3191
+ /**
3192
+ * Return program help documentation.
3193
+ *
3194
+ * @param {{ error: boolean }} [contextOptions] - pass {error:true} to wrap for stderr instead of stdout
3195
+ * @return {string}
3196
+ */
3197
+ helpInformation(contextOptions) {
3198
+ const helper = this.createHelp();
3199
+ const context = this._getOutputContext(contextOptions);
3200
+ helper.prepareContext({
3201
+ error: context.error,
3202
+ helpWidth: context.helpWidth,
3203
+ outputHasColors: context.hasColors
3204
+ });
3205
+ const text = helper.formatHelp(this, helper);
3206
+ if (context.hasColors) return text;
3207
+ return this._outputConfiguration.stripColor(text);
3208
+ }
3209
+ /**
3210
+ * @typedef HelpContext
3211
+ * @type {object}
3212
+ * @property {boolean} error
3213
+ * @property {number} helpWidth
3214
+ * @property {boolean} hasColors
3215
+ * @property {function} write - includes stripColor if needed
3216
+ *
3217
+ * @returns {HelpContext}
3218
+ * @private
3219
+ */
3220
+ _getOutputContext(contextOptions) {
3221
+ contextOptions = contextOptions || {};
3222
+ const error = !!contextOptions.error;
3223
+ let baseWrite;
3224
+ let hasColors;
3225
+ let helpWidth;
3226
+ if (error) {
3227
+ baseWrite = (str) => this._outputConfiguration.writeErr(str);
3228
+ hasColors = this._outputConfiguration.getErrHasColors();
3229
+ helpWidth = this._outputConfiguration.getErrHelpWidth();
3230
+ } else {
3231
+ baseWrite = (str) => this._outputConfiguration.writeOut(str);
3232
+ hasColors = this._outputConfiguration.getOutHasColors();
3233
+ helpWidth = this._outputConfiguration.getOutHelpWidth();
3234
+ }
3235
+ const write = (str) => {
3236
+ if (!hasColors) str = this._outputConfiguration.stripColor(str);
3237
+ return baseWrite(str);
3238
+ };
3239
+ return { error, write, hasColors, helpWidth };
3240
+ }
3241
+ /**
3242
+ * Output help information for this command.
3243
+ *
3244
+ * Outputs built-in help, and custom text added using `.addHelpText()`.
3245
+ *
3246
+ * @param {{ error: boolean } | Function} [contextOptions] - pass {error:true} to write to stderr instead of stdout
3247
+ */
3248
+ outputHelp(contextOptions) {
3249
+ let deprecatedCallback;
3250
+ if (typeof contextOptions === "function") {
3251
+ deprecatedCallback = contextOptions;
3252
+ contextOptions = void 0;
3253
+ }
3254
+ const outputContext = this._getOutputContext(contextOptions);
3255
+ const eventContext = {
3256
+ error: outputContext.error,
3257
+ write: outputContext.write,
3258
+ command: this
3259
+ };
3260
+ this._getCommandAndAncestors().reverse().forEach((command) => command.emit("beforeAllHelp", eventContext));
3261
+ this.emit("beforeHelp", eventContext);
3262
+ let helpInformation = this.helpInformation({ error: outputContext.error });
3263
+ if (deprecatedCallback) {
3264
+ helpInformation = deprecatedCallback(helpInformation);
3265
+ if (typeof helpInformation !== "string" && !Buffer.isBuffer(helpInformation)) {
3266
+ throw new Error("outputHelp callback must return a string or a Buffer");
3267
+ }
3268
+ }
3269
+ outputContext.write(helpInformation);
3270
+ if (this._getHelpOption()?.long) {
3271
+ this.emit(this._getHelpOption().long);
3272
+ }
3273
+ this.emit("afterHelp", eventContext);
3274
+ this._getCommandAndAncestors().forEach(
3275
+ (command) => command.emit("afterAllHelp", eventContext)
3276
+ );
3277
+ }
3278
+ /**
3279
+ * You can pass in flags and a description to customise the built-in help option.
3280
+ * Pass in false to disable the built-in help option.
3281
+ *
3282
+ * @example
3283
+ * program.helpOption('-?, --help' 'show help'); // customise
3284
+ * program.helpOption(false); // disable
3285
+ *
3286
+ * @param {(string | boolean)} flags
3287
+ * @param {string} [description]
3288
+ * @return {Command} `this` command for chaining
3289
+ */
3290
+ helpOption(flags, description) {
3291
+ if (typeof flags === "boolean") {
3292
+ if (flags) {
3293
+ if (this._helpOption === null) this._helpOption = void 0;
3294
+ if (this._defaultOptionGroup) {
3295
+ this._initOptionGroup(this._getHelpOption());
3296
+ }
3297
+ } else {
3298
+ this._helpOption = null;
3299
+ }
3300
+ return this;
3301
+ }
3302
+ this._helpOption = this.createOption(
3303
+ flags ?? "-h, --help",
3304
+ description ?? "display help for command"
3305
+ );
3306
+ if (flags || description) this._initOptionGroup(this._helpOption);
3307
+ return this;
3308
+ }
3309
+ /**
3310
+ * Lazy create help option.
3311
+ * Returns null if has been disabled with .helpOption(false).
3312
+ *
3313
+ * @returns {(Option | null)} the help option
3314
+ * @package
3315
+ */
3316
+ _getHelpOption() {
3317
+ if (this._helpOption === void 0) {
3318
+ this.helpOption(void 0, void 0);
3319
+ }
3320
+ return this._helpOption;
3321
+ }
3322
+ /**
3323
+ * Supply your own option to use for the built-in help option.
3324
+ * This is an alternative to using helpOption() to customise the flags and description etc.
3325
+ *
3326
+ * @param {Option} option
3327
+ * @return {Command} `this` command for chaining
3328
+ */
3329
+ addHelpOption(option) {
3330
+ this._helpOption = option;
3331
+ this._initOptionGroup(option);
3332
+ return this;
3333
+ }
3334
+ /**
3335
+ * Output help information and exit.
3336
+ *
3337
+ * Outputs built-in help, and custom text added using `.addHelpText()`.
3338
+ *
3339
+ * @param {{ error: boolean }} [contextOptions] - pass {error:true} to write to stderr instead of stdout
3340
+ */
3341
+ help(contextOptions) {
3342
+ this.outputHelp(contextOptions);
3343
+ let exitCode = Number(process2.exitCode ?? 0);
3344
+ if (exitCode === 0 && contextOptions && typeof contextOptions !== "function" && contextOptions.error) {
3345
+ exitCode = 1;
3346
+ }
3347
+ this._exit(exitCode, "commander.help", "(outputHelp)");
3348
+ }
3349
+ /**
3350
+ * // Do a little typing to coordinate emit and listener for the help text events.
3351
+ * @typedef HelpTextEventContext
3352
+ * @type {object}
3353
+ * @property {boolean} error
3354
+ * @property {Command} command
3355
+ * @property {function} write
3356
+ */
3357
+ /**
3358
+ * Add additional text to be displayed with the built-in help.
3359
+ *
3360
+ * Position is 'before' or 'after' to affect just this command,
3361
+ * and 'beforeAll' or 'afterAll' to affect this command and all its subcommands.
3362
+ *
3363
+ * @param {string} position - before or after built-in help
3364
+ * @param {(string | Function)} text - string to add, or a function returning a string
3365
+ * @return {Command} `this` command for chaining
3366
+ */
3367
+ addHelpText(position, text) {
3368
+ const allowedValues = ["beforeAll", "before", "after", "afterAll"];
3369
+ if (!allowedValues.includes(position)) {
3370
+ throw new Error(`Unexpected value for position to addHelpText.
3371
+ Expecting one of '${allowedValues.join("', '")}'`);
3372
+ }
3373
+ const helpEvent = `${position}Help`;
3374
+ this.on(helpEvent, (context) => {
3375
+ let helpStr;
3376
+ if (typeof text === "function") {
3377
+ helpStr = text({ error: context.error, command: context.command });
3378
+ } else {
3379
+ helpStr = text;
3380
+ }
3381
+ if (helpStr) {
3382
+ context.write(`${helpStr}
3383
+ `);
3384
+ }
3385
+ });
3386
+ return this;
3387
+ }
3388
+ /**
3389
+ * Output help information if help flags specified
3390
+ *
3391
+ * @param {Array} args - array of options to search for help flags
3392
+ * @private
3393
+ */
3394
+ _outputHelpIfRequested(args) {
3395
+ const helpOption = this._getHelpOption();
3396
+ const helpRequested = helpOption && args.find((arg) => helpOption.is(arg));
3397
+ if (helpRequested) {
3398
+ this.outputHelp();
3399
+ this._exit(0, "commander.helpDisplayed", "(outputHelp)");
3400
+ }
3401
+ }
3402
+ };
3403
+ function incrementNodeInspectorPort(args) {
3404
+ return args.map((arg) => {
3405
+ if (!arg.startsWith("--inspect")) {
3406
+ return arg;
3407
+ }
3408
+ let debugOption;
3409
+ let debugHost = "127.0.0.1";
3410
+ let debugPort = "9229";
3411
+ let match;
3412
+ if ((match = arg.match(/^(--inspect(-brk)?)$/)) !== null) {
3413
+ debugOption = match[1];
3414
+ } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/)) !== null) {
3415
+ debugOption = match[1];
3416
+ if (/^\d+$/.test(match[3])) {
3417
+ debugPort = match[3];
3418
+ } else {
3419
+ debugHost = match[3];
3420
+ }
3421
+ } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/)) !== null) {
3422
+ debugOption = match[1];
3423
+ debugHost = match[3];
3424
+ debugPort = match[4];
3425
+ }
3426
+ if (debugOption && debugPort !== "0") {
3427
+ return `${debugOption}=${debugHost}:${parseInt(debugPort) + 1}`;
3428
+ }
3429
+ return arg;
3430
+ });
3431
+ }
3432
+ function useColor() {
3433
+ if (process2.env.NO_COLOR || process2.env.FORCE_COLOR === "0" || process2.env.FORCE_COLOR === "false")
3434
+ return false;
3435
+ if (process2.env.FORCE_COLOR || process2.env.CLICOLOR_FORCE !== void 0)
3436
+ return true;
3437
+ return void 0;
3438
+ }
3439
+ exports.Command = Command2;
3440
+ exports.useColor = useColor;
3441
+ }
3442
+ });
3443
+
3444
+ // node_modules/commander/index.js
3445
+ var require_commander = __commonJS({
3446
+ "node_modules/commander/index.js"(exports) {
3447
+ "use strict";
3448
+ var { Argument: Argument2 } = require_argument();
3449
+ var { Command: Command2 } = require_command();
3450
+ var { CommanderError: CommanderError2, InvalidArgumentError: InvalidArgumentError2 } = require_error();
3451
+ var { Help: Help2 } = require_help();
3452
+ var { Option: Option2 } = require_option();
3453
+ exports.program = new Command2();
3454
+ exports.createCommand = (name) => new Command2(name);
3455
+ exports.createOption = (flags, description) => new Option2(flags, description);
3456
+ exports.createArgument = (name, description) => new Argument2(name, description);
3457
+ exports.Command = Command2;
3458
+ exports.Option = Option2;
3459
+ exports.Argument = Argument2;
3460
+ exports.Help = Help2;
3461
+ exports.CommanderError = CommanderError2;
3462
+ exports.InvalidArgumentError = InvalidArgumentError2;
3463
+ exports.InvalidOptionArgumentError = InvalidArgumentError2;
3464
+ }
3465
+ });
3466
+
3467
+ // node_modules/commander/esm.mjs
3468
+ var import_index = __toESM(require_commander(), 1);
3469
+ var {
3470
+ program,
3471
+ createCommand,
3472
+ createArgument,
3473
+ createOption,
3474
+ CommanderError,
3475
+ InvalidArgumentError,
3476
+ InvalidOptionArgumentError,
3477
+ // deprecated old name
3478
+ Command,
3479
+ Argument,
3480
+ Option,
3481
+ Help
3482
+ } = import_index.default;
3483
+
3484
+ // src/cli/update-check.ts
3485
+ import { join } from "path";
3486
+ var CACHE_TTL_MS = 864e5;
3487
+ function getCachePath() {
3488
+ return join(getConfigDir(), "cache", "update-check.json");
3489
+ }
3490
+ async function checkForUpdates() {
3491
+ if (process.env.CI || process.env.HIVE_NO_UPDATE_CHECK || !process.stderr.isTTY) {
3492
+ return;
3493
+ }
3494
+ const cached = readJsonFile(getCachePath());
3495
+ if (cached?.checkedAt) {
3496
+ const age = Date.now() - new Date(cached.checkedAt).getTime();
3497
+ if (age < CACHE_TTL_MS) {
3498
+ if (cached.latestVersion && cached.latestVersion !== CLI_VERSION) {
3499
+ showUpdateMessage(cached.latestVersion);
3500
+ }
3501
+ return;
3502
+ }
3503
+ }
3504
+ try {
3505
+ const controller = new AbortController();
3506
+ const timeout = setTimeout(() => controller.abort(), 3e3);
3507
+ const res = await fetch("https://registry.npmjs.org/hive-intelligence/latest", {
3508
+ signal: controller.signal
3509
+ });
3510
+ clearTimeout(timeout);
3511
+ if (!res.ok) return;
3512
+ const data = await res.json();
3513
+ ensureConfigDir();
3514
+ writeJsonFile(getCachePath(), {
3515
+ checkedAt: (/* @__PURE__ */ new Date()).toISOString(),
3516
+ latestVersion: data.version ?? null
3517
+ });
3518
+ if (!data.version || data.version === CLI_VERSION) return;
3519
+ showUpdateMessage(data.version);
3520
+ } catch {
3521
+ }
3522
+ }
3523
+ function showUpdateMessage(newVersion) {
3524
+ process.stderr.write(
3525
+ `
3526
+ Update available: ${CLI_VERSION} \u2192 ${newVersion}
3527
+ npm: npm update -g hive-intelligence
3528
+ bun: bun update -g hive-intelligence
3529
+
3530
+ `
3531
+ );
3532
+ }
3533
+
3534
+ // src/cli.ts
3535
+ process.on("unhandledRejection", (err) => {
3536
+ const msg = err instanceof Error ? process.env.DEBUG ? err.stack : err.message : String(err);
3537
+ process.stderr.write(`Fatal: ${msg}
3538
+ `);
3539
+ process.exit(ExitCode.GENERAL_ERROR);
3540
+ });
3541
+ process.on("uncaughtException", (err) => {
3542
+ process.stderr.write(
3543
+ `Fatal: ${process.env.DEBUG ? err.stack : err.message}
3544
+ `
3545
+ );
3546
+ process.exit(ExitCode.GENERAL_ERROR);
3547
+ });
3548
+ process.on("SIGINT", () => process.exit(130));
3549
+ process.on("SIGTERM", () => process.exit(143));
3550
+ var program2 = new Command();
3551
+ program2.name("hive").version(CLI_VERSION).description(
3552
+ "Hive Intelligence CLI \u2014 crypto, DeFi, stocks, forex, and macro data"
3553
+ ).exitOverride().configureOutput({
3554
+ writeErr: (str) => process.stderr.write(str),
3555
+ outputError: (str, write) => {
3556
+ write(process.stderr.isTTY ? red(str) : str);
3557
+ }
3558
+ }).showHelpAfterError("(use --help for usage)").option("--json", "Force JSON envelope output").option("--pretty", "Force human-readable output").option("--fields <list>", "Comma-separated fields to include in output").option("-q, --quiet", "Suppress all non-data output").option("-v, --verbose", "Show debug info").option("--no-color", "Disable ANSI colors").option("--env-file <path>", "Path to .env file", ".env").option("--timeout <ms>", "Tool execution timeout in ms", "30000").option("--no-retry", "Disable automatic retry on failure").option("--no-cache", "Bypass tool catalog cache").option("--jq <expr>", "Filter JSON output with query expression").option("--csv", "Output as CSV").option("--api-key <key>", "Override API key for this command");
3559
+ program2.hook("preAction", (thisCommand) => {
3560
+ const opts = thisCommand.opts();
3561
+ setOutputOptions({
3562
+ json: opts.json,
3563
+ pretty: opts.pretty,
3564
+ fields: opts.fields,
3565
+ quiet: opts.quiet,
3566
+ verbose: opts.verbose,
3567
+ noColor: opts.color === false,
3568
+ jq: opts.jq,
3569
+ csv: opts.csv
3570
+ });
3571
+ if (opts.verbose) {
3572
+ process.env.DEBUG = "1";
3573
+ }
3574
+ setCliFlags({ apiKey: opts.apiKey, noRetry: opts.retry === false });
3575
+ });
3576
+ program2.action(() => {
3577
+ program2.help();
3578
+ });
3579
+ for (const domain of NAMESPACE) {
3580
+ const domainCmd = program2.command(domain.name).description(domain.description);
3581
+ for (const sub of domain.commands) {
3582
+ const subCmd = domainCmd.command(sub.name).description(sub.description);
3583
+ if (sub.args) {
3584
+ for (const [, argDef] of Object.entries(sub.args)) {
3585
+ subCmd.option(
3586
+ argDef.flag,
3587
+ argDef.required ? `${argDef.description} (required)` : argDef.description
3588
+ );
3589
+ }
3590
+ }
3591
+ subCmd.option("--args <json>", "Pass all arguments as JSON");
3592
+ subCmd.action(async (opts) => {
3593
+ let args = {};
3594
+ if (opts.args) {
3595
+ try {
3596
+ args = JSON.parse(opts.args);
3597
+ } catch {
3598
+ process.stderr.write("Error: Invalid JSON in --args\n");
3599
+ process.exit(ExitCode.INVALID_ARGS);
3600
+ }
3601
+ }
3602
+ if (sub.args) {
3603
+ for (const [paramName, argDef] of Object.entries(sub.args)) {
3604
+ const flagName = argDef.flag.replace(/^--/, "").split(/[\s<]/)[0];
3605
+ if (opts[flagName] !== void 0) {
3606
+ args[paramName] = opts[flagName];
3607
+ }
3608
+ }
3609
+ }
3610
+ if (sub.args) {
3611
+ const missingRequired = Object.entries(sub.args).filter(
3612
+ ([paramName, argDef]) => argDef.required && args[paramName] === void 0
3613
+ );
3614
+ if (missingRequired.length > 0) {
3615
+ if (process.stdin.isTTY) {
3616
+ const { createInterface } = await import("readline");
3617
+ const rl = createInterface({
3618
+ input: process.stdin,
3619
+ output: process.stderr
3620
+ });
3621
+ const ask = (q) => new Promise((resolve) => rl.question(q, resolve));
3622
+ for (const [paramName, argDef] of missingRequired) {
3623
+ const answer = await ask(`${argDef.description || paramName}: `);
3624
+ if (answer.trim()) args[paramName] = answer.trim();
3625
+ }
3626
+ rl.close();
3627
+ }
3628
+ const stillMissing = missingRequired.filter(
3629
+ ([paramName]) => args[paramName] === void 0
3630
+ );
3631
+ if (stillMissing.length > 0) {
3632
+ const names = stillMissing.map(([, argDef]) => argDef.flag.split(/[\s<]/)[0]).join(", ");
3633
+ process.stderr.write(
3634
+ `Error: missing required option(s): ${names}
3635
+ `
3636
+ );
3637
+ process.exit(ExitCode.INVALID_ARGS);
3638
+ }
3639
+ }
3640
+ }
3641
+ const timeout = parseInt(program2.opts().timeout, 10);
3642
+ await executeTool(sub.tool, args, timeout);
3643
+ });
3644
+ }
3645
+ }
3646
+ var toolsCmd = program2.command("tools").description("Discover and execute tools");
3647
+ toolsCmd.command("list").description("List all registered tools").option("--category <name>", "Filter by category").option("--provider <name>", "Filter by provider prefix").option("--limit <n>", "Max tools to show", "50").option("--offset <n>", "Skip first N tools", "0").action(async (opts) => {
3648
+ const { listTools } = await import("./tools-4W3GGCUC.js");
3649
+ await listTools(opts);
3650
+ });
3651
+ toolsCmd.command("search <query>").description("Search tools by name or description").action(async (query) => {
3652
+ const { searchTools } = await import("./tools-4W3GGCUC.js");
3653
+ await searchTools(query);
3654
+ });
3655
+ toolsCmd.command("info <name>").description("Show detailed tool schema and description").action(async (name) => {
3656
+ const { toolInfo } = await import("./tools-4W3GGCUC.js");
3657
+ await toolInfo(name);
3658
+ });
3659
+ toolsCmd.command("call <name>").description("Execute a tool by name").option("--args <json>", "Tool arguments as JSON (or pipe JSON via stdin)").action(async (name, opts) => {
3660
+ let args = {};
3661
+ if (opts.args) {
3662
+ try {
3663
+ args = JSON.parse(opts.args);
3664
+ } catch {
3665
+ process.stderr.write("Error: Invalid JSON in --args\n");
3666
+ process.exit(ExitCode.INVALID_ARGS);
3667
+ }
3668
+ } else if (!process.stdin.isTTY) {
3669
+ const chunks = [];
3670
+ for await (const chunk of process.stdin) chunks.push(chunk);
3671
+ const input = Buffer.concat(chunks).toString("utf-8").trim();
3672
+ if (input) {
3673
+ try {
3674
+ args = JSON.parse(input);
3675
+ } catch {
3676
+ process.stderr.write("Error: Invalid JSON from stdin\n");
3677
+ process.exit(ExitCode.INVALID_ARGS);
3678
+ }
3679
+ }
3680
+ }
3681
+ const timeout = parseInt(program2.opts().timeout, 10);
3682
+ await executeTool(name, args, timeout);
3683
+ });
3684
+ toolsCmd.command("refresh").description("Force-refresh the tool catalog cache").action(async () => {
3685
+ const { refreshTools } = await import("./tools-4W3GGCUC.js");
3686
+ await refreshTools();
3687
+ });
3688
+ var configCmd = program2.command("config").description("Generate configuration for MCP clients");
3689
+ configCmd.command("claude-desktop").description("Print Claude Desktop config JSON").action(async () => {
3690
+ const { configClaudeDesktop } = await import("./config-2VDB2ZHE.js");
3691
+ configClaudeDesktop();
3692
+ });
3693
+ configCmd.command("cursor").description("Print Cursor config JSON").action(async () => {
3694
+ const { configCursor } = await import("./config-2VDB2ZHE.js");
3695
+ configCursor();
3696
+ });
3697
+ configCmd.command("vscode").description("Print VS Code mcp.json config").action(async () => {
3698
+ const { configVscode } = await import("./config-2VDB2ZHE.js");
3699
+ configVscode();
3700
+ });
3701
+ configCmd.command("claude-code").description("Print claude mcp add command").action(async () => {
3702
+ const { configClaudeCode } = await import("./config-2VDB2ZHE.js");
3703
+ configClaudeCode();
3704
+ });
3705
+ configCmd.command("http [url]").description("Print remote HTTP connection instructions").action(async (url) => {
3706
+ const { configHttpUrl } = await import("./config-2VDB2ZHE.js");
3707
+ configHttpUrl(
3708
+ url || process.env.HIVE_DEFAULT_URL || "https://mcp.hiveintelligence.xyz"
3709
+ );
3710
+ });
3711
+ program2.command("init").description("Interactive setup wizard for Hive API key").option("--minimal", "Write defaults without interactive prompts").option("--dry-run", "Preview changes without writing").action(async (opts) => {
3712
+ const { runInit } = await import("./init-YOJK6CH2.js");
3713
+ await runInit(opts);
3714
+ });
3715
+ program2.command("doctor").description("Diagnose environment and server connectivity").option("--probe", "Run live API probes (slower)").action(async (opts) => {
3716
+ const { runDoctor } = await import("./doctor-GYP6IHPP.js");
3717
+ await runDoctor(opts);
3718
+ });
3719
+ program2.command("completion <shell>").description("Generate shell completion script (bash, zsh, fish, powershell)").option("--install", "Auto-install to shell rc file").action(async (shell, opts) => {
3720
+ if (opts.install) {
3721
+ const { installCompletion } = await import("./completion-N35TWBLT.js");
3722
+ await installCompletion(shell);
3723
+ } else {
3724
+ const { generateCompletion } = await import("./completion-N35TWBLT.js");
3725
+ await generateCompletion(shell);
3726
+ }
3727
+ });
3728
+ var authCmd = program2.command("auth").description("Manage authentication profiles");
3729
+ authCmd.command("login").description("Log in with your Hive API key").option("--profile <name>", "Profile name", "default").action(async (opts) => {
3730
+ const { runLogin } = await import("./auth-PVT4GTAD.js");
3731
+ await runLogin(opts);
3732
+ });
3733
+ authCmd.command("logout").description("Remove stored credentials").action(async () => {
3734
+ const { runLogout } = await import("./auth-PVT4GTAD.js");
3735
+ await runLogout();
3736
+ });
3737
+ authCmd.command("whoami").description("Show current profile").action(async () => {
3738
+ const { runWhoami } = await import("./auth-PVT4GTAD.js");
3739
+ await runWhoami();
3740
+ });
3741
+ authCmd.command("profiles").description("List all profiles").action(async () => {
3742
+ const { runProfiles } = await import("./auth-PVT4GTAD.js");
3743
+ await runProfiles();
3744
+ });
3745
+ authCmd.command("switch <name>").description("Switch active profile").action(async (name) => {
3746
+ const { runSwitch } = await import("./auth-PVT4GTAD.js");
3747
+ await runSwitch(name);
3748
+ });
3749
+ program2.command("status").description("Quick health and version check").action(async () => {
3750
+ const { runStatus } = await import("./doctor-GYP6IHPP.js");
3751
+ await runStatus();
3752
+ });
3753
+ program2.command("open [target]").description("Open Hive dashboard, docs, status, or GitHub in browser").action(async (target) => {
3754
+ const { runOpen } = await import("./open-FUXYIHFO.js");
3755
+ runOpen(target);
3756
+ });
3757
+ program2.command("watch <domain> <command>").description("Poll a tool on interval").option("--interval <seconds>", "Poll interval in seconds", "30").option("--args <json>", "Tool arguments as JSON").action(async (domain, command, opts) => {
3758
+ const domainDef = NAMESPACE.find((d) => d.name === domain);
3759
+ if (!domainDef) {
3760
+ process.stderr.write(`Unknown domain: ${domain}
3761
+ `);
3762
+ process.exit(2);
3763
+ }
3764
+ const cmdDef = domainDef.commands.find((c) => c.name === command);
3765
+ if (!cmdDef) {
3766
+ process.stderr.write(`Unknown command: ${domain} ${command}
3767
+ `);
3768
+ process.exit(2);
3769
+ }
3770
+ let args = {};
3771
+ if (opts.args) {
3772
+ try {
3773
+ args = JSON.parse(opts.args);
3774
+ } catch {
3775
+ process.stderr.write("Invalid JSON\n");
3776
+ process.exit(2);
3777
+ }
3778
+ }
3779
+ const interval = parseInt(opts.interval, 10);
3780
+ const timeout = parseInt(program2.opts().timeout, 10);
3781
+ const { runWatch } = await import("./watch-P2QWGFYV.js");
3782
+ await runWatch(cmdDef.tool, args, interval, timeout);
3783
+ });
3784
+ var aliasCmd = program2.command("alias").description("Manage command aliases");
3785
+ aliasCmd.command("set <name> <command>").description("Create an alias").action(async (name, command) => {
3786
+ const { setAlias } = await import("./alias-INGXWFCG.js");
3787
+ setAlias(name, command);
3788
+ process.stderr.write(`Alias "${name}" set.
3789
+ `);
3790
+ });
3791
+ aliasCmd.command("list").description("Show all aliases").action(async () => {
3792
+ const { getAliases } = await import("./alias-INGXWFCG.js");
3793
+ const aliases = getAliases();
3794
+ const entries = Object.entries(aliases);
3795
+ if (entries.length === 0) {
3796
+ process.stderr.write("No aliases configured.\n");
3797
+ return;
3798
+ }
3799
+ for (const [name, cmd] of entries) {
3800
+ process.stderr.write(` ${name} \u2192 ${cmd}
3801
+ `);
3802
+ }
3803
+ process.stderr.write("\n");
3804
+ });
3805
+ aliasCmd.command("remove <name>").description("Remove an alias").action(async (name) => {
3806
+ const { removeAlias } = await import("./alias-INGXWFCG.js");
3807
+ removeAlias(name);
3808
+ process.stderr.write(`Alias "${name}" removed.
3809
+ `);
3810
+ });
3811
+ var telemetryCmd = program2.command("telemetry").description("Control anonymous usage telemetry");
3812
+ telemetryCmd.command("enable").description("Enable telemetry").action(async () => {
3813
+ const { enableTelemetry } = await import("./telemetry-KNWMQURH.js");
3814
+ enableTelemetry();
3815
+ });
3816
+ telemetryCmd.command("disable").description("Disable telemetry").action(async () => {
3817
+ const { disableTelemetry } = await import("./telemetry-KNWMQURH.js");
3818
+ disableTelemetry();
3819
+ });
3820
+ telemetryCmd.command("status").description("Show telemetry status").action(async () => {
3821
+ const { telemetryStatus } = await import("./telemetry-KNWMQURH.js");
3822
+ telemetryStatus();
3823
+ });
3824
+ program2.addHelpText(
3825
+ "after",
3826
+ `
3827
+ Examples:
3828
+ $ hive auth login
3829
+ $ hive market price --ids bitcoin --vs usd
3830
+ $ hive defi tvl --protocol aave
3831
+ $ hive stocks quote --symbol AAPL
3832
+ $ hive tools search "price" --jq ".[] | .name"
3833
+ $ hive status
3834
+ $ hive alias set btc 'market price --ids bitcoin --vs usd'
3835
+
3836
+ Run 'hive <domain> --help' for domain commands.
3837
+ Run 'hive tools list' for the full catalog.`
3838
+ );
3839
+ checkForUpdates();
3840
+ {
3841
+ const { expandAlias } = await import("./alias-INGXWFCG.js");
3842
+ const expanded = expandAlias(process.argv);
3843
+ if (expanded !== process.argv) {
3844
+ process.argv = expanded;
3845
+ }
3846
+ }
3847
+ try {
3848
+ await program2.parseAsync();
3849
+ } catch (err) {
3850
+ if (err instanceof CommanderError) {
3851
+ if (err.code === "commander.helpDisplayed" || err.code === "commander.version") {
3852
+ process.exit(0);
3853
+ }
3854
+ process.exit(err.exitCode);
3855
+ }
3856
+ throw err;
3857
+ }
3858
+ //# sourceMappingURL=cli.js.map