@bemoje/cli 4.0.1 → 5.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.cjs CHANGED
@@ -350,13 +350,9 @@ var Help = class {
350
350
  * Get an array of the visible subcommands. Includes a placeholder for the implicit help command, if there is one.
351
351
  */
352
352
  visibleCommands() {
353
- const res = Object.values(this.cmd.commands).filter((c) => {
354
- return !c.hidden;
355
- });
353
+ const res = Object.values(this.cmd.commands).filter((c) => !c.hidden);
356
354
  if (this.sortSubcommands) {
357
- res.sort((a, b) => {
358
- return a.name.localeCompare(b.name);
359
- });
355
+ res.sort((a, b) => a.name.localeCompare(b.name));
360
356
  }
361
357
  return res;
362
358
  }
@@ -364,18 +360,17 @@ var Help = class {
364
360
  * Compare options for sort.
365
361
  */
366
362
  compareOptions(a, b) {
367
- const getSortKey = /* @__PURE__ */ __name((option) => {
368
- return option.short ? option.short.replace(/^-/, "") : option.long.replace(/^--/, "");
369
- }, "getSortKey");
363
+ const getSortKey = /* @__PURE__ */ __name((option) => (
364
+ // WYSIWYG for order displayed in help. Short used for comparison if present. No special handling for negated.
365
+ option.short ? option.short.replace(/^-/, "") : option.long.replace(/^--/, "")
366
+ ), "getSortKey");
370
367
  return getSortKey(a).localeCompare(getSortKey(b));
371
368
  }
372
369
  /**
373
370
  * Get an array of the visible options. Includes a placeholder for the implicit help option, if there is one.
374
371
  */
375
372
  visibleOptions() {
376
- const res = this.cmd.options.filter((option) => {
377
- return !option.hidden;
378
- });
373
+ const res = this.cmd.options.filter((option) => !option.hidden);
379
374
  if (this.sortOptions) {
380
375
  res.sort(this.compareOptions);
381
376
  }
@@ -391,9 +386,7 @@ var Help = class {
391
386
  * Get the command term to show in the list of subcommands.
392
387
  */
393
388
  subcommandTerm(sub) {
394
- const args = sub.arguments.map((arg) => {
395
- return arg.usage;
396
- }).join(" ");
389
+ const args = sub.arguments.map((arg) => arg.usage).join(" ");
397
390
  return (sub.aliases[0] ? `${sub.aliases[0].padEnd(this.longestSubcommandAliasLength(), " ")} | ` : "") + sub.name + (sub.options.length ? ` ${this.usageDisplayOptionsAs}` : "") + // simplistic check for non-help option
398
391
  (args ? ` ${args}` : "");
399
392
  }
@@ -413,33 +406,25 @@ var Help = class {
413
406
  * Get the longest subcommand primary alias length.
414
407
  */
415
408
  longestSubcommandAliasLength() {
416
- return Math.max(0, ...this.visibleCommands().map((c) => {
417
- return c.aliases[0]?.length || 0;
418
- }));
409
+ return Math.max(0, ...this.visibleCommands().map((c) => c.aliases[0]?.length || 0));
419
410
  }
420
411
  /**
421
412
  * Get the longest subcommand term length.
422
413
  */
423
414
  longestSubcommandTermLength() {
424
- return this.visibleCommands().reduce((max, command) => {
425
- return Math.max(max, this.displayWidth(this.styleSubcommandTerm(this.subcommandTerm(command))));
426
- }, 0);
415
+ return this.visibleCommands().reduce((max, command) => Math.max(max, this.displayWidth(this.styleSubcommandTerm(this.subcommandTerm(command)))), 0);
427
416
  }
428
417
  /**
429
418
  * Get the longest option term length.
430
419
  */
431
420
  longestOptionTermLength() {
432
- return this.visibleOptions().reduce((max, option) => {
433
- return Math.max(max, this.displayWidth(this.styleOptionTerm(this.optionTerm(option))));
434
- }, 0);
421
+ return this.visibleOptions().reduce((max, option) => Math.max(max, this.displayWidth(this.styleOptionTerm(this.optionTerm(option)))), 0);
435
422
  }
436
423
  /**
437
424
  * Get the longest argument term length.
438
425
  */
439
426
  longestArgumentTermLength() {
440
- return this.visibleArguments().reduce((max, argument) => {
441
- return Math.max(max, this.displayWidth(this.styleArgumentTerm(this.argumentTerm(argument))));
442
- }, 0);
427
+ return this.visibleArguments().reduce((max, argument) => Math.max(max, this.displayWidth(this.styleArgumentTerm(this.argumentTerm(argument)))), 0);
443
428
  }
444
429
  /**
445
430
  * Get the command usage to be displayed at the top of the built-in help.
@@ -456,9 +441,7 @@ var Help = class {
456
441
  ...this.cmd.options.length ? [
457
442
  this.usageDisplayOptionsAs
458
443
  ] : [],
459
- ...this.cmd.arguments.map((arg) => {
460
- return arg.required ? arg.variadic ? `<${arg.name}...>` : `<${arg.name}>` : arg.variadic ? `[${arg.name}...]` : `[${arg.name}]`;
461
- })
444
+ ...this.cmd.arguments.map((arg) => arg.required ? arg.variadic ? `<${arg.name}...>` : `<${arg.name}>` : arg.variadic ? `[${arg.name}...]` : `[${arg.name}]`)
462
445
  ].join(" ")}`.trim();
463
446
  }
464
447
  /**
@@ -784,26 +767,16 @@ ${itemIndentStr}`);
784
767
  ""
785
768
  ]);
786
769
  }
787
- const argumentList = this.visibleArguments().map((argument) => {
788
- return this.formatItem(this.styleArgumentTerm(this.argumentTerm(argument)), this.padWidth(), this.styleArgumentDescription(this.argumentDescription(argument)));
789
- });
770
+ const argumentList = this.visibleArguments().map((argument) => this.formatItem(this.styleArgumentTerm(this.argumentTerm(argument)), this.padWidth(), this.styleArgumentDescription(this.argumentDescription(argument))));
790
771
  output = output.concat(this.formatItemList("Arguments:", argumentList));
791
- const optionGroups = this.groupItems(this.cmd.options, this.visibleOptions(), (option) => {
792
- return option.group ?? "Options:";
793
- });
772
+ const optionGroups = this.groupItems(this.cmd.options, this.visibleOptions(), (option) => option.group ?? "Options:");
794
773
  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
- });
774
+ const optionList = options.map((option) => this.formatItem(this.styleOptionTerm(this.optionTerm(option)), this.padWidth(), this.styleOptionDescription(this.optionDescription(option))));
798
775
  output = output.concat(this.formatItemList(group, optionList));
799
776
  });
800
- const commandGroups = this.groupItems(Object.values(this.cmd.commands), this.visibleCommands(), (sub) => {
801
- return sub.group || "Commands:";
802
- });
777
+ const commandGroups = this.groupItems(Object.values(this.cmd.commands), this.visibleCommands(), (sub) => sub.group || "Commands:");
803
778
  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
- });
779
+ const commandList = commands.map((sub) => this.formatItem(this.styleSubcommandTerm(this.subcommandTerm(sub)), this.padWidth(), this.styleSubcommandDescription(this.subcommandDescription(sub))));
807
780
  output = output.concat(this.formatItemList(group, commandList));
808
781
  });
809
782
  return output.join("\n");
@@ -858,39 +831,275 @@ _ts_decorate([
858
831
  _ts_metadata("design:returntype", Number)
859
832
  ], Help.prototype, "padWidth", null);
860
833
 
834
+ // src/lib/internal/isOptionLike.ts
835
+ function isOptionLike(word) {
836
+ return word.startsWith("-") && word !== "-" && !/^-(\d+\.?\d*|\.\d+)$/.test(word);
837
+ }
838
+ __name(isOptionLike, "isOptionLike");
839
+
840
+ // src/lib/internal/checkOptionValues.ts
841
+ function checkOptionValues(argv, options) {
842
+ const out = [];
843
+ const report = {
844
+ errors: [],
845
+ invalid: /* @__PURE__ */ new Set()
846
+ };
847
+ for (let i = 0; i < argv.length; i++) {
848
+ const word = argv[i];
849
+ if (word === "--") {
850
+ out.push(...argv.slice(i));
851
+ break;
852
+ }
853
+ const { keep, read } = word.startsWith("--") ? checkLong(word, argv[i + 1], options, report) : isOptionLike(word) ? checkShort(word, argv[i + 1], options, report) : {
854
+ keep: [
855
+ word
856
+ ],
857
+ read: 1
858
+ };
859
+ out.push(...keep);
860
+ i += read - 1;
861
+ }
862
+ return {
863
+ argv: out,
864
+ ...report
865
+ };
866
+ }
867
+ __name(checkOptionValues, "checkOptionValues");
868
+ function needsValue(def) {
869
+ return def.type === "string" && !(def.variadic && !def.required);
870
+ }
871
+ __name(needsValue, "needsValue");
872
+ function isNoValue(next) {
873
+ return next === void 0 || isOptionLike(next);
874
+ }
875
+ __name(isNoValue, "isNoValue");
876
+ function reportMissingValue(def, report) {
877
+ report.errors.push(`Option --${def.long} requires a value`);
878
+ report.invalid.add(def.name);
879
+ }
880
+ __name(reportMissingValue, "reportMissingValue");
881
+ function checkLong(word, next, options, report) {
882
+ const eq = word.indexOf("=");
883
+ const name = eq === -1 ? word.slice(2) : word.slice(2, eq);
884
+ const def = options.find((o) => o.name === name);
885
+ const negated = !def && name.startsWith("no-") ? options.find((o) => o.name === name.slice(3)) : void 0;
886
+ if (def?.type === "boolean" && eq !== -1) {
887
+ report.errors.push(`Option --${def.long} does not take a value: --${def.long}${word.slice(eq)}`);
888
+ report.invalid.add(def.name);
889
+ return {
890
+ keep: [],
891
+ read: 1
892
+ };
893
+ }
894
+ if (negated?.type === "string") {
895
+ report.errors.push(`Option --${negated.long} takes a value and cannot be negated: --no-${negated.long}`);
896
+ report.invalid.add(negated.name);
897
+ return {
898
+ keep: [],
899
+ read: 1
900
+ };
901
+ }
902
+ if (def?.type !== "string" || eq !== -1) {
903
+ return {
904
+ keep: [
905
+ word
906
+ ],
907
+ read: 1
908
+ };
909
+ }
910
+ if (!isNoValue(next)) {
911
+ return {
912
+ keep: [
913
+ word,
914
+ next
915
+ ],
916
+ read: 2
917
+ };
918
+ }
919
+ if (needsValue(def)) {
920
+ reportMissingValue(def, report);
921
+ return {
922
+ keep: [],
923
+ read: 1
924
+ };
925
+ }
926
+ return {
927
+ keep: [
928
+ word
929
+ ],
930
+ read: 1
931
+ };
932
+ }
933
+ __name(checkLong, "checkLong");
934
+ function checkShort(word, next, options, report) {
935
+ for (let j = 1; j < word.length; j++) {
936
+ const def = options.find((o) => o.short === word[j]);
937
+ if (def?.type !== "string") {
938
+ continue;
939
+ }
940
+ const before = j > 1 ? [
941
+ word.slice(0, j)
942
+ ] : [];
943
+ if (j < word.length - 1) {
944
+ return word[j + 1] === "=" ? {
945
+ keep: [
946
+ ...before,
947
+ `--${def.name}${word.slice(j + 1)}`
948
+ ],
949
+ read: 1
950
+ } : {
951
+ keep: [
952
+ word
953
+ ],
954
+ read: 1
955
+ };
956
+ }
957
+ if (!isNoValue(next)) {
958
+ return {
959
+ keep: [
960
+ word,
961
+ next
962
+ ],
963
+ read: 2
964
+ };
965
+ }
966
+ if (needsValue(def)) {
967
+ reportMissingValue(def, report);
968
+ return {
969
+ keep: before,
970
+ read: 1
971
+ };
972
+ }
973
+ break;
974
+ }
975
+ return {
976
+ keep: [
977
+ word
978
+ ],
979
+ read: 1
980
+ };
981
+ }
982
+ __name(checkShort, "checkShort");
983
+
861
984
  // src/lib/internal/collectVariadicOptionValues.ts
862
985
  function collectVariadicOptionValues(parsed, options) {
986
+ const taken = /* @__PURE__ */ new Set();
987
+ const collected = /* @__PURE__ */ new Map();
863
988
  for (let i = 0; i < parsed.tokens.length; i++) {
864
989
  const token = parsed.tokens[i];
865
990
  if (token.kind !== "option") {
866
991
  continue;
867
992
  }
868
- const def = options.find((o) => {
869
- return o.name === token.name;
870
- });
993
+ const def = options.find((o) => o.name === token.name);
871
994
  if (!def?.variadic || def.type !== "string") {
872
995
  continue;
873
996
  }
874
- const values = [
875
- token.value
876
- ];
997
+ const values = collected.get(token.name) ?? [];
998
+ collected.set(token.name, values);
999
+ if (token.value !== void 0) {
1000
+ values.push(token.value);
1001
+ }
877
1002
  let j = i + 1;
878
1003
  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
- }
1004
+ values.push(parsed.tokens[j].value);
1005
+ taken.add(j);
885
1006
  j++;
886
1007
  }
887
- Reflect.set(parsed.values, token.name, values.filter((v) => {
888
- return v !== void 0;
889
- }));
1008
+ }
1009
+ if (taken.size) {
1010
+ parsed.positionals = parsed.tokens.filter((token, index) => token.kind === "positional" && !taken.has(index)).map((token) => token.value);
1011
+ }
1012
+ for (const [name, values] of collected) {
1013
+ Reflect.set(parsed.values, name, values);
890
1014
  }
891
1015
  }
892
1016
  __name(collectVariadicOptionValues, "collectVariadicOptionValues");
893
1017
 
1018
+ // src/lib/internal/createOption.ts
1019
+ function createOption(flags, opts = {}) {
1020
+ const ins = {};
1021
+ const { short, long, name, argName } = parseOptionFlags(flags);
1022
+ ins.flags = flags;
1023
+ ins.short = short;
1024
+ ins.long = long;
1025
+ ins.name = name;
1026
+ ins.description = "";
1027
+ if (argName) {
1028
+ ins.type = "string";
1029
+ ins.argName = argName;
1030
+ if (flags.endsWith(">")) {
1031
+ if (flags.endsWith("...>")) {
1032
+ ins.required = true;
1033
+ ins.variadic = true;
1034
+ } else {
1035
+ ins.required = true;
1036
+ }
1037
+ } else if (flags.endsWith("]") && flags.endsWith("...]")) {
1038
+ ins.variadic = true;
1039
+ ins.defaultValue = opts.defaultValue ?? [];
1040
+ }
1041
+ } else {
1042
+ ins.type = "boolean";
1043
+ }
1044
+ for (const [key, value] of Object.entries(opts)) {
1045
+ if (value !== void 0) {
1046
+ Reflect.set(ins, key, value);
1047
+ }
1048
+ }
1049
+ if (ins.env && ins.defaultValue === void 0 && typeof process.env[ins.env] === "string") {
1050
+ ins.required = false;
1051
+ ins.flags = ins.flags.replace("<", "[").replace(">", "]");
1052
+ if (ins.type === "boolean") {
1053
+ ins.defaultValue = /^(t(rue)?|y(es)?|1)$/i.test(process.env[ins.env]);
1054
+ } else if (ins.variadic) {
1055
+ ins.defaultValue = process.env[ins.env].replace(/\[]/, "").split(",").map((v) => v.trim());
1056
+ } else {
1057
+ ins.defaultValue = process.env[ins.env];
1058
+ }
1059
+ }
1060
+ return ins;
1061
+ }
1062
+ __name(createOption, "createOption");
1063
+
1064
+ // src/lib/internal/findSubcommandIndex.ts
1065
+ function findSubcommandIndex(cmd, argv) {
1066
+ const takesNext = /* @__PURE__ */ __name((next) => next !== void 0 && !isOptionLike(next) ? 1 : 0, "takesNext");
1067
+ for (let i = 0; i < argv.length; i++) {
1068
+ const word = argv[i];
1069
+ if (word === "--") {
1070
+ return -1;
1071
+ }
1072
+ if (!isOptionLike(word)) {
1073
+ return findCommand(cmd, word) ? i : -1;
1074
+ }
1075
+ if (word.startsWith("--")) {
1076
+ const name = word.slice(2);
1077
+ const def = cmd.options.find((o) => o.long === name || o.name === name);
1078
+ if (def?.type === "string") {
1079
+ if (def.variadic) {
1080
+ return -1;
1081
+ }
1082
+ i += takesNext(argv[i + 1]);
1083
+ }
1084
+ continue;
1085
+ }
1086
+ for (let j = 1; j < word.length; j++) {
1087
+ const def = cmd.options.find((o) => o.short === word[j]);
1088
+ if (def?.type === "string") {
1089
+ if (j === word.length - 1) {
1090
+ if (def.variadic) {
1091
+ return -1;
1092
+ }
1093
+ i += takesNext(argv[i + 1]);
1094
+ }
1095
+ break;
1096
+ }
1097
+ }
1098
+ }
1099
+ return -1;
1100
+ }
1101
+ __name(findSubcommandIndex, "findSubcommandIndex");
1102
+
894
1103
  // src/lib/internal/mergeOptionDefaults.ts
895
1104
  function mergeOptionDefaults(values, options) {
896
1105
  for (const option of options) {
@@ -903,21 +1112,22 @@ __name(mergeOptionDefaults, "mergeOptionDefaults");
903
1112
 
904
1113
  // src/lib/internal/normalizeArgv.ts
905
1114
  function normalizeArgv(argv, options) {
1115
+ const end = argv.includes("--") ? argv.indexOf("--") : argv.length;
1116
+ const head = argv.slice(0, end);
906
1117
  for (const o of options) {
907
1118
  if (o.long === o.name) {
908
1119
  continue;
909
1120
  }
910
- argv = argv.map((a) => {
911
- if (a === `--${o.long}`) {
912
- return `--${o.name}`;
913
- }
914
- if (a === `--no-${o.long}`) {
915
- return `--no-${o.name}`;
1121
+ for (let i = 0; i < head.length; i++) {
1122
+ const a = head[i];
1123
+ if (a === `--${o.long}` || a.startsWith(`--${o.long}=`)) {
1124
+ head[i] = `--${o.name}${a.slice(2 + o.long.length)}`;
1125
+ } else if (a === `--no-${o.long}`) {
1126
+ head[i] = `--no-${o.name}`;
916
1127
  }
917
- return a;
918
- });
1128
+ }
919
1129
  }
920
- return argv;
1130
+ return head.concat(argv.slice(end));
921
1131
  }
922
1132
  __name(normalizeArgv, "normalizeArgv");
923
1133
  function resolveArguments(positionals, args) {
@@ -974,47 +1184,29 @@ function createLogger(name) {
974
1184
  const cyanArgs = createColoredArgs(C__default.default.cyan);
975
1185
  const yellowArgs = createColoredArgs(C__default.default.yellow);
976
1186
  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")
1187
+ start: /* @__PURE__ */ __name((...args) => console.info(...START, ...args), "start"),
1188
+ done: /* @__PURE__ */ __name((...args) => console.info(...DONE, ...args), "done"),
1189
+ info: /* @__PURE__ */ __name((...args) => console.info(...INFO, ...grayArgs(args)), "info"),
1190
+ log: /* @__PURE__ */ __name((...args) => console.log(...NAME ? [
1191
+ NAME,
1192
+ ...args
1193
+ ] : args), "log"),
1194
+ warn: /* @__PURE__ */ __name((...args) => console.warn(...WARN, ...yellowArgs(args)), "warn"),
1195
+ debug: /* @__PURE__ */ __name((...args) => console.debug(...DEBUG, ...cyanArgs(args)), "debug"),
1196
+ error: /* @__PURE__ */ __name((...args) => args.forEach((arg) => console.error(...ERROR, arg)), "error")
1003
1197
  };
1004
1198
  }
1005
1199
  __name(createLogger, "createLogger");
1006
1200
  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
- };
1201
+ return (args) => args.map((arg) => {
1202
+ if (predicate.isString(arg)) {
1203
+ return arg === C__default.default.stripColor(arg) ? colorFn(arg) : arg;
1204
+ } else if (predicate.isPrimitive(arg)) {
1205
+ return colorFn(String(arg));
1206
+ } else {
1207
+ return arg;
1208
+ }
1209
+ });
1018
1210
  }
1019
1211
  __name(createColoredArgs, "createColoredArgs");
1020
1212
  function timer(arg, task) {
@@ -1031,9 +1223,7 @@ function timer(arg, task) {
1031
1223
  if (!types.isPromise(retval)) {
1032
1224
  return done(retval);
1033
1225
  }
1034
- return retval.then((result) => {
1035
- return done(result);
1036
- });
1226
+ return retval.then((result) => done(result));
1037
1227
  function done(retval2) {
1038
1228
  if (process.exitCode) {
1039
1229
  return retval2;
@@ -1047,7 +1237,7 @@ function timer(arg, task) {
1047
1237
  __name(timer, "timer");
1048
1238
 
1049
1239
  // src/lib/internal/validateParsed.ts
1050
- function validateParsed(args, optionValues, argDefs, optionDefs) {
1240
+ function validateParsed(args, optionValues, argDefs, optionDefs, rawNames = {}, invalid = /* @__PURE__ */ new Set()) {
1051
1241
  return argDefs.map((def, index) => {
1052
1242
  const value = args[index];
1053
1243
  if (def.required && (def.variadic ? Array.isArray(value) && value.length === 0 : value === void 0)) {
@@ -1055,34 +1245,25 @@ function validateParsed(args, optionValues, argDefs, optionDefs) {
1055
1245
  }
1056
1246
  if (def.choices && value !== void 0 && ![
1057
1247
  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(",")}]`;
1248
+ ].flat().every((v) => def.choices.includes(v))) {
1249
+ return `Invalid argument [${index}] ${def.usage}: Got \`${value}\`. Accepted values: [${def.choices.map((c) => `\`${c}\``).join(",")}]`;
1064
1250
  }
1065
1251
  }).concat(entriesOf(optionValues).map(([key, value]) => {
1066
- const def = optionDefs.find((o) => {
1067
- return o.name === key;
1068
- });
1252
+ const def = optionDefs.find((o) => o.name === key);
1069
1253
  if (!def) {
1070
- return `Unknown option --${key}`;
1254
+ return `Unknown option ${rawNames[key] ?? `--${key}`}`;
1071
1255
  }
1072
1256
  if (def.choices && value !== void 0 && !(def.variadic ? value : [
1073
1257
  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);
1258
+ ]).every((v) => def.choices.includes(v))) {
1259
+ return `Invalid option value ${def.flags}: Got \`${value}\`. Accepted values: [${def.choices.map((c) => `\`${c}\``).join(",")}]`;
1260
+ }
1261
+ })).concat(optionDefs.map((def) => {
1262
+ const value = optionValues[def.name];
1263
+ if (def.required && !invalid.has(def.name) && (value === void 0 || Array.isArray(value) && !value.length)) {
1264
+ return `Missing option ${def.flags}`;
1265
+ }
1266
+ })).filter((s) => s !== void 0).reduce((acc, curr) => (acc ?? []).concat(curr), void 0);
1086
1267
  }
1087
1268
  __name(validateParsed, "validateParsed");
1088
1269
 
@@ -1098,6 +1279,7 @@ function _ts_metadata2(k, v) {
1098
1279
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
1099
1280
  }
1100
1281
  __name(_ts_metadata2, "_ts_metadata");
1282
+ var builtinOptions = /* @__PURE__ */ new WeakSet();
1101
1283
  var Command = class _Command {
1102
1284
  static {
1103
1285
  __name(this, "Command");
@@ -1141,21 +1323,17 @@ var Command = class _Command {
1141
1323
  enumerable: false
1142
1324
  });
1143
1325
  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,
1326
+ this.addBuiltinOption("-D, --debug", "Display debug information", ({ cmd, ...data }) => {
1327
+ data.logger.debug(util.inspect(cmd, {
1328
+ depth: 3,
1149
1329
  colors: true
1150
1330
  }));
1151
- console.debug(util.inspect(data, {
1152
- depth: 3,
1331
+ data.logger.debug(util.inspect(data, {
1332
+ depth: 1,
1153
1333
  colors: true
1154
1334
  }));
1155
1335
  });
1156
- this.addOption("-h, --help", {
1157
- description: "Display help information"
1158
- }).addOptionHook("help", ({ cmd }) => {
1336
+ this.addBuiltinOption("-h, --help", "Display help information", ({ cmd }) => {
1159
1337
  console.log(cmd.renderHelp());
1160
1338
  process.exitCode = 0;
1161
1339
  });
@@ -1206,9 +1384,7 @@ var Command = class _Command {
1206
1384
  if (findOption(this, "version")) {
1207
1385
  return this;
1208
1386
  }
1209
- return this.addOption("-V, --version", {
1210
- description: "Display semver version"
1211
- }).addOptionHook("version", ({ cmd }) => {
1387
+ return this.addBuiltinOption("-V, --version", "Display semver version", ({ cmd }) => {
1212
1388
  console.log(getCommandAndAncestors(cmd).find((c) => c.version)?.version);
1213
1389
  process.exitCode = 0;
1214
1390
  });
@@ -1306,57 +1482,46 @@ var Command = class _Command {
1306
1482
  * adds command-line option with type inference. Parses format: `-s, --long [<value>|[value]|<value...>|[value...]]`
1307
1483
  */
1308
1484
  addOption(flags, opts = {}) {
1309
- const ins = {};
1310
- const { short, long, name, argName } = parseOptionFlags(flags);
1485
+ const ins = createOption(flags, opts);
1311
1486
  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;
1487
+ const builtin = builtinOptions.has(opt);
1488
+ if (opt.long === ins.long) {
1489
+ if (!builtin) {
1490
+ throw new Error(`Option long name, --${ins.long} already in use by: ${opt.flags}`);
1333
1491
  }
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);
1492
+ this.options = this.options.filter((o) => o !== opt);
1493
+ this.hooks = this.hooks.filter((h) => h.name !== opt.name);
1494
+ continue;
1344
1495
  }
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];
1496
+ if (opt.short === ins.short) {
1497
+ if (!builtin) {
1498
+ throw new Error(`Option short name, -${ins.short} already in use by: ${opt.flags}`);
1499
+ }
1500
+ const longOnly = {
1501
+ ...opt,
1502
+ short: void 0,
1503
+ flags: `--${opt.long}`
1504
+ };
1505
+ builtinOptions.add(longOnly);
1506
+ this.options = this.options.map((o) => o === opt ? longOnly : o);
1355
1507
  }
1356
1508
  }
1357
1509
  this.options.push(ins);
1358
1510
  return this;
1359
1511
  }
1512
+ /** adds a built-in option with its hook; it goes without its short flag when an option already has that */
1513
+ addBuiltinOption(flags, description, action) {
1514
+ const ins = createOption(flags, {
1515
+ description
1516
+ });
1517
+ if (this.options.some((o) => o.short === ins.short)) {
1518
+ ins.short = void 0;
1519
+ ins.flags = `--${ins.long}`;
1520
+ }
1521
+ builtinOptions.add(ins);
1522
+ this.options.push(ins);
1523
+ return this.addOptionHook(ins.name, action);
1524
+ }
1360
1525
  /**
1361
1526
  * register an action to be invoked when an option is set to true or string value.
1362
1527
  *
@@ -1366,6 +1531,9 @@ var Command = class _Command {
1366
1531
  */
1367
1532
  addOptionHook(optionName, action) {
1368
1533
  const def = findOption(this, optionName);
1534
+ if (!def) {
1535
+ throw new Error(`Cannot add a hook for option "${String(optionName)}": ${this.name} has no such option`);
1536
+ }
1369
1537
  if (!def.group && /process\.exitCode ?= ?.+;?\s*}$/.test(action.toString())) {
1370
1538
  def.group = "Command Options";
1371
1539
  }
@@ -1378,20 +1546,24 @@ var Command = class _Command {
1378
1546
  }
1379
1547
  /** parses command-line arguments with subcommand support and type-safe validation. */
1380
1548
  parseArgv(argv = process.argv.slice(2)) {
1381
- const sub = findCommand(this, argv[0]);
1382
- if (sub) {
1383
- return sub.parseArgv(argv.slice(1));
1549
+ const subIndex = findSubcommandIndex(this, argv);
1550
+ if (subIndex !== -1) {
1551
+ const sub = findCommand(this, argv[subIndex]);
1552
+ return sub.parseArgv(argv.filter((_, i) => i !== subIndex));
1384
1553
  }
1385
1554
  argv = normalizeArgv(argv, this.options);
1555
+ const checked = checkOptionValues(argv, this.options);
1386
1556
  const parsed = util.parseArgs({
1387
- args: argv,
1557
+ args: checked.argv,
1388
1558
  options: Object.fromEntries(this.options.map((o) => [
1389
1559
  o.name,
1390
1560
  {
1391
1561
  type: o.type,
1392
- short: o.short,
1393
1562
  default: o.defaultValue,
1394
- multiple: !!o.variadic
1563
+ multiple: !!o.variadic,
1564
+ ...o.short ? {
1565
+ short: o.short
1566
+ } : {}
1395
1567
  }
1396
1568
  ])),
1397
1569
  allowPositionals: true,
@@ -1404,7 +1576,18 @@ var Command = class _Command {
1404
1576
  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
1577
  const args = resolveArguments(parsed.positionals, this.arguments);
1406
1578
  const opts = filterObject(parsed.values, (value) => value !== void 0);
1407
- const errors = validateParsed(args, parsed.values, this.arguments, this.options);
1579
+ const rawNames = Object.fromEntries(parsed.tokens.flatMap((t) => t.kind === "option" ? [
1580
+ [
1581
+ t.name,
1582
+ t.rawName
1583
+ ]
1584
+ ] : []));
1585
+ const unexpected = this.arguments.some((a) => a.variadic) ? [] : parsed.positionals.slice(this.arguments.length);
1586
+ const errorList = checked.errors.concat(validateParsed(args, parsed.values, this.arguments, this.options, rawNames, checked.invalid) ?? []).concat(
1587
+ // a command with subcommands has no arguments of its own: the words after an unknown name were meant for it
1588
+ Object.keys(this.commands).length ? unexpected.slice(0, 1).map((word) => `Unknown command \`${word}\``) : unexpected.map((word) => `Unexpected argument \`${word}\``)
1589
+ );
1590
+ const errors = errorList.length ? errorList : void 0;
1408
1591
  const path = getCommandAncestors(this).map((c) => c.name);
1409
1592
  const data = {
1410
1593
  path,
@@ -1416,37 +1599,42 @@ var Command = class _Command {
1416
1599
  cmd: this
1417
1600
  };
1418
1601
  const hooks = this.hooks.filter((t) => t.predicate(data));
1419
- const execute = /* @__PURE__ */ __name(async () => {
1602
+ const execute = /* @__PURE__ */ __name(async () => await timer([
1603
+ [
1604
+ ...path,
1605
+ this.name
1606
+ ].join(" "),
1607
+ this.summary || this.description
1608
+ ], async (logger) => {
1420
1609
  for (const hook of hooks) {
1421
- await hook.action(data);
1610
+ await hook.action({
1611
+ ...data,
1612
+ get logger() {
1613
+ return logger;
1614
+ }
1615
+ });
1422
1616
  if (process.exitCode !== void 0) {
1423
1617
  return;
1424
1618
  }
1425
1619
  }
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");
1620
+ if (errors) {
1621
+ errors.forEach((msg) => logger.error(C__default.default.red(msg)));
1622
+ process.exitCode = 1;
1623
+ return;
1624
+ }
1625
+ if (this.action) {
1626
+ return await this.action(...args, opts, {
1627
+ ...data,
1628
+ args,
1629
+ opts,
1630
+ cmd: this,
1631
+ get logger() {
1632
+ return logger;
1633
+ }
1634
+ });
1635
+ }
1636
+ console.log(this.renderHelp());
1637
+ }), "execute");
1450
1638
  return {
1451
1639
  ...data,
1452
1640
  hooks,
@@ -1455,11 +1643,13 @@ var Command = class _Command {
1455
1643
  }
1456
1644
  /**
1457
1645
  * 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.
1646
+ * The handler receives parsed arguments and options with correct typings. It may return a value (or a promise of one):
1647
+ * `execute()` of the parse result gives it back, typed.
1459
1648
  */
1460
1649
  setAction(fn) {
1461
- this.action = setName(this.name, fn);
1462
- return this;
1650
+ const typed = this;
1651
+ typed.action = setName(this.name, fn);
1652
+ return typed;
1463
1653
  }
1464
1654
  /** returns a new Command instance. Override this method in subclasses. */
1465
1655
  createSubcommand(name) {