@bemoje/cli 4.0.1 → 5.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.cjs CHANGED
@@ -31,9 +31,7 @@ function parseOptionFlags(flags) {
31
31
  }
32
32
  const long = match[2];
33
33
  const argName = (match[4] || match[5])?.replace(/\.{3}$/, "") || void 0;
34
- const name = long.split("-").reduce((str, word) => {
35
- return str + word[0].toUpperCase() + word.slice(1);
36
- });
34
+ const name = long.split("-").reduce((str, word) => str + word[0].toUpperCase() + word.slice(1));
37
35
  return {
38
36
  short,
39
37
  long,
@@ -62,13 +60,7 @@ __name(getCommandAncestors, "getCommandAncestors");
62
60
 
63
61
  // src/lib/helpers/findOption.ts
64
62
  function findOption(cmd, nameOrShortOrLong) {
65
- return nameOrShortOrLong.startsWith("--") ? cmd.options.find((o) => {
66
- return o.long === nameOrShortOrLong.slice(2);
67
- }) : nameOrShortOrLong.startsWith("-") ? cmd.options.find((o) => {
68
- return o.short === nameOrShortOrLong.slice(1);
69
- }) : cmd.options.find((o) => {
70
- return o.name === nameOrShortOrLong;
71
- });
63
+ return nameOrShortOrLong.startsWith("--") ? cmd.options.find((o) => o.long === nameOrShortOrLong.slice(2)) : nameOrShortOrLong.startsWith("-") ? cmd.options.find((o) => o.short === nameOrShortOrLong.slice(1)) : cmd.options.find((o) => o.name === nameOrShortOrLong);
72
64
  }
73
65
  __name(findOption, "findOption");
74
66
 
@@ -102,9 +94,7 @@ function objSortKeys(o, compare) {
102
94
  if (compare) {
103
95
  entries.sort(compare);
104
96
  } else {
105
- entries.sort((a, b) => {
106
- return a[0].localeCompare(b[0]);
107
- });
97
+ entries.sort((a, b) => a[0].localeCompare(b[0]));
108
98
  }
109
99
  return Object.fromEntries(entries);
110
100
  }
@@ -277,9 +267,7 @@ function memoizeSync(arg = {}) {
277
267
  } else {
278
268
  const wmap = /* @__PURE__ */ new WeakMap();
279
269
  descriptor.value = function(...args) {
280
- const memoized = mapGetOrDefault(wmap, this, () => {
281
- return memoizee__default.default(orig, options);
282
- });
270
+ const memoized = mapGetOrDefault(wmap, this, () => memoizee__default.default(orig, options));
283
271
  return memoized.apply(this, args);
284
272
  };
285
273
  }
@@ -302,9 +290,7 @@ function createLazyPropDecorator(map) {
302
290
  const { get, value } = descriptor;
303
291
  if (predicate.isFunction(get)) {
304
292
  descriptor.get = function() {
305
- return mapGetOrDefault(map, this, () => {
306
- return get.call(this);
307
- });
293
+ return mapGetOrDefault(map, this, () => get.call(this));
308
294
  };
309
295
  return descriptor;
310
296
  }
@@ -350,13 +336,9 @@ var Help = class {
350
336
  * Get an array of the visible subcommands. Includes a placeholder for the implicit help command, if there is one.
351
337
  */
352
338
  visibleCommands() {
353
- const res = Object.values(this.cmd.commands).filter((c) => {
354
- return !c.hidden;
355
- });
339
+ const res = Object.values(this.cmd.commands).filter((c) => !c.hidden);
356
340
  if (this.sortSubcommands) {
357
- res.sort((a, b) => {
358
- return a.name.localeCompare(b.name);
359
- });
341
+ res.sort((a, b) => a.name.localeCompare(b.name));
360
342
  }
361
343
  return res;
362
344
  }
@@ -364,18 +346,17 @@ var Help = class {
364
346
  * Compare options for sort.
365
347
  */
366
348
  compareOptions(a, b) {
367
- const getSortKey = /* @__PURE__ */ __name((option) => {
368
- return option.short ? option.short.replace(/^-/, "") : option.long.replace(/^--/, "");
369
- }, "getSortKey");
349
+ const getSortKey = /* @__PURE__ */ __name((option) => (
350
+ // WYSIWYG for order displayed in help. Short used for comparison if present. No special handling for negated.
351
+ option.short ? option.short.replace(/^-/, "") : option.long.replace(/^--/, "")
352
+ ), "getSortKey");
370
353
  return getSortKey(a).localeCompare(getSortKey(b));
371
354
  }
372
355
  /**
373
356
  * Get an array of the visible options. Includes a placeholder for the implicit help option, if there is one.
374
357
  */
375
358
  visibleOptions() {
376
- const res = this.cmd.options.filter((option) => {
377
- return !option.hidden;
378
- });
359
+ const res = this.cmd.options.filter((option) => !option.hidden);
379
360
  if (this.sortOptions) {
380
361
  res.sort(this.compareOptions);
381
362
  }
@@ -391,9 +372,7 @@ var Help = class {
391
372
  * Get the command term to show in the list of subcommands.
392
373
  */
393
374
  subcommandTerm(sub) {
394
- const args = sub.arguments.map((arg) => {
395
- return arg.usage;
396
- }).join(" ");
375
+ const args = sub.arguments.map((arg) => arg.usage).join(" ");
397
376
  return (sub.aliases[0] ? `${sub.aliases[0].padEnd(this.longestSubcommandAliasLength(), " ")} | ` : "") + sub.name + (sub.options.length ? ` ${this.usageDisplayOptionsAs}` : "") + // simplistic check for non-help option
398
377
  (args ? ` ${args}` : "");
399
378
  }
@@ -413,33 +392,25 @@ var Help = class {
413
392
  * Get the longest subcommand primary alias length.
414
393
  */
415
394
  longestSubcommandAliasLength() {
416
- return Math.max(0, ...this.visibleCommands().map((c) => {
417
- return c.aliases[0]?.length || 0;
418
- }));
395
+ return Math.max(0, ...this.visibleCommands().map((c) => c.aliases[0]?.length || 0));
419
396
  }
420
397
  /**
421
398
  * Get the longest subcommand term length.
422
399
  */
423
400
  longestSubcommandTermLength() {
424
- return this.visibleCommands().reduce((max, command) => {
425
- return Math.max(max, this.displayWidth(this.styleSubcommandTerm(this.subcommandTerm(command))));
426
- }, 0);
401
+ return this.visibleCommands().reduce((max, command) => Math.max(max, this.displayWidth(this.styleSubcommandTerm(this.subcommandTerm(command)))), 0);
427
402
  }
428
403
  /**
429
404
  * Get the longest option term length.
430
405
  */
431
406
  longestOptionTermLength() {
432
- return this.visibleOptions().reduce((max, option) => {
433
- return Math.max(max, this.displayWidth(this.styleOptionTerm(this.optionTerm(option))));
434
- }, 0);
407
+ return this.visibleOptions().reduce((max, option) => Math.max(max, this.displayWidth(this.styleOptionTerm(this.optionTerm(option)))), 0);
435
408
  }
436
409
  /**
437
410
  * Get the longest argument term length.
438
411
  */
439
412
  longestArgumentTermLength() {
440
- return this.visibleArguments().reduce((max, argument) => {
441
- return Math.max(max, this.displayWidth(this.styleArgumentTerm(this.argumentTerm(argument))));
442
- }, 0);
413
+ return this.visibleArguments().reduce((max, argument) => Math.max(max, this.displayWidth(this.styleArgumentTerm(this.argumentTerm(argument)))), 0);
443
414
  }
444
415
  /**
445
416
  * Get the command usage to be displayed at the top of the built-in help.
@@ -456,9 +427,7 @@ var Help = class {
456
427
  ...this.cmd.options.length ? [
457
428
  this.usageDisplayOptionsAs
458
429
  ] : [],
459
- ...this.cmd.arguments.map((arg) => {
460
- return arg.required ? arg.variadic ? `<${arg.name}...>` : `<${arg.name}>` : arg.variadic ? `[${arg.name}...]` : `[${arg.name}]`;
461
- })
430
+ ...this.cmd.arguments.map((arg) => arg.required ? arg.variadic ? `<${arg.name}...>` : `<${arg.name}>` : arg.variadic ? `[${arg.name}...]` : `[${arg.name}]`)
462
431
  ].join(" ")}`.trim();
463
432
  }
464
433
  /**
@@ -784,26 +753,16 @@ ${itemIndentStr}`);
784
753
  ""
785
754
  ]);
786
755
  }
787
- const argumentList = this.visibleArguments().map((argument) => {
788
- return this.formatItem(this.styleArgumentTerm(this.argumentTerm(argument)), this.padWidth(), this.styleArgumentDescription(this.argumentDescription(argument)));
789
- });
756
+ const argumentList = this.visibleArguments().map((argument) => this.formatItem(this.styleArgumentTerm(this.argumentTerm(argument)), this.padWidth(), this.styleArgumentDescription(this.argumentDescription(argument))));
790
757
  output = output.concat(this.formatItemList("Arguments:", argumentList));
791
- const optionGroups = this.groupItems(this.cmd.options, this.visibleOptions(), (option) => {
792
- return option.group ?? "Options:";
793
- });
758
+ const optionGroups = this.groupItems(this.cmd.options, this.visibleOptions(), (option) => option.group ?? "Options:");
794
759
  optionGroups.forEach((options, group) => {
795
- const optionList = options.map((option) => {
796
- return this.formatItem(this.styleOptionTerm(this.optionTerm(option)), this.padWidth(), this.styleOptionDescription(this.optionDescription(option)));
797
- });
760
+ const optionList = options.map((option) => this.formatItem(this.styleOptionTerm(this.optionTerm(option)), this.padWidth(), this.styleOptionDescription(this.optionDescription(option))));
798
761
  output = output.concat(this.formatItemList(group, optionList));
799
762
  });
800
- const commandGroups = this.groupItems(Object.values(this.cmd.commands), this.visibleCommands(), (sub) => {
801
- return sub.group || "Commands:";
802
- });
763
+ const commandGroups = this.groupItems(Object.values(this.cmd.commands), this.visibleCommands(), (sub) => sub.group || "Commands:");
803
764
  commandGroups.forEach((commands, group) => {
804
- const commandList = commands.map((sub) => {
805
- return this.formatItem(this.styleSubcommandTerm(this.subcommandTerm(sub)), this.padWidth(), this.styleSubcommandDescription(this.subcommandDescription(sub)));
806
- });
765
+ const commandList = commands.map((sub) => this.formatItem(this.styleSubcommandTerm(this.subcommandTerm(sub)), this.padWidth(), this.styleSubcommandDescription(this.subcommandDescription(sub))));
807
766
  output = output.concat(this.formatItemList(group, commandList));
808
767
  });
809
768
  return output.join("\n");
@@ -858,39 +817,275 @@ _ts_decorate([
858
817
  _ts_metadata("design:returntype", Number)
859
818
  ], Help.prototype, "padWidth", null);
860
819
 
820
+ // src/lib/internal/isOptionLike.ts
821
+ function isOptionLike(word) {
822
+ return word.startsWith("-") && word !== "-" && !/^-(\d+\.?\d*|\.\d+)$/.test(word);
823
+ }
824
+ __name(isOptionLike, "isOptionLike");
825
+
826
+ // src/lib/internal/checkOptionValues.ts
827
+ function checkOptionValues(argv, options) {
828
+ const out = [];
829
+ const report = {
830
+ errors: [],
831
+ invalid: /* @__PURE__ */ new Set()
832
+ };
833
+ for (let i = 0; i < argv.length; i++) {
834
+ const word = argv[i];
835
+ if (word === "--") {
836
+ out.push(...argv.slice(i));
837
+ break;
838
+ }
839
+ const { keep, read } = word.startsWith("--") ? checkLong(word, argv[i + 1], options, report) : isOptionLike(word) ? checkShort(word, argv[i + 1], options, report) : {
840
+ keep: [
841
+ word
842
+ ],
843
+ read: 1
844
+ };
845
+ out.push(...keep);
846
+ i += read - 1;
847
+ }
848
+ return {
849
+ argv: out,
850
+ ...report
851
+ };
852
+ }
853
+ __name(checkOptionValues, "checkOptionValues");
854
+ function needsValue(def) {
855
+ return def.type === "string" && !(def.variadic && !def.required);
856
+ }
857
+ __name(needsValue, "needsValue");
858
+ function isNoValue(next) {
859
+ return next === void 0 || isOptionLike(next);
860
+ }
861
+ __name(isNoValue, "isNoValue");
862
+ function reportMissingValue(def, report) {
863
+ report.errors.push(`Option --${def.long} requires a value`);
864
+ report.invalid.add(def.name);
865
+ }
866
+ __name(reportMissingValue, "reportMissingValue");
867
+ function checkLong(word, next, options, report) {
868
+ const eq = word.indexOf("=");
869
+ const name = eq === -1 ? word.slice(2) : word.slice(2, eq);
870
+ const def = options.find((o) => o.name === name);
871
+ const negated = !def && name.startsWith("no-") ? options.find((o) => o.name === name.slice(3)) : void 0;
872
+ if (def?.type === "boolean" && eq !== -1) {
873
+ report.errors.push(`Option --${def.long} does not take a value: --${def.long}${word.slice(eq)}`);
874
+ report.invalid.add(def.name);
875
+ return {
876
+ keep: [],
877
+ read: 1
878
+ };
879
+ }
880
+ if (negated?.type === "string") {
881
+ report.errors.push(`Option --${negated.long} takes a value and cannot be negated: --no-${negated.long}`);
882
+ report.invalid.add(negated.name);
883
+ return {
884
+ keep: [],
885
+ read: 1
886
+ };
887
+ }
888
+ if (def?.type !== "string" || eq !== -1) {
889
+ return {
890
+ keep: [
891
+ word
892
+ ],
893
+ read: 1
894
+ };
895
+ }
896
+ if (!isNoValue(next)) {
897
+ return {
898
+ keep: [
899
+ word,
900
+ next
901
+ ],
902
+ read: 2
903
+ };
904
+ }
905
+ if (needsValue(def)) {
906
+ reportMissingValue(def, report);
907
+ return {
908
+ keep: [],
909
+ read: 1
910
+ };
911
+ }
912
+ return {
913
+ keep: [
914
+ word
915
+ ],
916
+ read: 1
917
+ };
918
+ }
919
+ __name(checkLong, "checkLong");
920
+ function checkShort(word, next, options, report) {
921
+ for (let j = 1; j < word.length; j++) {
922
+ const def = options.find((o) => o.short === word[j]);
923
+ if (def?.type !== "string") {
924
+ continue;
925
+ }
926
+ const before = j > 1 ? [
927
+ word.slice(0, j)
928
+ ] : [];
929
+ if (j < word.length - 1) {
930
+ return word[j + 1] === "=" ? {
931
+ keep: [
932
+ ...before,
933
+ `--${def.name}${word.slice(j + 1)}`
934
+ ],
935
+ read: 1
936
+ } : {
937
+ keep: [
938
+ word
939
+ ],
940
+ read: 1
941
+ };
942
+ }
943
+ if (!isNoValue(next)) {
944
+ return {
945
+ keep: [
946
+ word,
947
+ next
948
+ ],
949
+ read: 2
950
+ };
951
+ }
952
+ if (needsValue(def)) {
953
+ reportMissingValue(def, report);
954
+ return {
955
+ keep: before,
956
+ read: 1
957
+ };
958
+ }
959
+ break;
960
+ }
961
+ return {
962
+ keep: [
963
+ word
964
+ ],
965
+ read: 1
966
+ };
967
+ }
968
+ __name(checkShort, "checkShort");
969
+
861
970
  // src/lib/internal/collectVariadicOptionValues.ts
862
971
  function collectVariadicOptionValues(parsed, options) {
972
+ const taken = /* @__PURE__ */ new Set();
973
+ const collected = /* @__PURE__ */ new Map();
863
974
  for (let i = 0; i < parsed.tokens.length; i++) {
864
975
  const token = parsed.tokens[i];
865
976
  if (token.kind !== "option") {
866
977
  continue;
867
978
  }
868
- const def = options.find((o) => {
869
- return o.name === token.name;
870
- });
979
+ const def = options.find((o) => o.name === token.name);
871
980
  if (!def?.variadic || def.type !== "string") {
872
981
  continue;
873
982
  }
874
- const values = [
875
- token.value
876
- ];
983
+ const values = collected.get(token.name) ?? [];
984
+ collected.set(token.name, values);
985
+ if (token.value !== void 0) {
986
+ values.push(token.value);
987
+ }
877
988
  let j = i + 1;
878
989
  while (j < parsed.tokens.length && parsed.tokens[j].kind === "positional") {
879
- const positionalToken = parsed.tokens[j];
880
- values.push(positionalToken.value);
881
- const posIndex = parsed.positionals.indexOf(positionalToken.value);
882
- if (posIndex !== -1) {
883
- parsed.positionals.splice(posIndex, 1);
884
- }
990
+ values.push(parsed.tokens[j].value);
991
+ taken.add(j);
885
992
  j++;
886
993
  }
887
- Reflect.set(parsed.values, token.name, values.filter((v) => {
888
- return v !== void 0;
889
- }));
994
+ }
995
+ if (taken.size) {
996
+ parsed.positionals = parsed.tokens.filter((token, index) => token.kind === "positional" && !taken.has(index)).map((token) => token.value);
997
+ }
998
+ for (const [name, values] of collected) {
999
+ Reflect.set(parsed.values, name, values);
890
1000
  }
891
1001
  }
892
1002
  __name(collectVariadicOptionValues, "collectVariadicOptionValues");
893
1003
 
1004
+ // src/lib/internal/createOption.ts
1005
+ function createOption(flags, opts = {}) {
1006
+ const ins = {};
1007
+ const { short, long, name, argName } = parseOptionFlags(flags);
1008
+ ins.flags = flags;
1009
+ ins.short = short;
1010
+ ins.long = long;
1011
+ ins.name = name;
1012
+ ins.description = "";
1013
+ if (argName) {
1014
+ ins.type = "string";
1015
+ ins.argName = argName;
1016
+ if (flags.endsWith(">")) {
1017
+ if (flags.endsWith("...>")) {
1018
+ ins.required = true;
1019
+ ins.variadic = true;
1020
+ } else {
1021
+ ins.required = true;
1022
+ }
1023
+ } else if (flags.endsWith("]") && flags.endsWith("...]")) {
1024
+ ins.variadic = true;
1025
+ ins.defaultValue = opts.defaultValue ?? [];
1026
+ }
1027
+ } else {
1028
+ ins.type = "boolean";
1029
+ }
1030
+ for (const [key, value] of Object.entries(opts)) {
1031
+ if (value !== void 0) {
1032
+ Reflect.set(ins, key, value);
1033
+ }
1034
+ }
1035
+ if (ins.env && ins.defaultValue === void 0 && typeof process.env[ins.env] === "string") {
1036
+ ins.required = false;
1037
+ ins.flags = ins.flags.replace("<", "[").replace(">", "]");
1038
+ if (ins.type === "boolean") {
1039
+ ins.defaultValue = /^(t(rue)?|y(es)?|1)$/i.test(process.env[ins.env]);
1040
+ } else if (ins.variadic) {
1041
+ ins.defaultValue = process.env[ins.env].replace(/\[]/, "").split(",").map((v) => v.trim());
1042
+ } else {
1043
+ ins.defaultValue = process.env[ins.env];
1044
+ }
1045
+ }
1046
+ return ins;
1047
+ }
1048
+ __name(createOption, "createOption");
1049
+
1050
+ // src/lib/internal/findSubcommandIndex.ts
1051
+ function findSubcommandIndex(cmd, argv) {
1052
+ const takesNext = /* @__PURE__ */ __name((next) => next !== void 0 && !isOptionLike(next) ? 1 : 0, "takesNext");
1053
+ for (let i = 0; i < argv.length; i++) {
1054
+ const word = argv[i];
1055
+ if (word === "--") {
1056
+ return -1;
1057
+ }
1058
+ if (!isOptionLike(word)) {
1059
+ return findCommand(cmd, word) ? i : -1;
1060
+ }
1061
+ if (word.startsWith("--")) {
1062
+ const name = word.slice(2);
1063
+ const def = cmd.options.find((o) => o.long === name || o.name === name);
1064
+ if (def?.type === "string") {
1065
+ if (def.variadic) {
1066
+ return -1;
1067
+ }
1068
+ i += takesNext(argv[i + 1]);
1069
+ }
1070
+ continue;
1071
+ }
1072
+ for (let j = 1; j < word.length; j++) {
1073
+ const def = cmd.options.find((o) => o.short === word[j]);
1074
+ if (def?.type === "string") {
1075
+ if (j === word.length - 1) {
1076
+ if (def.variadic) {
1077
+ return -1;
1078
+ }
1079
+ i += takesNext(argv[i + 1]);
1080
+ }
1081
+ break;
1082
+ }
1083
+ }
1084
+ }
1085
+ return -1;
1086
+ }
1087
+ __name(findSubcommandIndex, "findSubcommandIndex");
1088
+
894
1089
  // src/lib/internal/mergeOptionDefaults.ts
895
1090
  function mergeOptionDefaults(values, options) {
896
1091
  for (const option of options) {
@@ -903,21 +1098,22 @@ __name(mergeOptionDefaults, "mergeOptionDefaults");
903
1098
 
904
1099
  // src/lib/internal/normalizeArgv.ts
905
1100
  function normalizeArgv(argv, options) {
1101
+ const end = argv.includes("--") ? argv.indexOf("--") : argv.length;
1102
+ const head = argv.slice(0, end);
906
1103
  for (const o of options) {
907
1104
  if (o.long === o.name) {
908
1105
  continue;
909
1106
  }
910
- argv = argv.map((a) => {
911
- if (a === `--${o.long}`) {
912
- return `--${o.name}`;
1107
+ for (let i = 0; i < head.length; i++) {
1108
+ const a = head[i];
1109
+ if (a === `--${o.long}` || a.startsWith(`--${o.long}=`)) {
1110
+ head[i] = `--${o.name}${a.slice(2 + o.long.length)}`;
1111
+ } else if (a === `--no-${o.long}`) {
1112
+ head[i] = `--no-${o.name}`;
913
1113
  }
914
- if (a === `--no-${o.long}`) {
915
- return `--no-${o.name}`;
916
- }
917
- return a;
918
- });
1114
+ }
919
1115
  }
920
- return argv;
1116
+ return head.concat(argv.slice(end));
921
1117
  }
922
1118
  __name(normalizeArgv, "normalizeArgv");
923
1119
  function resolveArguments(positionals, args) {
@@ -974,47 +1170,29 @@ function createLogger(name) {
974
1170
  const cyanArgs = createColoredArgs(C__default.default.cyan);
975
1171
  const yellowArgs = createColoredArgs(C__default.default.yellow);
976
1172
  return {
977
- start: /* @__PURE__ */ __name((...args) => {
978
- return console.info(...START, ...args);
979
- }, "start"),
980
- done: /* @__PURE__ */ __name((...args) => {
981
- return console.info(...DONE, ...args);
982
- }, "done"),
983
- info: /* @__PURE__ */ __name((...args) => {
984
- return console.info(...INFO, ...grayArgs(args));
985
- }, "info"),
986
- log: /* @__PURE__ */ __name((...args) => {
987
- return console.log(...NAME ? [
988
- NAME,
989
- ...args
990
- ] : args);
991
- }, "log"),
992
- warn: /* @__PURE__ */ __name((...args) => {
993
- return console.warn(...WARN, ...yellowArgs(args));
994
- }, "warn"),
995
- debug: /* @__PURE__ */ __name((...args) => {
996
- return console.debug(...DEBUG, ...cyanArgs(args));
997
- }, "debug"),
998
- error: /* @__PURE__ */ __name((...args) => {
999
- return args.forEach((arg) => {
1000
- return console.error(...ERROR, arg);
1001
- });
1002
- }, "error")
1173
+ start: /* @__PURE__ */ __name((...args) => console.info(...START, ...args), "start"),
1174
+ done: /* @__PURE__ */ __name((...args) => console.info(...DONE, ...args), "done"),
1175
+ info: /* @__PURE__ */ __name((...args) => console.info(...INFO, ...grayArgs(args)), "info"),
1176
+ log: /* @__PURE__ */ __name((...args) => console.log(...NAME ? [
1177
+ NAME,
1178
+ ...args
1179
+ ] : args), "log"),
1180
+ warn: /* @__PURE__ */ __name((...args) => console.warn(...WARN, ...yellowArgs(args)), "warn"),
1181
+ debug: /* @__PURE__ */ __name((...args) => console.debug(...DEBUG, ...cyanArgs(args)), "debug"),
1182
+ error: /* @__PURE__ */ __name((...args) => args.forEach((arg) => console.error(...ERROR, arg)), "error")
1003
1183
  };
1004
1184
  }
1005
1185
  __name(createLogger, "createLogger");
1006
1186
  function createColoredArgs(colorFn) {
1007
- return (args) => {
1008
- return args.map((arg) => {
1009
- if (predicate.isString(arg)) {
1010
- return arg === C__default.default.stripColor(arg) ? colorFn(arg) : arg;
1011
- } else if (predicate.isPrimitive(arg)) {
1012
- return colorFn(String(arg));
1013
- } else {
1014
- return arg;
1015
- }
1016
- });
1017
- };
1187
+ return (args) => args.map((arg) => {
1188
+ if (predicate.isString(arg)) {
1189
+ return arg === C__default.default.stripColor(arg) ? colorFn(arg) : arg;
1190
+ } else if (predicate.isPrimitive(arg)) {
1191
+ return colorFn(String(arg));
1192
+ } else {
1193
+ return arg;
1194
+ }
1195
+ });
1018
1196
  }
1019
1197
  __name(createColoredArgs, "createColoredArgs");
1020
1198
  function timer(arg, task) {
@@ -1031,9 +1209,7 @@ function timer(arg, task) {
1031
1209
  if (!types.isPromise(retval)) {
1032
1210
  return done(retval);
1033
1211
  }
1034
- return retval.then((result) => {
1035
- return done(result);
1036
- });
1212
+ return retval.then((result) => done(result));
1037
1213
  function done(retval2) {
1038
1214
  if (process.exitCode) {
1039
1215
  return retval2;
@@ -1047,7 +1223,7 @@ function timer(arg, task) {
1047
1223
  __name(timer, "timer");
1048
1224
 
1049
1225
  // src/lib/internal/validateParsed.ts
1050
- function validateParsed(args, optionValues, argDefs, optionDefs) {
1226
+ function validateParsed(args, optionValues, argDefs, optionDefs, rawNames = {}, invalid = /* @__PURE__ */ new Set()) {
1051
1227
  return argDefs.map((def, index) => {
1052
1228
  const value = args[index];
1053
1229
  if (def.required && (def.variadic ? Array.isArray(value) && value.length === 0 : value === void 0)) {
@@ -1055,34 +1231,25 @@ function validateParsed(args, optionValues, argDefs, optionDefs) {
1055
1231
  }
1056
1232
  if (def.choices && value !== void 0 && ![
1057
1233
  value
1058
- ].flat().every((v) => {
1059
- return def.choices.includes(v);
1060
- })) {
1061
- return `Invalid argument [${index}] ${def.usage}: Got \`${value}\`. Accepted values: [${def.choices.map((c) => {
1062
- return `\`${c}\``;
1063
- }).join(",")}]`;
1234
+ ].flat().every((v) => def.choices.includes(v))) {
1235
+ return `Invalid argument [${index}] ${def.usage}: Got \`${value}\`. Accepted values: [${def.choices.map((c) => `\`${c}\``).join(",")}]`;
1064
1236
  }
1065
1237
  }).concat(entriesOf(optionValues).map(([key, value]) => {
1066
- const def = optionDefs.find((o) => {
1067
- return o.name === key;
1068
- });
1238
+ const def = optionDefs.find((o) => o.name === key);
1069
1239
  if (!def) {
1070
- return `Unknown option --${key}`;
1240
+ return `Unknown option ${rawNames[key] ?? `--${key}`}`;
1071
1241
  }
1072
1242
  if (def.choices && value !== void 0 && !(def.variadic ? value : [
1073
1243
  value
1074
- ]).every((v) => {
1075
- return def.choices.includes(v);
1076
- })) {
1077
- return `Invalid option value ${def.flags}: Got \`${value}\`. Accepted values: [${def.choices.map((c) => {
1078
- return `\`${c}\``;
1079
- }).join(",")}]`;
1080
- }
1081
- })).filter((s) => {
1082
- return s !== void 0;
1083
- }).reduce((acc, curr) => {
1084
- return (acc ?? []).concat(curr);
1085
- }, void 0);
1244
+ ]).every((v) => def.choices.includes(v))) {
1245
+ return `Invalid option value ${def.flags}: Got \`${value}\`. Accepted values: [${def.choices.map((c) => `\`${c}\``).join(",")}]`;
1246
+ }
1247
+ })).concat(optionDefs.map((def) => {
1248
+ const value = optionValues[def.name];
1249
+ if (def.required && !invalid.has(def.name) && (value === void 0 || Array.isArray(value) && !value.length)) {
1250
+ return `Missing option ${def.flags}`;
1251
+ }
1252
+ })).filter((s) => s !== void 0).reduce((acc, curr) => (acc ?? []).concat(curr), void 0);
1086
1253
  }
1087
1254
  __name(validateParsed, "validateParsed");
1088
1255
 
@@ -1098,6 +1265,7 @@ function _ts_metadata2(k, v) {
1098
1265
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
1099
1266
  }
1100
1267
  __name(_ts_metadata2, "_ts_metadata");
1268
+ var builtinOptions = /* @__PURE__ */ new WeakSet();
1101
1269
  var Command = class _Command {
1102
1270
  static {
1103
1271
  __name(this, "Command");
@@ -1141,21 +1309,17 @@ var Command = class _Command {
1141
1309
  enumerable: false
1142
1310
  });
1143
1311
  if (!parent) {
1144
- this.addOption("-D, --debug", {
1145
- description: "Display debug information"
1146
- }).addOptionHook("debug", ({ cmd, ...data }) => {
1147
- console.debug(util.inspect(cmd, {
1148
- depth: 1,
1312
+ this.addBuiltinOption("-D, --debug", "Display debug information", ({ cmd, ...data }) => {
1313
+ data.logger.debug(util.inspect(cmd, {
1314
+ depth: 3,
1149
1315
  colors: true
1150
1316
  }));
1151
- console.debug(util.inspect(data, {
1152
- depth: 3,
1317
+ data.logger.debug(util.inspect(data, {
1318
+ depth: 1,
1153
1319
  colors: true
1154
1320
  }));
1155
1321
  });
1156
- this.addOption("-h, --help", {
1157
- description: "Display help information"
1158
- }).addOptionHook("help", ({ cmd }) => {
1322
+ this.addBuiltinOption("-h, --help", "Display help information", ({ cmd }) => {
1159
1323
  console.log(cmd.renderHelp());
1160
1324
  process.exitCode = 0;
1161
1325
  });
@@ -1206,9 +1370,7 @@ var Command = class _Command {
1206
1370
  if (findOption(this, "version")) {
1207
1371
  return this;
1208
1372
  }
1209
- return this.addOption("-V, --version", {
1210
- description: "Display semver version"
1211
- }).addOptionHook("version", ({ cmd }) => {
1373
+ return this.addBuiltinOption("-V, --version", "Display semver version", ({ cmd }) => {
1212
1374
  console.log(getCommandAndAncestors(cmd).find((c) => c.version)?.version);
1213
1375
  process.exitCode = 0;
1214
1376
  });
@@ -1306,57 +1468,46 @@ var Command = class _Command {
1306
1468
  * adds command-line option with type inference. Parses format: `-s, --long [<value>|[value]|<value...>|[value...]]`
1307
1469
  */
1308
1470
  addOption(flags, opts = {}) {
1309
- const ins = {};
1310
- const { short, long, name, argName } = parseOptionFlags(flags);
1471
+ const ins = createOption(flags, opts);
1311
1472
  for (const opt of this.options) {
1312
- if (opt.long === long) {
1313
- throw new Error(`Option long name, --${long} already in use by: ${opt.flags}`);
1314
- }
1315
- if (opt.short === short) {
1316
- throw new Error(`Option short name, -${short} already in use by: ${opt.flags}`);
1317
- }
1318
- }
1319
- ins.flags = flags;
1320
- ins.short = short;
1321
- ins.long = long;
1322
- ins.name = name;
1323
- ins.description = "";
1324
- if (argName) {
1325
- ins.type = "string";
1326
- ins.argName = argName;
1327
- if (flags.endsWith(">")) {
1328
- if (flags.endsWith("...>")) {
1329
- ins.required = true;
1330
- ins.variadic = true;
1331
- } else {
1332
- ins.required = true;
1473
+ const builtin = builtinOptions.has(opt);
1474
+ if (opt.long === ins.long) {
1475
+ if (!builtin) {
1476
+ throw new Error(`Option long name, --${ins.long} already in use by: ${opt.flags}`);
1333
1477
  }
1334
- } else if (flags.endsWith("]") && flags.endsWith("...]")) {
1335
- ins.variadic = true;
1336
- ins.defaultValue = opts.defaultValue ?? [];
1337
- }
1338
- } else {
1339
- ins.type = "boolean";
1340
- }
1341
- for (const [key, value] of Object.entries(opts)) {
1342
- if (value !== void 0) {
1343
- Reflect.set(ins, key, value);
1478
+ this.options = this.options.filter((o) => o !== opt);
1479
+ this.hooks = this.hooks.filter((h) => h.name !== opt.name);
1480
+ continue;
1344
1481
  }
1345
- }
1346
- if (ins.env && ins.defaultValue === void 0 && typeof process.env[ins.env] === "string") {
1347
- ins.required = false;
1348
- ins.flags = ins.flags.replace("<", "[").replace(">", "]");
1349
- if (ins.type === "boolean") {
1350
- ins.defaultValue = /^(t(rue)?|y(es)?|1)$/i.test(process.env[ins.env]);
1351
- } else if (ins.variadic) {
1352
- ins.defaultValue = process.env[ins.env].replace(/\[]/, "").split(",").map((v) => v.trim());
1353
- } else {
1354
- ins.defaultValue = process.env[ins.env];
1482
+ if (opt.short === ins.short) {
1483
+ if (!builtin) {
1484
+ throw new Error(`Option short name, -${ins.short} already in use by: ${opt.flags}`);
1485
+ }
1486
+ const longOnly = {
1487
+ ...opt,
1488
+ short: void 0,
1489
+ flags: `--${opt.long}`
1490
+ };
1491
+ builtinOptions.add(longOnly);
1492
+ this.options = this.options.map((o) => o === opt ? longOnly : o);
1355
1493
  }
1356
1494
  }
1357
1495
  this.options.push(ins);
1358
1496
  return this;
1359
1497
  }
1498
+ /** adds a built-in option with its hook; it goes without its short flag when an option already has that */
1499
+ addBuiltinOption(flags, description, action) {
1500
+ const ins = createOption(flags, {
1501
+ description
1502
+ });
1503
+ if (this.options.some((o) => o.short === ins.short)) {
1504
+ ins.short = void 0;
1505
+ ins.flags = `--${ins.long}`;
1506
+ }
1507
+ builtinOptions.add(ins);
1508
+ this.options.push(ins);
1509
+ return this.addOptionHook(ins.name, action);
1510
+ }
1360
1511
  /**
1361
1512
  * register an action to be invoked when an option is set to true or string value.
1362
1513
  *
@@ -1366,6 +1517,9 @@ var Command = class _Command {
1366
1517
  */
1367
1518
  addOptionHook(optionName, action) {
1368
1519
  const def = findOption(this, optionName);
1520
+ if (!def) {
1521
+ throw new Error(`Cannot add a hook for option "${String(optionName)}": ${this.name} has no such option`);
1522
+ }
1369
1523
  if (!def.group && /process\.exitCode ?= ?.+;?\s*}$/.test(action.toString())) {
1370
1524
  def.group = "Command Options";
1371
1525
  }
@@ -1378,20 +1532,24 @@ var Command = class _Command {
1378
1532
  }
1379
1533
  /** parses command-line arguments with subcommand support and type-safe validation. */
1380
1534
  parseArgv(argv = process.argv.slice(2)) {
1381
- const sub = findCommand(this, argv[0]);
1382
- if (sub) {
1383
- return sub.parseArgv(argv.slice(1));
1535
+ const subIndex = findSubcommandIndex(this, argv);
1536
+ if (subIndex !== -1) {
1537
+ const sub = findCommand(this, argv[subIndex]);
1538
+ return sub.parseArgv(argv.filter((_, i) => i !== subIndex));
1384
1539
  }
1385
1540
  argv = normalizeArgv(argv, this.options);
1541
+ const checked = checkOptionValues(argv, this.options);
1386
1542
  const parsed = util.parseArgs({
1387
- args: argv,
1543
+ args: checked.argv,
1388
1544
  options: Object.fromEntries(this.options.map((o) => [
1389
1545
  o.name,
1390
1546
  {
1391
1547
  type: o.type,
1392
- short: o.short,
1393
1548
  default: o.defaultValue,
1394
- multiple: !!o.variadic
1549
+ multiple: !!o.variadic,
1550
+ ...o.short ? {
1551
+ short: o.short
1552
+ } : {}
1395
1553
  }
1396
1554
  ])),
1397
1555
  allowPositionals: true,
@@ -1404,7 +1562,18 @@ var Command = class _Command {
1404
1562
  parsed.values = objSortKeys(parsed.values, (a, b) => a[1] === false ? 1 : b[1] === false ? -1 : a[1] === true ? 1 : b[1] === true ? -1 : 0);
1405
1563
  const args = resolveArguments(parsed.positionals, this.arguments);
1406
1564
  const opts = filterObject(parsed.values, (value) => value !== void 0);
1407
- const errors = validateParsed(args, parsed.values, this.arguments, this.options);
1565
+ const rawNames = Object.fromEntries(parsed.tokens.flatMap((t) => t.kind === "option" ? [
1566
+ [
1567
+ t.name,
1568
+ t.rawName
1569
+ ]
1570
+ ] : []));
1571
+ const unexpected = this.arguments.some((a) => a.variadic) ? [] : parsed.positionals.slice(this.arguments.length);
1572
+ const errorList = checked.errors.concat(validateParsed(args, parsed.values, this.arguments, this.options, rawNames, checked.invalid) ?? []).concat(
1573
+ // a command with subcommands has no arguments of its own: the words after an unknown name were meant for it
1574
+ Object.keys(this.commands).length ? unexpected.slice(0, 1).map((word) => `Unknown command \`${word}\``) : unexpected.map((word) => `Unexpected argument \`${word}\``)
1575
+ );
1576
+ const errors = errorList.length ? errorList : void 0;
1408
1577
  const path = getCommandAncestors(this).map((c) => c.name);
1409
1578
  const data = {
1410
1579
  path,
@@ -1416,37 +1585,42 @@ var Command = class _Command {
1416
1585
  cmd: this
1417
1586
  };
1418
1587
  const hooks = this.hooks.filter((t) => t.predicate(data));
1419
- const execute = /* @__PURE__ */ __name(async () => {
1588
+ const execute = /* @__PURE__ */ __name(async () => await timer([
1589
+ [
1590
+ ...path,
1591
+ this.name
1592
+ ].join(" "),
1593
+ this.summary || this.description
1594
+ ], async (logger) => {
1420
1595
  for (const hook of hooks) {
1421
- await hook.action(data);
1596
+ await hook.action({
1597
+ ...data,
1598
+ get logger() {
1599
+ return logger;
1600
+ }
1601
+ });
1422
1602
  if (process.exitCode !== void 0) {
1423
1603
  return;
1424
1604
  }
1425
1605
  }
1426
- await timer([
1427
- [
1428
- ...path,
1429
- this.name
1430
- ].join(" "),
1431
- this.description
1432
- ], async (logger) => {
1433
- if (errors) {
1434
- errors.forEach((msg) => logger.error(C__default.default.red(msg)));
1435
- process.exitCode = 1;
1436
- return;
1437
- }
1438
- if (this.action) {
1439
- return await this.action(...args, opts, {
1440
- ...data,
1441
- args,
1442
- opts,
1443
- cmd: this,
1444
- logger
1445
- });
1446
- }
1447
- console.log(this.renderHelp());
1448
- });
1449
- }, "execute");
1606
+ if (errors) {
1607
+ errors.forEach((msg) => logger.error(C__default.default.red(msg)));
1608
+ process.exitCode = 1;
1609
+ return;
1610
+ }
1611
+ if (this.action) {
1612
+ return await this.action(...args, opts, {
1613
+ ...data,
1614
+ args,
1615
+ opts,
1616
+ cmd: this,
1617
+ get logger() {
1618
+ return logger;
1619
+ }
1620
+ });
1621
+ }
1622
+ console.log(this.renderHelp());
1623
+ }), "execute");
1450
1624
  return {
1451
1625
  ...data,
1452
1626
  hooks,
@@ -1455,11 +1629,13 @@ var Command = class _Command {
1455
1629
  }
1456
1630
  /**
1457
1631
  * sets the main action handler for this command, which is executed after any matching option hooks when the command is invoked.
1458
- * The handler receives parsed arguments and options with correct typings.
1632
+ * The handler receives parsed arguments and options with correct typings. It may return a value (or a promise of one):
1633
+ * `execute()` of the parse result gives it back, typed.
1459
1634
  */
1460
1635
  setAction(fn) {
1461
- this.action = setName(this.name, fn);
1462
- return this;
1636
+ const typed = this;
1637
+ typed.action = setName(this.name, fn);
1638
+ return typed;
1463
1639
  }
1464
1640
  /** returns a new Command instance. Override this method in subclasses. */
1465
1641
  createSubcommand(name) {