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