storybook 10.0.0-beta.4 → 10.0.0-beta.6

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 (107) hide show
  1. package/assets/server/openBrowser.applescript +94 -0
  2. package/dist/_browser-chunks/Color-KPLIACXP.js +1569 -0
  3. package/dist/_browser-chunks/{WithTooltip-ERFLZL6W.js → WithTooltip-SK46ZJ2J.js} +1 -1
  4. package/dist/_browser-chunks/{chunk-YY5GICNT.js → chunk-6E2SHJSL.js} +175 -32
  5. package/dist/_browser-chunks/{chunk-MZNYTCNT.js → chunk-AM4PZYVQ.js} +10 -63
  6. package/dist/_browser-chunks/{chunk-EOILZP2R.js → chunk-BOOOPFZF.js} +7 -2
  7. package/dist/_browser-chunks/{chunk-YWDKX534.js → chunk-FA42P6MO.js} +49 -4
  8. package/dist/_browser-chunks/chunk-G33S6YM3.js +521 -0
  9. package/dist/_browser-chunks/chunk-GJ67EE65.js +67 -0
  10. package/dist/_browser-chunks/{chunk-4QPX7WIQ.js → chunk-JJZMHC3A.js} +57 -166
  11. package/dist/_browser-chunks/{chunk-MD2FTHCZ.js → chunk-JVSKG4YS.js} +3 -16
  12. package/dist/_browser-chunks/{chunk-E7VLET3C.js → chunk-KSCAWCCE.js} +3947 -4291
  13. package/dist/_browser-chunks/chunk-QK3L5AXO.js +372 -0
  14. package/dist/_browser-chunks/chunk-VUAFL5XK.js +20 -0
  15. package/dist/_browser-chunks/{chunk-T7RCAJIX.js → chunk-Y3M7TW6K.js} +43 -47
  16. package/dist/_browser-chunks/{chunk-PYK5ZTFK.js → chunk-YQV3EGQ5.js} +5 -5
  17. package/dist/_browser-chunks/{syntaxhighlighter-YYAA4CS4.js → syntaxhighlighter-RJW7FE3A.js} +3 -2
  18. package/dist/_node-chunks/{builder-manager-IKHPPPFE.js → builder-manager-V33CQT2M.js} +26 -151
  19. package/dist/_node-chunks/camelcase-BZ55OCHI.js +18 -0
  20. package/dist/_node-chunks/{chunk-5OILJTZE.js → chunk-2DMFI367.js} +7 -7
  21. package/dist/_node-chunks/{chunk-DCHFG5TX.js → chunk-4TOI4VSK.js} +7 -7
  22. package/dist/_node-chunks/{chunk-XA4TAMUS.js → chunk-55VWKF63.js} +710 -935
  23. package/dist/_node-chunks/{chunk-N3GFXZDP.js → chunk-5IEY46LQ.js} +7 -7
  24. package/dist/_node-chunks/{chunk-YRPXGWKW.js → chunk-6PTV7XGR.js} +8 -8
  25. package/dist/_node-chunks/{chunk-4FMOVB65.js → chunk-7NJGTQ3W.js} +223 -243
  26. package/dist/_node-chunks/{chunk-4VGW2SQA.js → chunk-7WH7AGOR.js} +7 -7
  27. package/dist/_node-chunks/{camelcase-O2O7JODG.js → chunk-A7CUP23N.js} +9 -8
  28. package/dist/_node-chunks/{chunk-XT6O5CVI.js → chunk-B3AMFGAL.js} +30 -21
  29. package/dist/_node-chunks/{chunk-IB5AEYPX.js → chunk-BNOZ3EKF.js} +7 -7
  30. package/dist/_node-chunks/{chunk-TTQRDWDJ.js → chunk-DC7OWBHB.js} +12 -12
  31. package/dist/_node-chunks/{chunk-3J7DQ6TI.js → chunk-E6TLN2J2.js} +7 -7
  32. package/dist/_node-chunks/{chunk-JP4LEAXM.js → chunk-EAOPWIKA.js} +623 -750
  33. package/dist/_node-chunks/{chunk-YJHXEN7U.js → chunk-EY5PTUZL.js} +583 -180
  34. package/dist/_node-chunks/{chunk-JSSBBVU5.js → chunk-F3PO67U3.js} +7 -7
  35. package/dist/_node-chunks/chunk-FDDJHDCE.js +62 -0
  36. package/dist/_node-chunks/{chunk-6COBULLV.js → chunk-HEBHWRWL.js} +162 -103
  37. package/dist/_node-chunks/{chunk-USDZSU5L.js → chunk-HPFXREVG.js} +7 -7
  38. package/dist/_node-chunks/{chunk-JECCFKKM.js → chunk-IINJT47N.js} +7 -7
  39. package/dist/_node-chunks/{chunk-OL2HWCBH.js → chunk-JNHUDBJL.js} +7 -7
  40. package/dist/_node-chunks/{chunk-NF3GXIEK.js → chunk-JOXYGIZK.js} +9 -9
  41. package/dist/_node-chunks/{chunk-NOSGJ5PL.js → chunk-MLBTKECD.js} +7 -7
  42. package/dist/_node-chunks/{chunk-TYGVOW7L.js → chunk-NJXBURX7.js} +8 -8
  43. package/dist/_node-chunks/{chunk-AXFNB3AN.js → chunk-NKZ4UPPV.js} +7 -7
  44. package/dist/_node-chunks/{chunk-HAVE6SGK.js → chunk-NUVGSFQI.js} +7 -7
  45. package/dist/_node-chunks/chunk-R5DIBOM6.js +18 -0
  46. package/dist/_node-chunks/{chunk-AC3BNULF.js → chunk-RIPA4LFD.js} +22 -22
  47. package/dist/_node-chunks/{chunk-TBAIXCHN.js → chunk-TJIMCNYJ.js} +8 -8
  48. package/dist/_node-chunks/{chunk-SF2IETZ2.js → chunk-UYKQJMQY.js} +36 -23
  49. package/dist/_node-chunks/{chunk-7IIAUEWB.js → chunk-VQH4ZFTS.js} +8 -8
  50. package/dist/_node-chunks/{chunk-FWFQ2GU7.js → chunk-VSC6LSCQ.js} +6 -6
  51. package/dist/_node-chunks/{chunk-MOO2Y4GI.js → chunk-XZTBG2TG.js} +6 -6
  52. package/dist/_node-chunks/{dist-BMKSKYDI.js → dist-CGGAYWME.js} +9 -9
  53. package/dist/_node-chunks/{globby-DASPUXWI.js → globby-3IFB7BJC.js} +17 -13
  54. package/dist/_node-chunks/{lib-L6BIH4EV.js → lib-IT6OBSID.js} +36 -12
  55. package/dist/_node-chunks/{mdx-N42X6CFJ-2COTUDSL.js → mdx-N42X6CFJ-WM36SSZ6.js} +8 -8
  56. package/dist/_node-chunks/{p-limit-HVR3I7TJ.js → p-limit-3V5XIKA7.js} +7 -7
  57. package/dist/_node-chunks/{plugin-FZOHPRK7.js → plugin-3YREMMJJ.js} +10 -10
  58. package/dist/_node-chunks/{plugin-2XPSFYWZ.js → plugin-GJUBUKCT.js} +10 -10
  59. package/dist/_node-chunks/{webpack-inject-mocker-runtime-plugin-FGQM2EPC.js → webpack-inject-mocker-runtime-plugin-DCJQFJQ5.js} +1307 -847
  60. package/dist/_node-chunks/{webpack-mock-plugin-4HOAIYSX.js → webpack-mock-plugin-XJNFAHBI.js} +9 -9
  61. package/dist/babel/index.d.ts +1 -1
  62. package/dist/babel/index.js +11 -11
  63. package/dist/bin/core.js +638 -187
  64. package/dist/bin/dispatcher.js +11 -11
  65. package/dist/bin/loader.js +8 -8
  66. package/dist/cli/index.d.ts +61 -74
  67. package/dist/cli/index.js +56 -44
  68. package/dist/common/index.js +21 -21
  69. package/dist/components/index.js +27 -23
  70. package/dist/core-events/index.d.ts +18 -2
  71. package/dist/core-events/index.js +7 -1
  72. package/dist/core-server/index.js +4545 -4115
  73. package/dist/core-server/presets/common-manager.js +507 -747
  74. package/dist/core-server/presets/common-override-preset.js +9 -9
  75. package/dist/core-server/presets/common-preset.js +691 -29
  76. package/dist/core-server/presets/webpack/loaders/storybook-mock-transform-loader.js +9 -9
  77. package/dist/core-server/presets/webpack/loaders/webpack-automock-loader.js +10 -10
  78. package/dist/csf/index.js +6 -6
  79. package/dist/csf-tools/index.js +9 -9
  80. package/dist/docs-tools/index.js +4 -4
  81. package/dist/instrumenter/index.js +1 -1
  82. package/dist/manager/globals-runtime.js +9164 -18083
  83. package/dist/manager/globals.d.ts +0 -4
  84. package/dist/manager/globals.js +1 -6
  85. package/dist/manager/runtime.js +12967 -11396
  86. package/dist/manager-api/index.d.ts +2 -0
  87. package/dist/manager-api/index.js +303 -64
  88. package/dist/node-logger/index.d.ts +1 -1
  89. package/dist/node-logger/index.js +1136 -661
  90. package/dist/preview/runtime.js +12068 -21585
  91. package/dist/preview-api/index.d.ts +68 -67
  92. package/dist/preview-api/index.js +6 -6
  93. package/dist/router/index.js +2 -2
  94. package/dist/server-errors.js +10 -10
  95. package/dist/telemetry/index.d.ts +1 -1
  96. package/dist/telemetry/index.js +24 -24
  97. package/dist/test/index.js +1872 -4023
  98. package/dist/theming/index.d.ts +2 -2
  99. package/dist/theming/index.js +6 -6
  100. package/dist/types/index.d.ts +4 -0
  101. package/package.json +7 -6
  102. package/dist/_browser-chunks/Color-SFYJJKWL.js +0 -605
  103. package/dist/_browser-chunks/chunk-DHO2SA6L.js +0 -12
  104. package/dist/_browser-chunks/chunk-WPHPDNUA.js +0 -974
  105. package/dist/_node-chunks/chunk-CHJLO2LV.js +0 -62
  106. package/dist/_node-chunks/chunk-MNG223PY.js +0 -18
  107. package/dist/_node-chunks/default-browser-id-J4OIAAJ5.js +0 -1719
package/dist/bin/core.js CHANGED
@@ -1,32 +1,32 @@
1
- import CJS_COMPAT_NODE_URL_bdftjtsviyb from 'node:url';
2
- import CJS_COMPAT_NODE_PATH_bdftjtsviyb from 'node:path';
3
- import CJS_COMPAT_NODE_MODULE_bdftjtsviyb from "node:module";
1
+ import CJS_COMPAT_NODE_URL_0v1evul49qdo from 'node:url';
2
+ import CJS_COMPAT_NODE_PATH_0v1evul49qdo from 'node:path';
3
+ import CJS_COMPAT_NODE_MODULE_0v1evul49qdo from "node:module";
4
4
 
5
- var __filename = CJS_COMPAT_NODE_URL_bdftjtsviyb.fileURLToPath(import.meta.url);
6
- var __dirname = CJS_COMPAT_NODE_PATH_bdftjtsviyb.dirname(__filename);
7
- var require = CJS_COMPAT_NODE_MODULE_bdftjtsviyb.createRequire(import.meta.url);
5
+ var __filename = CJS_COMPAT_NODE_URL_0v1evul49qdo.fileURLToPath(import.meta.url);
6
+ var __dirname = CJS_COMPAT_NODE_PATH_0v1evul49qdo.dirname(__filename);
7
+ var require = CJS_COMPAT_NODE_MODULE_0v1evul49qdo.createRequire(import.meta.url);
8
8
 
9
9
  // ------------------------------------------------------------
10
10
  // end of CJS compatibility banner, injected by Storybook's esbuild configuration
11
11
  // ------------------------------------------------------------
12
12
  import {
13
13
  version
14
- } from "../_node-chunks/chunk-MNG223PY.js";
14
+ } from "../_node-chunks/chunk-R5DIBOM6.js";
15
15
  import {
16
16
  globalSettings
17
- } from "../_node-chunks/chunk-4FMOVB65.js";
17
+ } from "../_node-chunks/chunk-7NJGTQ3W.js";
18
18
  import {
19
19
  require_dist
20
- } from "../_node-chunks/chunk-NOSGJ5PL.js";
20
+ } from "../_node-chunks/chunk-MLBTKECD.js";
21
21
  import {
22
22
  require_picocolors
23
- } from "../_node-chunks/chunk-N3GFXZDP.js";
23
+ } from "../_node-chunks/chunk-5IEY46LQ.js";
24
24
  import {
25
25
  __commonJS,
26
26
  __name,
27
27
  __require,
28
28
  __toESM
29
- } from "../_node-chunks/chunk-MOO2Y4GI.js";
29
+ } from "../_node-chunks/chunk-XZTBG2TG.js";
30
30
 
31
31
  // ../node_modules/commander/lib/error.js
32
32
  var require_error = __commonJS({
@@ -106,7 +106,7 @@ var require_argument = __commonJS({
106
106
  this._name = name;
107
107
  break;
108
108
  }
109
- if (this._name.length > 3 && this._name.slice(-3) === "...") {
109
+ if (this._name.endsWith("...")) {
110
110
  this.variadic = true;
111
111
  this._name = this._name.slice(0, -3);
112
112
  }
@@ -122,11 +122,12 @@ var require_argument = __commonJS({
122
122
  /**
123
123
  * @package
124
124
  */
125
- _concatValue(value, previous) {
125
+ _collectValue(value, previous) {
126
126
  if (previous === this.defaultValue || !Array.isArray(previous)) {
127
127
  return [value];
128
128
  }
129
- return previous.concat(value);
129
+ previous.push(value);
130
+ return previous;
130
131
  }
131
132
  /**
132
133
  * Set the default value, and optionally supply the description to be displayed in the help.
@@ -165,7 +166,7 @@ var require_argument = __commonJS({
165
166
  );
166
167
  }
167
168
  if (this.variadic) {
168
- return this._concatValue(arg, previous);
169
+ return this._collectValue(arg, previous);
169
170
  }
170
171
  return arg;
171
172
  };
@@ -210,10 +211,22 @@ var require_help = __commonJS({
210
211
  }
211
212
  constructor() {
212
213
  this.helpWidth = void 0;
214
+ this.minWidthToWrap = 40;
213
215
  this.sortSubcommands = false;
214
216
  this.sortOptions = false;
215
217
  this.showGlobalOptions = false;
216
218
  }
219
+ /**
220
+ * prepareContext is called by Commander after applying overrides from `Command.configureHelp()`
221
+ * and just before calling `formatHelp()`.
222
+ *
223
+ * Commander just uses the helpWidth and the rest is provided for optional use by more complex subclasses.
224
+ *
225
+ * @param {{ error?: boolean, helpWidth?: number, outputHasColors?: boolean }} contextOptions
226
+ */
227
+ prepareContext(contextOptions) {
228
+ this.helpWidth = this.helpWidth ?? contextOptions.helpWidth ?? 80;
229
+ }
217
230
  /**
218
231
  * Get an array of the visible subcommands. Includes a placeholder for the implicit help command, if there is one.
219
232
  *
@@ -350,7 +363,12 @@ var require_help = __commonJS({
350
363
  */
351
364
  longestSubcommandTermLength(cmd, helper) {
352
365
  return helper.visibleCommands(cmd).reduce((max, command2) => {
353
- return Math.max(max, helper.subcommandTerm(command2).length);
366
+ return Math.max(
367
+ max,
368
+ this.displayWidth(
369
+ helper.styleSubcommandTerm(helper.subcommandTerm(command2))
370
+ )
371
+ );
354
372
  }, 0);
355
373
  }
356
374
  /**
@@ -362,7 +380,10 @@ var require_help = __commonJS({
362
380
  */
363
381
  longestOptionTermLength(cmd, helper) {
364
382
  return helper.visibleOptions(cmd).reduce((max, option) => {
365
- return Math.max(max, helper.optionTerm(option).length);
383
+ return Math.max(
384
+ max,
385
+ this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option)))
386
+ );
366
387
  }, 0);
367
388
  }
368
389
  /**
@@ -374,7 +395,10 @@ var require_help = __commonJS({
374
395
  */
375
396
  longestGlobalOptionTermLength(cmd, helper) {
376
397
  return helper.visibleGlobalOptions(cmd).reduce((max, option) => {
377
- return Math.max(max, helper.optionTerm(option).length);
398
+ return Math.max(
399
+ max,
400
+ this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option)))
401
+ );
378
402
  }, 0);
379
403
  }
380
404
  /**
@@ -386,7 +410,12 @@ var require_help = __commonJS({
386
410
  */
387
411
  longestArgumentTermLength(cmd, helper) {
388
412
  return helper.visibleArguments(cmd).reduce((max, argument) => {
389
- return Math.max(max, helper.argumentTerm(argument).length);
413
+ return Math.max(
414
+ max,
415
+ this.displayWidth(
416
+ helper.styleArgumentTerm(helper.argumentTerm(argument))
417
+ )
418
+ );
390
419
  }, 0);
391
420
  }
392
421
  /**
@@ -454,7 +483,11 @@ var require_help = __commonJS({
454
483
  extraInfo.push(`env: ${option.envVar}`);
455
484
  }
456
485
  if (extraInfo.length > 0) {
457
- return `${option.description} (${extraInfo.join(", ")})`;
486
+ const extraDescription = `(${extraInfo.join(", ")})`;
487
+ if (option.description) {
488
+ return `${option.description} ${extraDescription}`;
489
+ }
490
+ return extraDescription;
458
491
  }
459
492
  return option.description;
460
493
  }
@@ -478,14 +511,49 @@ var require_help = __commonJS({
478
511
  );
479
512
  }
480
513
  if (extraInfo.length > 0) {
481
- const extraDescripton = `(${extraInfo.join(", ")})`;
514
+ const extraDescription = `(${extraInfo.join(", ")})`;
482
515
  if (argument.description) {
483
- return `${argument.description} ${extraDescripton}`;
516
+ return `${argument.description} ${extraDescription}`;
484
517
  }
485
- return extraDescripton;
518
+ return extraDescription;
486
519
  }
487
520
  return argument.description;
488
521
  }
522
+ /**
523
+ * Format a list of items, given a heading and an array of formatted items.
524
+ *
525
+ * @param {string} heading
526
+ * @param {string[]} items
527
+ * @param {Help} helper
528
+ * @returns string[]
529
+ */
530
+ formatItemList(heading, items, helper) {
531
+ if (items.length === 0) return [];
532
+ return [helper.styleTitle(heading), ...items, ""];
533
+ }
534
+ /**
535
+ * Group items by their help group heading.
536
+ *
537
+ * @param {Command[] | Option[]} unsortedItems
538
+ * @param {Command[] | Option[]} visibleItems
539
+ * @param {Function} getGroup
540
+ * @returns {Map<string, Command[] | Option[]>}
541
+ */
542
+ groupItems(unsortedItems, visibleItems, getGroup) {
543
+ const result = /* @__PURE__ */ new Map();
544
+ unsortedItems.forEach((item) => {
545
+ const group = getGroup(item);
546
+ if (!result.has(group)) result.set(group, []);
547
+ });
548
+ visibleItems.forEach((item) => {
549
+ const group = getGroup(item);
550
+ if (!result.has(group)) {
551
+ result.set(group, []);
552
+ }
553
+ result.get(group).push(item);
554
+ });
555
+ return result;
556
+ }
489
557
  /**
490
558
  * Generate the built-in help text.
491
559
  *
@@ -495,77 +563,143 @@ var require_help = __commonJS({
495
563
  */
496
564
  formatHelp(cmd, helper) {
497
565
  const termWidth = helper.padWidth(cmd, helper);
498
- const helpWidth = helper.helpWidth || 80;
499
- const itemIndentWidth = 2;
500
- const itemSeparatorWidth = 2;
501
- function formatItem(term, description) {
502
- if (description) {
503
- const fullText = `${term.padEnd(termWidth + itemSeparatorWidth)}${description}`;
504
- return helper.wrap(
505
- fullText,
506
- helpWidth - itemIndentWidth,
507
- termWidth + itemSeparatorWidth
508
- );
509
- }
510
- return term;
511
- }
512
- __name(formatItem, "formatItem");
513
- function formatList(textArray) {
514
- return textArray.join("\n").replace(/^/gm, " ".repeat(itemIndentWidth));
515
- }
516
- __name(formatList, "formatList");
517
- let output = [`Usage: ${helper.commandUsage(cmd)}`, ""];
566
+ const helpWidth = helper.helpWidth ?? 80;
567
+ function callFormatItem(term, description) {
568
+ return helper.formatItem(term, termWidth, description, helper);
569
+ }
570
+ __name(callFormatItem, "callFormatItem");
571
+ let output = [
572
+ `${helper.styleTitle("Usage:")} ${helper.styleUsage(helper.commandUsage(cmd))}`,
573
+ ""
574
+ ];
518
575
  const commandDescription = helper.commandDescription(cmd);
519
576
  if (commandDescription.length > 0) {
520
577
  output = output.concat([
521
- helper.wrap(commandDescription, helpWidth, 0),
578
+ helper.boxWrap(
579
+ helper.styleCommandDescription(commandDescription),
580
+ helpWidth
581
+ ),
522
582
  ""
523
583
  ]);
524
584
  }
525
585
  const argumentList = helper.visibleArguments(cmd).map((argument) => {
526
- return formatItem(
527
- helper.argumentTerm(argument),
528
- helper.argumentDescription(argument)
586
+ return callFormatItem(
587
+ helper.styleArgumentTerm(helper.argumentTerm(argument)),
588
+ helper.styleArgumentDescription(helper.argumentDescription(argument))
529
589
  );
530
590
  });
531
- if (argumentList.length > 0) {
532
- output = output.concat(["Arguments:", formatList(argumentList), ""]);
533
- }
534
- const optionList = helper.visibleOptions(cmd).map((option) => {
535
- return formatItem(
536
- helper.optionTerm(option),
537
- helper.optionDescription(option)
538
- );
591
+ output = output.concat(
592
+ this.formatItemList("Arguments:", argumentList, helper)
593
+ );
594
+ const optionGroups = this.groupItems(
595
+ cmd.options,
596
+ helper.visibleOptions(cmd),
597
+ (option) => option.helpGroupHeading ?? "Options:"
598
+ );
599
+ optionGroups.forEach((options, group) => {
600
+ const optionList = options.map((option) => {
601
+ return callFormatItem(
602
+ helper.styleOptionTerm(helper.optionTerm(option)),
603
+ helper.styleOptionDescription(helper.optionDescription(option))
604
+ );
605
+ });
606
+ output = output.concat(this.formatItemList(group, optionList, helper));
539
607
  });
540
- if (optionList.length > 0) {
541
- output = output.concat(["Options:", formatList(optionList), ""]);
542
- }
543
- if (this.showGlobalOptions) {
608
+ if (helper.showGlobalOptions) {
544
609
  const globalOptionList = helper.visibleGlobalOptions(cmd).map((option) => {
545
- return formatItem(
546
- helper.optionTerm(option),
547
- helper.optionDescription(option)
610
+ return callFormatItem(
611
+ helper.styleOptionTerm(helper.optionTerm(option)),
612
+ helper.styleOptionDescription(helper.optionDescription(option))
548
613
  );
549
614
  });
550
- if (globalOptionList.length > 0) {
551
- output = output.concat([
552
- "Global Options:",
553
- formatList(globalOptionList),
554
- ""
555
- ]);
556
- }
557
- }
558
- const commandList = helper.visibleCommands(cmd).map((cmd2) => {
559
- return formatItem(
560
- helper.subcommandTerm(cmd2),
561
- helper.subcommandDescription(cmd2)
615
+ output = output.concat(
616
+ this.formatItemList("Global Options:", globalOptionList, helper)
562
617
  );
563
- });
564
- if (commandList.length > 0) {
565
- output = output.concat(["Commands:", formatList(commandList), ""]);
566
618
  }
619
+ const commandGroups = this.groupItems(
620
+ cmd.commands,
621
+ helper.visibleCommands(cmd),
622
+ (sub) => sub.helpGroup() || "Commands:"
623
+ );
624
+ commandGroups.forEach((commands, group) => {
625
+ const commandList = commands.map((sub) => {
626
+ return callFormatItem(
627
+ helper.styleSubcommandTerm(helper.subcommandTerm(sub)),
628
+ helper.styleSubcommandDescription(helper.subcommandDescription(sub))
629
+ );
630
+ });
631
+ output = output.concat(this.formatItemList(group, commandList, helper));
632
+ });
567
633
  return output.join("\n");
568
634
  }
635
+ /**
636
+ * Return display width of string, ignoring ANSI escape sequences. Used in padding and wrapping calculations.
637
+ *
638
+ * @param {string} str
639
+ * @returns {number}
640
+ */
641
+ displayWidth(str) {
642
+ return stripColor(str).length;
643
+ }
644
+ /**
645
+ * Style the title for displaying in the help. Called with 'Usage:', 'Options:', etc.
646
+ *
647
+ * @param {string} str
648
+ * @returns {string}
649
+ */
650
+ styleTitle(str) {
651
+ return str;
652
+ }
653
+ styleUsage(str) {
654
+ return str.split(" ").map((word) => {
655
+ if (word === "[options]") return this.styleOptionText(word);
656
+ if (word === "[command]") return this.styleSubcommandText(word);
657
+ if (word[0] === "[" || word[0] === "<")
658
+ return this.styleArgumentText(word);
659
+ return this.styleCommandText(word);
660
+ }).join(" ");
661
+ }
662
+ styleCommandDescription(str) {
663
+ return this.styleDescriptionText(str);
664
+ }
665
+ styleOptionDescription(str) {
666
+ return this.styleDescriptionText(str);
667
+ }
668
+ styleSubcommandDescription(str) {
669
+ return this.styleDescriptionText(str);
670
+ }
671
+ styleArgumentDescription(str) {
672
+ return this.styleDescriptionText(str);
673
+ }
674
+ styleDescriptionText(str) {
675
+ return str;
676
+ }
677
+ styleOptionTerm(str) {
678
+ return this.styleOptionText(str);
679
+ }
680
+ styleSubcommandTerm(str) {
681
+ return str.split(" ").map((word) => {
682
+ if (word === "[options]") return this.styleOptionText(word);
683
+ if (word[0] === "[" || word[0] === "<")
684
+ return this.styleArgumentText(word);
685
+ return this.styleSubcommandText(word);
686
+ }).join(" ");
687
+ }
688
+ styleArgumentTerm(str) {
689
+ return this.styleArgumentText(str);
690
+ }
691
+ styleOptionText(str) {
692
+ return str;
693
+ }
694
+ styleArgumentText(str) {
695
+ return str;
696
+ }
697
+ styleSubcommandText(str) {
698
+ return str;
699
+ }
700
+ styleCommandText(str) {
701
+ return str;
702
+ }
569
703
  /**
570
704
  * Calculate the pad width from the maximum term length.
571
705
  *
@@ -582,40 +716,95 @@ var require_help = __commonJS({
582
716
  );
583
717
  }
584
718
  /**
585
- * Wrap the given string to width characters per line, with lines after the first indented.
586
- * Do not wrap if insufficient room for wrapping (minColumnWidth), or string is manually formatted.
719
+ * Detect manually wrapped and indented strings by checking for line break followed by whitespace.
587
720
  *
588
721
  * @param {string} str
589
- * @param {number} width
590
- * @param {number} indent
591
- * @param {number} [minColumnWidth=40]
592
- * @return {string}
722
+ * @returns {boolean}
723
+ */
724
+ preformatted(str) {
725
+ return /\n[^\S\r\n]/.test(str);
726
+ }
727
+ /**
728
+ * Format the "item", which consists of a term and description. Pad the term and wrap the description, indenting the following lines.
729
+ *
730
+ * So "TTT", 5, "DDD DDDD DD DDD" might be formatted for this.helpWidth=17 like so:
731
+ * TTT DDD DDDD
732
+ * DD DDD
593
733
  *
734
+ * @param {string} term
735
+ * @param {number} termWidth
736
+ * @param {string} description
737
+ * @param {Help} helper
738
+ * @returns {string}
594
739
  */
595
- wrap(str, width, indent, minColumnWidth = 40) {
596
- const indents = " \\f\\t\\v\xA0\u1680\u2000-\u200A\u202F\u205F\u3000\uFEFF";
597
- const manualIndent = new RegExp(`[\\n][${indents}]+`);
598
- if (str.match(manualIndent)) return str;
599
- const columnWidth = width - indent;
600
- if (columnWidth < minColumnWidth) return str;
601
- const leadingStr = str.slice(0, indent);
602
- const columnText = str.slice(indent).replace("\r\n", "\n");
603
- const indentString = " ".repeat(indent);
604
- const zeroWidthSpace = "\u200B";
605
- const breaks = `\\s${zeroWidthSpace}`;
606
- const regex = new RegExp(
607
- `
608
- |.{1,${columnWidth - 1}}([${breaks}]|$)|[^${breaks}]+?([${breaks}]|$)`,
609
- "g"
740
+ formatItem(term, termWidth, description, helper) {
741
+ const itemIndent = 2;
742
+ const itemIndentStr = " ".repeat(itemIndent);
743
+ if (!description) return itemIndentStr + term;
744
+ const paddedTerm = term.padEnd(
745
+ termWidth + term.length - helper.displayWidth(term)
610
746
  );
611
- const lines = columnText.match(regex) || [];
612
- return leadingStr + lines.map((line, i) => {
613
- if (line === "\n") return "";
614
- return (i > 0 ? indentString : "") + line.trimEnd();
615
- }).join("\n");
747
+ const spacerWidth = 2;
748
+ const helpWidth = this.helpWidth ?? 80;
749
+ const remainingWidth = helpWidth - termWidth - spacerWidth - itemIndent;
750
+ let formattedDescription;
751
+ if (remainingWidth < this.minWidthToWrap || helper.preformatted(description)) {
752
+ formattedDescription = description;
753
+ } else {
754
+ const wrappedDescription = helper.boxWrap(description, remainingWidth);
755
+ formattedDescription = wrappedDescription.replace(
756
+ /\n/g,
757
+ "\n" + " ".repeat(termWidth + spacerWidth)
758
+ );
759
+ }
760
+ return itemIndentStr + paddedTerm + " ".repeat(spacerWidth) + formattedDescription.replace(/\n/g, `
761
+ ${itemIndentStr}`);
762
+ }
763
+ /**
764
+ * Wrap a string at whitespace, preserving existing line breaks.
765
+ * Wrapping is skipped if the width is less than `minWidthToWrap`.
766
+ *
767
+ * @param {string} str
768
+ * @param {number} width
769
+ * @returns {string}
770
+ */
771
+ boxWrap(str, width) {
772
+ if (width < this.minWidthToWrap) return str;
773
+ const rawLines = str.split(/\r\n|\n/);
774
+ const chunkPattern = /[\s]*[^\s]+/g;
775
+ const wrappedLines = [];
776
+ rawLines.forEach((line) => {
777
+ const chunks = line.match(chunkPattern);
778
+ if (chunks === null) {
779
+ wrappedLines.push("");
780
+ return;
781
+ }
782
+ let sumChunks = [chunks.shift()];
783
+ let sumWidth = this.displayWidth(sumChunks[0]);
784
+ chunks.forEach((chunk) => {
785
+ const visibleWidth = this.displayWidth(chunk);
786
+ if (sumWidth + visibleWidth <= width) {
787
+ sumChunks.push(chunk);
788
+ sumWidth += visibleWidth;
789
+ return;
790
+ }
791
+ wrappedLines.push(sumChunks.join(""));
792
+ const nextChunk = chunk.trimStart();
793
+ sumChunks = [nextChunk];
794
+ sumWidth = this.displayWidth(nextChunk);
795
+ });
796
+ wrappedLines.push(sumChunks.join(""));
797
+ });
798
+ return wrappedLines.join("\n");
616
799
  }
617
800
  };
801
+ function stripColor(str) {
802
+ const sgrPattern = /\x1b\[\d*(;\d*)*m/g;
803
+ return str.replace(sgrPattern, "");
804
+ }
805
+ __name(stripColor, "stripColor");
618
806
  exports.Help = Help2;
807
+ exports.stripColor = stripColor;
619
808
  }
620
809
  });
621
810
 
@@ -656,6 +845,7 @@ var require_option = __commonJS({
656
845
  this.argChoices = void 0;
657
846
  this.conflictsWith = [];
658
847
  this.implied = void 0;
848
+ this.helpGroupHeading = void 0;
659
849
  }
660
850
  /**
661
851
  * Set the default value, and optionally supply the description to be displayed in the help.
@@ -766,11 +956,12 @@ var require_option = __commonJS({
766
956
  /**
767
957
  * @package
768
958
  */
769
- _concatValue(value, previous) {
959
+ _collectValue(value, previous) {
770
960
  if (previous === this.defaultValue || !Array.isArray(previous)) {
771
961
  return [value];
772
962
  }
773
- return previous.concat(value);
963
+ previous.push(value);
964
+ return previous;
774
965
  }
775
966
  /**
776
967
  * Only allow option value to be one of choices.
@@ -787,7 +978,7 @@ var require_option = __commonJS({
787
978
  );
788
979
  }
789
980
  if (this.variadic) {
790
- return this._concatValue(arg, previous);
981
+ return this._collectValue(arg, previous);
791
982
  }
792
983
  return arg;
793
984
  };
@@ -806,12 +997,25 @@ var require_option = __commonJS({
806
997
  }
807
998
  /**
808
999
  * Return option name, in a camelcase format that can be used
809
- * as a object attribute key.
1000
+ * as an object attribute key.
810
1001
  *
811
1002
  * @return {string}
812
1003
  */
813
1004
  attributeName() {
814
- return camelcase(this.name().replace(/^no-/, ""));
1005
+ if (this.negate) {
1006
+ return camelcase(this.name().replace(/^no-/, ""));
1007
+ }
1008
+ return camelcase(this.name());
1009
+ }
1010
+ /**
1011
+ * Set the help group heading.
1012
+ *
1013
+ * @param {string} heading
1014
+ * @return {Option}
1015
+ */
1016
+ helpGroup(heading) {
1017
+ this.helpGroupHeading = heading;
1018
+ return this;
815
1019
  }
816
1020
  /**
817
1021
  * Check if `arg` matches the short or long flag.
@@ -883,14 +1087,40 @@ var require_option = __commonJS({
883
1087
  function splitOptionFlags(flags) {
884
1088
  let shortFlag;
885
1089
  let longFlag;
886
- const flagParts = flags.split(/[ |,]+/);
887
- if (flagParts.length > 1 && !/^[[<]/.test(flagParts[1]))
1090
+ const shortFlagExp = /^-[^-]$/;
1091
+ const longFlagExp = /^--[^-]/;
1092
+ const flagParts = flags.split(/[ |,]+/).concat("guard");
1093
+ if (shortFlagExp.test(flagParts[0])) shortFlag = flagParts.shift();
1094
+ if (longFlagExp.test(flagParts[0])) longFlag = flagParts.shift();
1095
+ if (!shortFlag && shortFlagExp.test(flagParts[0]))
888
1096
  shortFlag = flagParts.shift();
889
- longFlag = flagParts.shift();
890
- if (!shortFlag && /^-[^-]$/.test(longFlag)) {
1097
+ if (!shortFlag && longFlagExp.test(flagParts[0])) {
891
1098
  shortFlag = longFlag;
892
- longFlag = void 0;
1099
+ longFlag = flagParts.shift();
893
1100
  }
1101
+ if (flagParts[0].startsWith("-")) {
1102
+ const unsupportedFlag = flagParts[0];
1103
+ const baseError = `option creation failed due to '${unsupportedFlag}' in option flags '${flags}'`;
1104
+ if (/^-[^-][^-]/.test(unsupportedFlag))
1105
+ throw new Error(
1106
+ `${baseError}
1107
+ - a short flag is a single dash and a single character
1108
+ - either use a single dash and a single character (for a short flag)
1109
+ - or use a double dash for a long option (and can have two, like '--ws, --workspace')`
1110
+ );
1111
+ if (shortFlagExp.test(unsupportedFlag))
1112
+ throw new Error(`${baseError}
1113
+ - too many short flags`);
1114
+ if (longFlagExp.test(unsupportedFlag))
1115
+ throw new Error(`${baseError}
1116
+ - too many long flags`);
1117
+ throw new Error(`${baseError}
1118
+ - unrecognised flag format`);
1119
+ }
1120
+ if (shortFlag === void 0 && longFlag === void 0)
1121
+ throw new Error(
1122
+ `option creation failed due to no flags found in '${flags}'.`
1123
+ );
894
1124
  return { shortFlag, longFlag };
895
1125
  }
896
1126
  __name(splitOptionFlags, "splitOptionFlags");
@@ -991,7 +1221,7 @@ var require_command = __commonJS({
991
1221
  var process2 = __require("node:process");
992
1222
  var { Argument: Argument2, humanReadableArgName } = require_argument();
993
1223
  var { CommanderError: CommanderError2 } = require_error();
994
- var { Help: Help2 } = require_help();
1224
+ var { Help: Help2, stripColor } = require_help();
995
1225
  var { Option: Option2, DualOptions } = require_option();
996
1226
  var { suggestSimilar } = require_suggestSimilar();
997
1227
  var Command2 = class _Command extends EventEmitter {
@@ -1009,7 +1239,7 @@ var require_command = __commonJS({
1009
1239
  this.options = [];
1010
1240
  this.parent = null;
1011
1241
  this._allowUnknownOption = false;
1012
- this._allowExcessArguments = true;
1242
+ this._allowExcessArguments = false;
1013
1243
  this.registeredArguments = [];
1014
1244
  this._args = this.registeredArguments;
1015
1245
  this.args = [];
@@ -1036,18 +1266,25 @@ var require_command = __commonJS({
1036
1266
  this._lifeCycleHooks = {};
1037
1267
  this._showHelpAfterError = false;
1038
1268
  this._showSuggestionAfterError = true;
1269
+ this._savedState = null;
1039
1270
  this._outputConfiguration = {
1040
1271
  writeOut: /* @__PURE__ */ __name((str) => process2.stdout.write(str), "writeOut"),
1041
1272
  writeErr: /* @__PURE__ */ __name((str) => process2.stderr.write(str), "writeErr"),
1273
+ outputError: /* @__PURE__ */ __name((str, write) => write(str), "outputError"),
1042
1274
  getOutHelpWidth: /* @__PURE__ */ __name(() => process2.stdout.isTTY ? process2.stdout.columns : void 0, "getOutHelpWidth"),
1043
1275
  getErrHelpWidth: /* @__PURE__ */ __name(() => process2.stderr.isTTY ? process2.stderr.columns : void 0, "getErrHelpWidth"),
1044
- outputError: /* @__PURE__ */ __name((str, write) => write(str), "outputError")
1276
+ getOutHasColors: /* @__PURE__ */ __name(() => useColor() ?? (process2.stdout.isTTY && process2.stdout.hasColors?.()), "getOutHasColors"),
1277
+ getErrHasColors: /* @__PURE__ */ __name(() => useColor() ?? (process2.stderr.isTTY && process2.stderr.hasColors?.()), "getErrHasColors"),
1278
+ stripColor: /* @__PURE__ */ __name((str) => stripColor(str), "stripColor")
1045
1279
  };
1046
1280
  this._hidden = false;
1047
1281
  this._helpOption = void 0;
1048
1282
  this._addImplicitHelpCommand = void 0;
1049
1283
  this._helpCommand = void 0;
1050
1284
  this._helpConfiguration = {};
1285
+ this._helpGroupHeading = void 0;
1286
+ this._defaultCommandGroup = void 0;
1287
+ this._defaultOptionGroup = void 0;
1051
1288
  }
1052
1289
  /**
1053
1290
  * Copy settings that are useful to have in common across root command and subcommands.
@@ -1169,21 +1406,28 @@ var require_command = __commonJS({
1169
1406
  *
1170
1407
  * The configuration properties are all functions:
1171
1408
  *
1172
- * // functions to change where being written, stdout and stderr
1409
+ * // change how output being written, defaults to stdout and stderr
1173
1410
  * writeOut(str)
1174
1411
  * writeErr(str)
1175
- * // matching functions to specify width for wrapping help
1412
+ * // change how output being written for errors, defaults to writeErr
1413
+ * outputError(str, write) // used for displaying errors and not used for displaying help
1414
+ * // specify width for wrapping help
1176
1415
  * getOutHelpWidth()
1177
1416
  * getErrHelpWidth()
1178
- * // functions based on what is being written out
1179
- * outputError(str, write) // used for displaying errors, and not used for displaying help
1417
+ * // color support, currently only used with Help
1418
+ * getOutHasColors()
1419
+ * getErrHasColors()
1420
+ * stripColor() // used to remove ANSI escape codes if output does not have colors
1180
1421
  *
1181
1422
  * @param {object} [configuration] - configuration options
1182
1423
  * @return {(Command | object)} `this` command for chaining, or stored configuration
1183
1424
  */
1184
1425
  configureOutput(configuration) {
1185
1426
  if (configuration === void 0) return this._outputConfiguration;
1186
- Object.assign(this._outputConfiguration, configuration);
1427
+ this._outputConfiguration = {
1428
+ ...this._outputConfiguration,
1429
+ ...configuration
1430
+ };
1187
1431
  return this;
1188
1432
  }
1189
1433
  /**
@@ -1254,16 +1498,16 @@ var require_command = __commonJS({
1254
1498
  *
1255
1499
  * @param {string} name
1256
1500
  * @param {string} [description]
1257
- * @param {(Function|*)} [fn] - custom argument processing function
1501
+ * @param {(Function|*)} [parseArg] - custom argument processing function or default value
1258
1502
  * @param {*} [defaultValue]
1259
1503
  * @return {Command} `this` command for chaining
1260
1504
  */
1261
- argument(name, description, fn, defaultValue) {
1505
+ argument(name, description, parseArg, defaultValue) {
1262
1506
  const argument = this.createArgument(name, description);
1263
- if (typeof fn === "function") {
1264
- argument.default(defaultValue).argParser(fn);
1507
+ if (typeof parseArg === "function") {
1508
+ argument.default(defaultValue).argParser(parseArg);
1265
1509
  } else {
1266
- argument.default(fn);
1510
+ argument.default(parseArg);
1267
1511
  }
1268
1512
  this.addArgument(argument);
1269
1513
  return this;
@@ -1293,7 +1537,7 @@ var require_command = __commonJS({
1293
1537
  */
1294
1538
  addArgument(argument) {
1295
1539
  const previousArgument = this.registeredArguments.slice(-1)[0];
1296
- if (previousArgument && previousArgument.variadic) {
1540
+ if (previousArgument?.variadic) {
1297
1541
  throw new Error(
1298
1542
  `only the last argument can be variadic '${previousArgument.name()}'`
1299
1543
  );
@@ -1322,10 +1566,13 @@ var require_command = __commonJS({
1322
1566
  helpCommand(enableOrNameAndArgs, description) {
1323
1567
  if (typeof enableOrNameAndArgs === "boolean") {
1324
1568
  this._addImplicitHelpCommand = enableOrNameAndArgs;
1569
+ if (enableOrNameAndArgs && this._defaultCommandGroup) {
1570
+ this._initCommandGroup(this._getHelpCommand());
1571
+ }
1325
1572
  return this;
1326
1573
  }
1327
- enableOrNameAndArgs = enableOrNameAndArgs ?? "help [command]";
1328
- const [, helpName, helpArgs] = enableOrNameAndArgs.match(/([^ ]+) *(.*)/);
1574
+ const nameAndArgs = enableOrNameAndArgs ?? "help [command]";
1575
+ const [, helpName, helpArgs] = nameAndArgs.match(/([^ ]+) *(.*)/);
1329
1576
  const helpDescription = description ?? "display help for command";
1330
1577
  const helpCommand = this.createCommand(helpName);
1331
1578
  helpCommand.helpOption(false);
@@ -1333,6 +1580,7 @@ var require_command = __commonJS({
1333
1580
  if (helpDescription) helpCommand.description(helpDescription);
1334
1581
  this._addImplicitHelpCommand = true;
1335
1582
  this._helpCommand = helpCommand;
1583
+ if (enableOrNameAndArgs || description) this._initCommandGroup(helpCommand);
1336
1584
  return this;
1337
1585
  }
1338
1586
  /**
@@ -1349,6 +1597,7 @@ var require_command = __commonJS({
1349
1597
  }
1350
1598
  this._addImplicitHelpCommand = true;
1351
1599
  this._helpCommand = helpCommand;
1600
+ this._initCommandGroup(helpCommand);
1352
1601
  return this;
1353
1602
  }
1354
1603
  /**
@@ -1497,6 +1746,7 @@ Expecting one of '${allowedValues.join("', '")}'`);
1497
1746
  throw new Error(`Cannot add option '${option.flags}'${this._name && ` to command '${this._name}'`} due to conflicting flag '${matchingFlag}'
1498
1747
  - already used by option '${matchingOption.flags}'`);
1499
1748
  }
1749
+ this._initOptionGroup(option);
1500
1750
  this.options.push(option);
1501
1751
  }
1502
1752
  /**
@@ -1520,6 +1770,7 @@ Expecting one of '${allowedValues.join("', '")}'`);
1520
1770
  `cannot add command '${newCmd}' as already have command '${existingCmd}'`
1521
1771
  );
1522
1772
  }
1773
+ this._initCommandGroup(command2);
1523
1774
  this.commands.push(command2);
1524
1775
  }
1525
1776
  /**
@@ -1552,7 +1803,7 @@ Expecting one of '${allowedValues.join("', '")}'`);
1552
1803
  if (val !== null && option.parseArg) {
1553
1804
  val = this._callParseArg(option, val, oldValue, invalidValueMessage);
1554
1805
  } else if (val !== null && option.variadic) {
1555
- val = option._concatValue(val, oldValue);
1806
+ val = option._collectValue(val, oldValue);
1556
1807
  }
1557
1808
  if (val == null) {
1558
1809
  if (option.negate) {
@@ -1616,7 +1867,7 @@ Expecting one of '${allowedValues.join("', '")}'`);
1616
1867
  * @example
1617
1868
  * program
1618
1869
  * .option('-p, --pepper', 'add pepper')
1619
- * .option('-p, --pizza-type <TYPE>', 'type of pizza') // required option-argument
1870
+ * .option('--pt, --pizza-type <TYPE>', 'type of pizza') // required option-argument
1620
1871
  * .option('-c, --cheese [CHEESE]', 'add extra cheese', 'mozzarella') // optional option-argument with default
1621
1872
  * .option('-t, --tip <VALUE>', 'add tip to purchase cost', parseFloat) // custom parse function
1622
1873
  *
@@ -1883,6 +2134,7 @@ Expecting one of '${allowedValues.join("', '")}'`);
1883
2134
  * @return {Command} `this` command for chaining
1884
2135
  */
1885
2136
  parse(argv, parseOptions) {
2137
+ this._prepareForParse();
1886
2138
  const userArgs = this._prepareUserArgs(argv, parseOptions);
1887
2139
  this._parseCommand([], userArgs);
1888
2140
  return this;
@@ -1908,10 +2160,68 @@ Expecting one of '${allowedValues.join("', '")}'`);
1908
2160
  * @return {Promise}
1909
2161
  */
1910
2162
  async parseAsync(argv, parseOptions) {
2163
+ this._prepareForParse();
1911
2164
  const userArgs = this._prepareUserArgs(argv, parseOptions);
1912
2165
  await this._parseCommand([], userArgs);
1913
2166
  return this;
1914
2167
  }
2168
+ _prepareForParse() {
2169
+ if (this._savedState === null) {
2170
+ this.saveStateBeforeParse();
2171
+ } else {
2172
+ this.restoreStateBeforeParse();
2173
+ }
2174
+ }
2175
+ /**
2176
+ * Called the first time parse is called to save state and allow a restore before subsequent calls to parse.
2177
+ * Not usually called directly, but available for subclasses to save their custom state.
2178
+ *
2179
+ * This is called in a lazy way. Only commands used in parsing chain will have state saved.
2180
+ */
2181
+ saveStateBeforeParse() {
2182
+ this._savedState = {
2183
+ // name is stable if supplied by author, but may be unspecified for root command and deduced during parsing
2184
+ _name: this._name,
2185
+ // option values before parse have default values (including false for negated options)
2186
+ // shallow clones
2187
+ _optionValues: { ...this._optionValues },
2188
+ _optionValueSources: { ...this._optionValueSources }
2189
+ };
2190
+ }
2191
+ /**
2192
+ * Restore state before parse for calls after the first.
2193
+ * Not usually called directly, but available for subclasses to save their custom state.
2194
+ *
2195
+ * This is called in a lazy way. Only commands used in parsing chain will have state restored.
2196
+ */
2197
+ restoreStateBeforeParse() {
2198
+ if (this._storeOptionsAsProperties)
2199
+ throw new Error(`Can not call parse again when storeOptionsAsProperties is true.
2200
+ - either make a new Command for each call to parse, or stop storing options as properties`);
2201
+ this._name = this._savedState._name;
2202
+ this._scriptPath = null;
2203
+ this.rawArgs = [];
2204
+ this._optionValues = { ...this._savedState._optionValues };
2205
+ this._optionValueSources = { ...this._savedState._optionValueSources };
2206
+ this.args = [];
2207
+ this.processedArgs = [];
2208
+ }
2209
+ /**
2210
+ * Throw if expected executable is missing. Add lots of help for author.
2211
+ *
2212
+ * @param {string} executableFile
2213
+ * @param {string} executableDir
2214
+ * @param {string} subcommandName
2215
+ */
2216
+ _checkForMissingExecutable(executableFile, executableDir, subcommandName) {
2217
+ if (fs.existsSync(executableFile)) return;
2218
+ 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";
2219
+ const executableMissing = `'${executableFile}' does not exist
2220
+ - if '${subcommandName}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
2221
+ - if the default executable name is not suitable, use the executableFile option to supply a custom name or path
2222
+ - ${executableDirMessage}`;
2223
+ throw new Error(executableMissing);
2224
+ }
1915
2225
  /**
1916
2226
  * Execute a sub-command executable.
1917
2227
  *
@@ -1940,7 +2250,7 @@ Expecting one of '${allowedValues.join("', '")}'`);
1940
2250
  let resolvedScriptPath;
1941
2251
  try {
1942
2252
  resolvedScriptPath = fs.realpathSync(this._scriptPath);
1943
- } catch (err) {
2253
+ } catch {
1944
2254
  resolvedScriptPath = this._scriptPath;
1945
2255
  }
1946
2256
  executableDir = path.resolve(
@@ -1975,6 +2285,11 @@ Expecting one of '${allowedValues.join("', '")}'`);
1975
2285
  proc = childProcess.spawn(executableFile, args, { stdio: "inherit" });
1976
2286
  }
1977
2287
  } else {
2288
+ this._checkForMissingExecutable(
2289
+ executableFile,
2290
+ executableDir,
2291
+ subcommand._name
2292
+ );
1978
2293
  args.unshift(executableFile);
1979
2294
  args = incrementNodeInspectorPort(process2.execArgv).concat(args);
1980
2295
  proc = childProcess.spawn(process2.execPath, args, { stdio: "inherit" });
@@ -2006,12 +2321,11 @@ Expecting one of '${allowedValues.join("', '")}'`);
2006
2321
  });
2007
2322
  proc.on("error", (err) => {
2008
2323
  if (err.code === "ENOENT") {
2009
- 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";
2010
- const executableMissing = `'${executableFile}' does not exist
2011
- - if '${subcommand._name}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
2012
- - if the default executable name is not suitable, use the executableFile option to supply a custom name or path
2013
- - ${executableDirMessage}`;
2014
- throw new Error(executableMissing);
2324
+ this._checkForMissingExecutable(
2325
+ executableFile,
2326
+ executableDir,
2327
+ subcommand._name
2328
+ );
2015
2329
  } else if (err.code === "EACCES") {
2016
2330
  throw new Error(`'${executableFile}' not executable`);
2017
2331
  }
@@ -2035,6 +2349,7 @@ Expecting one of '${allowedValues.join("', '")}'`);
2035
2349
  _dispatchSubcommand(commandName, operands, unknown) {
2036
2350
  const subCommand = this._findCommand(commandName);
2037
2351
  if (!subCommand) this.help({ error: true });
2352
+ subCommand._prepareForParse();
2038
2353
  let promiseChain;
2039
2354
  promiseChain = this._chainOrCallSubCommandHook(
2040
2355
  promiseChain,
@@ -2141,7 +2456,7 @@ Expecting one of '${allowedValues.join("', '")}'`);
2141
2456
  * @private
2142
2457
  */
2143
2458
  _chainOrCall(promise, fn) {
2144
- if (promise && promise.then && typeof promise.then === "function") {
2459
+ if (promise?.then && typeof promise.then === "function") {
2145
2460
  return promise.then(() => fn());
2146
2461
  }
2147
2462
  return fn();
@@ -2246,7 +2561,7 @@ Expecting one of '${allowedValues.join("', '")}'`);
2246
2561
  promiseChain = this._chainOrCallHooks(promiseChain, "postAction");
2247
2562
  return promiseChain;
2248
2563
  }
2249
- if (this.parent && this.parent.listenerCount(commandEvent)) {
2564
+ if (this.parent?.listenerCount(commandEvent)) {
2250
2565
  checkForUnknownOptions();
2251
2566
  this._processArguments();
2252
2567
  this.parent.emit(commandEvent, operands, unknown);
@@ -2347,6 +2662,8 @@ Expecting one of '${allowedValues.join("', '")}'`);
2347
2662
  * Parse options from `argv` removing known options,
2348
2663
  * and return argv split into operands and unknown arguments.
2349
2664
  *
2665
+ * Side effects: modifies command by storing options. Does not reset state if called again.
2666
+ *
2350
2667
  * Examples:
2351
2668
  *
2352
2669
  * argv => operands, unknown
@@ -2355,27 +2672,35 @@ Expecting one of '${allowedValues.join("', '")}'`);
2355
2672
  * sub --unknown uuu op => [sub], [--unknown uuu op]
2356
2673
  * sub -- --unknown uuu op => [sub --unknown uuu op], []
2357
2674
  *
2358
- * @param {string[]} argv
2675
+ * @param {string[]} args
2359
2676
  * @return {{operands: string[], unknown: string[]}}
2360
2677
  */
2361
- parseOptions(argv) {
2678
+ parseOptions(args) {
2362
2679
  const operands = [];
2363
2680
  const unknown = [];
2364
2681
  let dest = operands;
2365
- const args = argv.slice();
2366
2682
  function maybeOption(arg) {
2367
2683
  return arg.length > 1 && arg[0] === "-";
2368
2684
  }
2369
2685
  __name(maybeOption, "maybeOption");
2686
+ const negativeNumberArg = /* @__PURE__ */ __name((arg) => {
2687
+ if (!/^-\d*\.?\d+(e[+-]?\d+)?$/.test(arg)) return false;
2688
+ return !this._getCommandAndAncestors().some(
2689
+ (cmd) => cmd.options.map((opt) => opt.short).some((short) => /^-\d$/.test(short))
2690
+ );
2691
+ }, "negativeNumberArg");
2370
2692
  let activeVariadicOption = null;
2371
- while (args.length) {
2372
- const arg = args.shift();
2693
+ let activeGroup = null;
2694
+ let i = 0;
2695
+ while (i < args.length || activeGroup) {
2696
+ const arg = activeGroup ?? args[i++];
2697
+ activeGroup = null;
2373
2698
  if (arg === "--") {
2374
2699
  if (dest === unknown) dest.push(arg);
2375
- dest.push(...args);
2700
+ dest.push(...args.slice(i));
2376
2701
  break;
2377
2702
  }
2378
- if (activeVariadicOption && !maybeOption(arg)) {
2703
+ if (activeVariadicOption && (!maybeOption(arg) || negativeNumberArg(arg))) {
2379
2704
  this.emit(`option:${activeVariadicOption.name()}`, arg);
2380
2705
  continue;
2381
2706
  }
@@ -2384,13 +2709,13 @@ Expecting one of '${allowedValues.join("', '")}'`);
2384
2709
  const option = this._findOption(arg);
2385
2710
  if (option) {
2386
2711
  if (option.required) {
2387
- const value = args.shift();
2712
+ const value = args[i++];
2388
2713
  if (value === void 0) this.optionMissingArgument(option);
2389
2714
  this.emit(`option:${option.name()}`, value);
2390
2715
  } else if (option.optional) {
2391
2716
  let value = null;
2392
- if (args.length > 0 && !maybeOption(args[0])) {
2393
- value = args.shift();
2717
+ if (i < args.length && (!maybeOption(args[i]) || negativeNumberArg(args[i]))) {
2718
+ value = args[i++];
2394
2719
  }
2395
2720
  this.emit(`option:${option.name()}`, value);
2396
2721
  } else {
@@ -2407,7 +2732,7 @@ Expecting one of '${allowedValues.join("', '")}'`);
2407
2732
  this.emit(`option:${option.name()}`, arg.slice(2));
2408
2733
  } else {
2409
2734
  this.emit(`option:${option.name()}`);
2410
- args.unshift(`-${arg.slice(2)}`);
2735
+ activeGroup = `-${arg.slice(2)}`;
2411
2736
  }
2412
2737
  continue;
2413
2738
  }
@@ -2420,27 +2745,24 @@ Expecting one of '${allowedValues.join("', '")}'`);
2420
2745
  continue;
2421
2746
  }
2422
2747
  }
2423
- if (maybeOption(arg)) {
2748
+ if (dest === operands && maybeOption(arg) && !(this.commands.length === 0 && negativeNumberArg(arg))) {
2424
2749
  dest = unknown;
2425
2750
  }
2426
2751
  if ((this._enablePositionalOptions || this._passThroughOptions) && operands.length === 0 && unknown.length === 0) {
2427
2752
  if (this._findCommand(arg)) {
2428
2753
  operands.push(arg);
2429
- if (args.length > 0) unknown.push(...args);
2754
+ unknown.push(...args.slice(i));
2430
2755
  break;
2431
2756
  } else if (this._getHelpCommand() && arg === this._getHelpCommand().name()) {
2432
- operands.push(arg);
2433
- if (args.length > 0) operands.push(...args);
2757
+ operands.push(arg, ...args.slice(i));
2434
2758
  break;
2435
2759
  } else if (this._defaultCommandName) {
2436
- unknown.push(arg);
2437
- if (args.length > 0) unknown.push(...args);
2760
+ unknown.push(arg, ...args.slice(i));
2438
2761
  break;
2439
2762
  }
2440
2763
  }
2441
2764
  if (this._passThroughOptions) {
2442
- dest.push(arg);
2443
- if (args.length > 0) dest.push(...args);
2765
+ dest.push(arg, ...args.slice(i));
2444
2766
  break;
2445
2767
  }
2446
2768
  dest.push(arg);
@@ -2792,6 +3114,69 @@ Expecting one of '${allowedValues.join("', '")}'`);
2792
3114
  this._name = str;
2793
3115
  return this;
2794
3116
  }
3117
+ /**
3118
+ * Set/get the help group heading for this subcommand in parent command's help.
3119
+ *
3120
+ * @param {string} [heading]
3121
+ * @return {Command | string}
3122
+ */
3123
+ helpGroup(heading) {
3124
+ if (heading === void 0) return this._helpGroupHeading ?? "";
3125
+ this._helpGroupHeading = heading;
3126
+ return this;
3127
+ }
3128
+ /**
3129
+ * Set/get the default help group heading for subcommands added to this command.
3130
+ * (This does not override a group set directly on the subcommand using .helpGroup().)
3131
+ *
3132
+ * @example
3133
+ * program.commandsGroup('Development Commands:);
3134
+ * program.command('watch')...
3135
+ * program.command('lint')...
3136
+ * ...
3137
+ *
3138
+ * @param {string} [heading]
3139
+ * @returns {Command | string}
3140
+ */
3141
+ commandsGroup(heading) {
3142
+ if (heading === void 0) return this._defaultCommandGroup ?? "";
3143
+ this._defaultCommandGroup = heading;
3144
+ return this;
3145
+ }
3146
+ /**
3147
+ * Set/get the default help group heading for options added to this command.
3148
+ * (This does not override a group set directly on the option using .helpGroup().)
3149
+ *
3150
+ * @example
3151
+ * program
3152
+ * .optionsGroup('Development Options:')
3153
+ * .option('-d, --debug', 'output extra debugging')
3154
+ * .option('-p, --profile', 'output profiling information')
3155
+ *
3156
+ * @param {string} [heading]
3157
+ * @returns {Command | string}
3158
+ */
3159
+ optionsGroup(heading) {
3160
+ if (heading === void 0) return this._defaultOptionGroup ?? "";
3161
+ this._defaultOptionGroup = heading;
3162
+ return this;
3163
+ }
3164
+ /**
3165
+ * @param {Option} option
3166
+ * @private
3167
+ */
3168
+ _initOptionGroup(option) {
3169
+ if (this._defaultOptionGroup && !option.helpGroupHeading)
3170
+ option.helpGroup(this._defaultOptionGroup);
3171
+ }
3172
+ /**
3173
+ * @param {Command} cmd
3174
+ * @private
3175
+ */
3176
+ _initCommandGroup(cmd) {
3177
+ if (this._defaultCommandGroup && !cmd.helpGroup())
3178
+ cmd.helpGroup(this._defaultCommandGroup);
3179
+ }
2795
3180
  /**
2796
3181
  * Set the name of the command from script filename, such as process.argv[1],
2797
3182
  * or require.main.filename, or __filename.
@@ -2832,26 +3217,47 @@ Expecting one of '${allowedValues.join("', '")}'`);
2832
3217
  */
2833
3218
  helpInformation(contextOptions) {
2834
3219
  const helper = this.createHelp();
2835
- if (helper.helpWidth === void 0) {
2836
- helper.helpWidth = contextOptions && contextOptions.error ? this._outputConfiguration.getErrHelpWidth() : this._outputConfiguration.getOutHelpWidth();
2837
- }
2838
- return helper.formatHelp(this, helper);
3220
+ const context = this._getOutputContext(contextOptions);
3221
+ helper.prepareContext({
3222
+ error: context.error,
3223
+ helpWidth: context.helpWidth,
3224
+ outputHasColors: context.hasColors
3225
+ });
3226
+ const text = helper.formatHelp(this, helper);
3227
+ if (context.hasColors) return text;
3228
+ return this._outputConfiguration.stripColor(text);
2839
3229
  }
2840
3230
  /**
3231
+ * @typedef HelpContext
3232
+ * @type {object}
3233
+ * @property {boolean} error
3234
+ * @property {number} helpWidth
3235
+ * @property {boolean} hasColors
3236
+ * @property {function} write - includes stripColor if needed
3237
+ *
3238
+ * @returns {HelpContext}
2841
3239
  * @private
2842
3240
  */
2843
- _getHelpContext(contextOptions) {
3241
+ _getOutputContext(contextOptions) {
2844
3242
  contextOptions = contextOptions || {};
2845
- const context = { error: !!contextOptions.error };
2846
- let write;
2847
- if (context.error) {
2848
- write = /* @__PURE__ */ __name((arg) => this._outputConfiguration.writeErr(arg), "write");
3243
+ const error = !!contextOptions.error;
3244
+ let baseWrite;
3245
+ let hasColors;
3246
+ let helpWidth;
3247
+ if (error) {
3248
+ baseWrite = /* @__PURE__ */ __name((str) => this._outputConfiguration.writeErr(str), "baseWrite");
3249
+ hasColors = this._outputConfiguration.getErrHasColors();
3250
+ helpWidth = this._outputConfiguration.getErrHelpWidth();
2849
3251
  } else {
2850
- write = /* @__PURE__ */ __name((arg) => this._outputConfiguration.writeOut(arg), "write");
3252
+ baseWrite = /* @__PURE__ */ __name((str) => this._outputConfiguration.writeOut(str), "baseWrite");
3253
+ hasColors = this._outputConfiguration.getOutHasColors();
3254
+ helpWidth = this._outputConfiguration.getOutHelpWidth();
2851
3255
  }
2852
- context.write = contextOptions.write || write;
2853
- context.command = this;
2854
- return context;
3256
+ const write = /* @__PURE__ */ __name((str) => {
3257
+ if (!hasColors) str = this._outputConfiguration.stripColor(str);
3258
+ return baseWrite(str);
3259
+ }, "write");
3260
+ return { error, write, hasColors, helpWidth };
2855
3261
  }
2856
3262
  /**
2857
3263
  * Output help information for this command.
@@ -2866,23 +3272,28 @@ Expecting one of '${allowedValues.join("', '")}'`);
2866
3272
  deprecatedCallback = contextOptions;
2867
3273
  contextOptions = void 0;
2868
3274
  }
2869
- const context = this._getHelpContext(contextOptions);
2870
- this._getCommandAndAncestors().reverse().forEach((command2) => command2.emit("beforeAllHelp", context));
2871
- this.emit("beforeHelp", context);
2872
- let helpInformation = this.helpInformation(context);
3275
+ const outputContext = this._getOutputContext(contextOptions);
3276
+ const eventContext = {
3277
+ error: outputContext.error,
3278
+ write: outputContext.write,
3279
+ command: this
3280
+ };
3281
+ this._getCommandAndAncestors().reverse().forEach((command2) => command2.emit("beforeAllHelp", eventContext));
3282
+ this.emit("beforeHelp", eventContext);
3283
+ let helpInformation = this.helpInformation({ error: outputContext.error });
2873
3284
  if (deprecatedCallback) {
2874
3285
  helpInformation = deprecatedCallback(helpInformation);
2875
3286
  if (typeof helpInformation !== "string" && !Buffer.isBuffer(helpInformation)) {
2876
3287
  throw new Error("outputHelp callback must return a string or a Buffer");
2877
3288
  }
2878
3289
  }
2879
- context.write(helpInformation);
3290
+ outputContext.write(helpInformation);
2880
3291
  if (this._getHelpOption()?.long) {
2881
3292
  this.emit(this._getHelpOption().long);
2882
3293
  }
2883
- this.emit("afterHelp", context);
3294
+ this.emit("afterHelp", eventContext);
2884
3295
  this._getCommandAndAncestors().forEach(
2885
- (command2) => command2.emit("afterAllHelp", context)
3296
+ (command2) => command2.emit("afterAllHelp", eventContext)
2886
3297
  );
2887
3298
  }
2888
3299
  /**
@@ -2900,15 +3311,20 @@ Expecting one of '${allowedValues.join("', '")}'`);
2900
3311
  helpOption(flags, description) {
2901
3312
  if (typeof flags === "boolean") {
2902
3313
  if (flags) {
2903
- this._helpOption = this._helpOption ?? void 0;
3314
+ if (this._helpOption === null) this._helpOption = void 0;
3315
+ if (this._defaultOptionGroup) {
3316
+ this._initOptionGroup(this._getHelpOption());
3317
+ }
2904
3318
  } else {
2905
3319
  this._helpOption = null;
2906
3320
  }
2907
3321
  return this;
2908
3322
  }
2909
- flags = flags ?? "-h, --help";
2910
- description = description ?? "display help for command";
2911
- this._helpOption = this.createOption(flags, description);
3323
+ this._helpOption = this.createOption(
3324
+ flags ?? "-h, --help",
3325
+ description ?? "display help for command"
3326
+ );
3327
+ if (flags || description) this._initOptionGroup(this._helpOption);
2912
3328
  return this;
2913
3329
  }
2914
3330
  /**
@@ -2933,6 +3349,7 @@ Expecting one of '${allowedValues.join("', '")}'`);
2933
3349
  */
2934
3350
  addHelpOption(option) {
2935
3351
  this._helpOption = option;
3352
+ this._initOptionGroup(option);
2936
3353
  return this;
2937
3354
  }
2938
3355
  /**
@@ -2944,12 +3361,20 @@ Expecting one of '${allowedValues.join("', '")}'`);
2944
3361
  */
2945
3362
  help(contextOptions) {
2946
3363
  this.outputHelp(contextOptions);
2947
- let exitCode = process2.exitCode || 0;
3364
+ let exitCode = Number(process2.exitCode ?? 0);
2948
3365
  if (exitCode === 0 && contextOptions && typeof contextOptions !== "function" && contextOptions.error) {
2949
3366
  exitCode = 1;
2950
3367
  }
2951
3368
  this._exit(exitCode, "commander.help", "(outputHelp)");
2952
3369
  }
3370
+ /**
3371
+ * // Do a little typing to coordinate emit and listener for the help text events.
3372
+ * @typedef HelpTextEventContext
3373
+ * @type {object}
3374
+ * @property {boolean} error
3375
+ * @property {Command} command
3376
+ * @property {function} write
3377
+ */
2953
3378
  /**
2954
3379
  * Add additional text to be displayed with the built-in help.
2955
3380
  *
@@ -3026,7 +3451,16 @@ Expecting one of '${allowedValues.join("', '")}'`);
3026
3451
  });
3027
3452
  }
3028
3453
  __name(incrementNodeInspectorPort, "incrementNodeInspectorPort");
3454
+ function useColor() {
3455
+ if (process2.env.NO_COLOR || process2.env.FORCE_COLOR === "0" || process2.env.FORCE_COLOR === "false")
3456
+ return false;
3457
+ if (process2.env.FORCE_COLOR || process2.env.CLICOLOR_FORCE !== void 0)
3458
+ return true;
3459
+ return void 0;
3460
+ }
3461
+ __name(useColor, "useColor");
3029
3462
  exports.Command = Command2;
3463
+ exports.useColor = useColor;
3030
3464
  }
3031
3465
  });
3032
3466
 
@@ -3077,10 +3511,11 @@ var {
3077
3511
  // ../node_modules/leven/index.js
3078
3512
  var array = [];
3079
3513
  var characterCodeCache = [];
3080
- function leven(first, second) {
3514
+ function leven(first, second, options) {
3081
3515
  if (first === second) {
3082
3516
  return 0;
3083
3517
  }
3518
+ const maxDistance = options?.maxDistance;
3084
3519
  const swap = first;
3085
3520
  if (first.length > second.length) {
3086
3521
  first = second;
@@ -3098,8 +3533,11 @@ function leven(first, second) {
3098
3533
  }
3099
3534
  firstLength -= start;
3100
3535
  secondLength -= start;
3536
+ if (maxDistance !== void 0 && secondLength - firstLength > maxDistance) {
3537
+ return maxDistance;
3538
+ }
3101
3539
  if (firstLength === 0) {
3102
- return secondLength;
3540
+ return maxDistance !== void 0 && secondLength > maxDistance ? maxDistance : secondLength;
3103
3541
  }
3104
3542
  let bCharacterCode;
3105
3543
  let result;
@@ -3120,8 +3558,21 @@ function leven(first, second) {
3120
3558
  temporary = array[index];
3121
3559
  result = array[index] = temporary > result ? temporary2 > result ? result + 1 : temporary2 : temporary2 > temporary ? temporary + 1 : temporary2;
3122
3560
  }
3561
+ if (maxDistance !== void 0) {
3562
+ let rowMinimum = result;
3563
+ for (index = 0; index < firstLength; index++) {
3564
+ if (array[index] < rowMinimum) {
3565
+ rowMinimum = array[index];
3566
+ }
3567
+ }
3568
+ if (rowMinimum > maxDistance) {
3569
+ return maxDistance;
3570
+ }
3571
+ }
3123
3572
  }
3124
- return result;
3573
+ array.length = firstLength;
3574
+ characterCodeCache.length = firstLength;
3575
+ return maxDistance !== void 0 && result > maxDistance ? maxDistance : result;
3125
3576
  }
3126
3577
  __name(leven, "leven");
3127
3578