@gunshi/bone 1.0.0-rc.1 → 1.0.0-rc.3

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.d.ts CHANGED
@@ -1034,7 +1034,8 @@ interface CommandEnvironment<G extends GunshiParamsConstraint = DefaultGunshiPar
1034
1034
  * The entry command of the CLI, marked with `entry: true`.
1035
1035
  *
1036
1036
  * It is available whether or not the CLI has sub-commands, while {@linkcode CommandEnvironment.subCommands}
1037
- * includes the entry command only when the sub-commands are given with {@linkcode CliOptions.subCommands}.
1037
+ * includes the entry command only when the CLI has sub-commands, given with {@linkcode CliOptions.subCommands}
1038
+ * or with {@linkcode Command.subCommands} of the entry command.
1038
1039
  * It is not frozen, like the commands in {@linkcode CommandEnvironment.subCommands}.
1039
1040
  */
1040
1041
  entryCommand?: Command<any> | LazyCommand<any>;
@@ -1109,8 +1110,11 @@ interface CliOptions<G extends GunshiParamsConstraint = DefaultGunshiParams> {
1109
1110
  version?: string;
1110
1111
  /**
1111
1112
  * Sub commands.
1113
+ *
1114
+ * An object or a Map keyed by the sub-command names, or an array of commands, which are keyed by their names.
1115
+ * When this is not given, the {@linkcode Command.subCommands} of the entry command are the sub-commands.
1112
1116
  */
1113
- subCommands?: Record<string, SubCommandable> | Map<string, SubCommandable>;
1117
+ subCommands?: Record<string, SubCommandable> | Map<string, SubCommandable> | readonly SubCommandable[];
1114
1118
  /**
1115
1119
  * Left margin of the command output.
1116
1120
  */
@@ -1134,6 +1138,9 @@ interface CliOptions<G extends GunshiParamsConstraint = DefaultGunshiParams> {
1134
1138
  * Output that must still appear — machine-readable results for an agent, warnings for the
1135
1139
  * CLI author — should use `console.log` / `console.warn`, not `ctx.log`.
1136
1140
  *
1141
+ * The validation errors are not printed either, so `cli()` rejects with them, for the caller to
1142
+ * report them (see {@linkcode CliOptions.renderValidationErrors}).
1143
+ *
1137
1144
  * @default false
1138
1145
  */
1139
1146
  usageSilent?: boolean;
@@ -1157,6 +1164,12 @@ interface CliOptions<G extends GunshiParamsConstraint = DefaultGunshiParams> {
1157
1164
  renderHeader?: ((ctx: Readonly<CommandContext<G>>) => Promise<string>) | null;
1158
1165
  /**
1159
1166
  * Render function the validation errors.
1167
+ *
1168
+ * With the global options plugin, the rendered message is printed to stderr, the exit code is set
1169
+ * to `1`, {@linkcode CliOptions.onErrorCommand} is called, and `cli()` resolves with `undefined`.
1170
+ * Set it to `null` to report the validation errors yourself: nothing is printed, and `cli()` rejects
1171
+ * with the `AggregateError`. A renderer that returns an empty message, and
1172
+ * {@linkcode CliOptions.usageSilent}, also leave them to the caller.
1160
1173
  */
1161
1174
  renderValidationErrors?: ((ctx: Readonly<CommandContext<G>>, error: AggregateError) => Promise<string>) | null;
1162
1175
  /**
@@ -1188,10 +1201,14 @@ interface CliOptions<G extends GunshiParamsConstraint = DefaultGunshiParams> {
1188
1201
  */
1189
1202
  onAfterCommand?: (ctx: Readonly<CommandContext<G>>, result: string | undefined) => Awaitable<void>;
1190
1203
  /**
1191
- * Hook that runs when a command throws an error
1204
+ * Hook that runs when a command throws an error, or when the arguments fail validation
1205
+ *
1206
+ * For the validation errors that the global options plugin has printed, the exit code is already `1`
1207
+ * when the hook runs, so the hook can set another one, and `cli()` resolves after it. Any other
1208
+ * error rejects `cli()` after the hook.
1192
1209
  *
1193
1210
  * @param ctx - The command context
1194
- * @param error - The error thrown during execution
1211
+ * @param error - The error thrown during execution, or the `AggregateError` of the validation errors
1195
1212
  * @since v0.27.0
1196
1213
  */
1197
1214
  onErrorCommand?: (ctx: Readonly<CommandContext<G>>, error: Error) => Awaitable<void>;
@@ -1360,9 +1377,11 @@ interface RenderingOptions<G extends GunshiParamsConstraint = DefaultGunshiParam
1360
1377
  usage?: ((ctx: Readonly<CommandContext<G>>) => Promise<string>) | null;
1361
1378
  /**
1362
1379
  * Validation errors rendering configuration
1363
- * - `null`: Disable rendering
1380
+ * - `null`: Disable rendering. `cli()` rejects with the validation errors, for the caller to report them
1364
1381
  * - `function`: Use custom renderer
1365
1382
  * - `undefined` (when omitted): Use default renderer
1383
+ *
1384
+ * See {@linkcode CliOptions.renderValidationErrors} for where the rendered message goes.
1366
1385
  */
1367
1386
  validationErrors?: ((ctx: Readonly<CommandContext<G>>, error: AggregateError) => Promise<string>) | null;
1368
1387
  }
@@ -1427,10 +1446,13 @@ interface Command<G extends GunshiParamsConstraint = DefaultGunshiParams> {
1427
1446
  *
1428
1447
  * Allows building command trees like `git remote add`.
1429
1448
  * Each key is the sub-command name, and the value is a command or lazy command.
1449
+ * An array of commands is keyed by the names of the commands.
1450
+ *
1451
+ * On the entry command, these are the top-level sub-commands when {@linkcode CliOptions.subCommands} is not given.
1430
1452
  *
1431
1453
  * @since v0.28.0
1432
1454
  */
1433
- subCommands?: Record<string, SubCommandable> | Map<string, SubCommandable>;
1455
+ subCommands?: Record<string, SubCommandable> | Map<string, SubCommandable> | readonly SubCommandable[];
1434
1456
  }
1435
1457
  /**
1436
1458
  * Lazy command interface.
@@ -1513,7 +1535,7 @@ interface SubCommandable {
1513
1535
  * @see {@link Command.subCommands}
1514
1536
  * @since v0.28.0
1515
1537
  */
1516
- subCommands?: Record<string, any> | Map<string, any>;
1538
+ subCommands?: Record<string, any> | Map<string, any> | readonly any[];
1517
1539
  /**
1518
1540
  * Index signature to allow additional properties
1519
1541
  */
package/lib/index.js CHANGED
@@ -1264,13 +1264,27 @@ function log(...args) {
1264
1264
  /**
1265
1265
  * Get the sub-commands of a command as a normalized Map.
1266
1266
  *
1267
+ * An array of sub-commands is keyed by the names of the commands (`commandName` for a lazy command).
1268
+ *
1267
1269
  * @param cmd - A command or lazy command
1268
1270
  * @returns A Map of sub-commands, or undefined if the command has no sub-commands.
1271
+ * @throws {TypeError} If a command in an array has no name, or two commands in an array have the same name.
1269
1272
  */
1270
1273
  function getCommandSubCommands(cmd) {
1271
1274
  const subCommands = isLazyCommand(cmd) ? cmd.subCommands : typeof cmd === "object" ? cmd.subCommands : void 0;
1272
1275
  if (!subCommands) return;
1273
1276
  if (subCommands instanceof Map) return subCommands.size > 0 ? subCommands : void 0;
1277
+ if (Array.isArray(subCommands)) {
1278
+ if (subCommands.length === 0) return;
1279
+ const map = /* @__PURE__ */ new Map();
1280
+ for (const sub of subCommands) {
1281
+ const name = isLazyCommand(sub) ? sub.commandName : sub?.name;
1282
+ if (typeof name !== "string" || name === "") throw new TypeError(`Sub-command name must be a non-empty string in an array of 'subCommands'`);
1283
+ if (map.has(name)) throw new TypeError(`Sub-command '${name}' is given twice in an array of 'subCommands'`);
1284
+ map.set(name, sub);
1285
+ }
1286
+ return map;
1287
+ }
1274
1288
  if (typeof subCommands === "object") {
1275
1289
  const entries = Object.entries(subCommands);
1276
1290
  if (entries.length === 0) return;
@@ -1892,7 +1906,7 @@ async function cliCore(argv, entry, options, plugins, usageOnly = false) {
1892
1906
  skipPositional
1893
1907
  });
1894
1908
  const validationError = mergeValidationErrors(error, [...additionalValidationErrors, ...cliOptions.strict && !diagnostic ? createUnknownOptionErrors(findUnknownOptions(args, tokens, { toKebab: resolvedCommand.toKebab })) : []]);
1895
- return await executeCommand(resolvedCommand, await createCommandContext({
1909
+ const commandContext = await createCommandContext({
1896
1910
  args,
1897
1911
  explicit,
1898
1912
  values,
@@ -1907,7 +1921,41 @@ async function cliCore(argv, entry, options, plugins, usageOnly = false) {
1907
1921
  extensions: getPluginExtensions(resolvedPlugins),
1908
1922
  validationError,
1909
1923
  cliOptions
1910
- }), decorators.commandDecorators);
1924
+ });
1925
+ const reported = trackReported(commandContext);
1926
+ try {
1927
+ return await executeCommand(resolvedCommand, commandContext, decorators.commandDecorators);
1928
+ } catch (error) {
1929
+ /**
1930
+ * NOTE(kazupon): a plugin that has reported the validation errors to the user marks them, as the
1931
+ * global options plugin does after it prints them to stderr and sets the exit code. They have been
1932
+ * dealt with, and `onErrorCommand` has seen them in `executeCommand`, so `cli()` ends without
1933
+ * rejecting. Errors that nobody reported, such as when the app renders the validation errors itself
1934
+ * or an error thrown by a command, reject as before.
1935
+ */
1936
+ if (error != null && typeof error === "object" && reported.has(error)) return;
1937
+ throw error;
1938
+ }
1939
+ }
1940
+ /**
1941
+ * The key of the registry that maps the command context of a run to the set of the errors that a plugin
1942
+ * has reported to the user during the run. The global options plugin uses the same registered symbol,
1943
+ * since `gunshi` and the plugins bundle their own copies.
1944
+ */
1945
+ const REPORTED = Symbol.for("gunshi.reported");
1946
+ /**
1947
+ * Prepare the set of the errors that a plugin reports to the user during a run. The set belongs to the
1948
+ * command context of the run, so a report counts for this run only: not for a nested `cli()` in a hook,
1949
+ * nor for a later run in which the same error is thrown again.
1950
+ *
1951
+ * @param ctx - The command context of the run
1952
+ * @returns The set of the errors that have been reported during the run
1953
+ */
1954
+ function trackReported(ctx) {
1955
+ const registry = globalThis;
1956
+ const reported = /* @__PURE__ */ new WeakSet();
1957
+ (registry[REPORTED] ??= /* @__PURE__ */ new WeakMap()).set(ctx, reported);
1958
+ return reported;
1911
1959
  }
1912
1960
  /**
1913
1961
  * Create the decorator that renders the usage of the command instead of running it.
@@ -2042,7 +2090,6 @@ function mergeValidationErrors(error, additionalErrors) {
2042
2090
  if (additionalErrors.length === 0) return error;
2043
2091
  return new AggregateError(error ? [...error.errors, ...additionalErrors] : additionalErrors, error?.message || additionalErrors[0]?.message);
2044
2092
  }
2045
- const isObject = (val) => val !== null && typeof val === "object";
2046
2093
  /**
2047
2094
  * Create the entry command that sub-commands and plugins can see.
2048
2095
  * The user-provided entry is copied, so that marking it with `entry: true` does not mutate it.
@@ -2060,10 +2107,13 @@ function createEntryCommand(entryCmd) {
2060
2107
  };
2061
2108
  }
2062
2109
  function createInitialSubCommands(options, entryCommand) {
2063
- const hasSubCommands = options.subCommands ? options.subCommands instanceof Map ? options.subCommands.size > 0 : isObject(options.subCommands) && Object.keys(options.subCommands).length > 0 : false;
2064
- const subCommands = new Map(options.subCommands instanceof Map ? options.subCommands : []);
2065
- if (!(options.subCommands instanceof Map) && isObject(options.subCommands)) for (const [name, cmd] of Object.entries(options.subCommands)) subCommands.set(name, cmd);
2066
- if (hasSubCommands && entryCommand) subCommands.set(resolveEntryName(entryCommand), entryCommand);
2110
+ const subCommands = new Map(getCommandSubCommands({ subCommands: options.subCommands }) ?? []);
2111
+ /**
2112
+ * NOTE(kazupon): `subCommands` works for any command definition, the entry included.
2113
+ * Without sub-commands in the options, the sub-commands of the entry are the top-level ones.
2114
+ */
2115
+ if (!(subCommands.size > 0) && entryCommand) for (const [name, cmd] of getCommandSubCommands(entryCommand) ?? []) subCommands.set(name, cmd);
2116
+ if (subCommands.size > 0 && entryCommand) subCommands.set(resolveEntryName(entryCommand), entryCommand);
2067
2117
  return subCommands;
2068
2118
  }
2069
2119
  function normalizeCliOptions(options, decorators, pluginContext, entryCommand) {
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@gunshi/bone",
3
3
  "description": "gunshi minimum",
4
- "version": "1.0.0-rc.1",
4
+ "version": "1.0.0-rc.3",
5
5
  "author": {
6
6
  "name": "kazuya kawaguchi",
7
7
  "email": "kawakazu80@gmail.com"
@@ -51,11 +51,11 @@
51
51
  }
52
52
  },
53
53
  "devDependencies": {
54
- "@gunshi/definition": "1.0.0-rc.1",
55
- "@gunshi/plugin-global": "1.0.0-rc.1",
56
- "@gunshi/plugin-renderer": "1.0.0-rc.1",
54
+ "@gunshi/definition": "1.0.0-rc.3",
55
+ "@gunshi/plugin-global": "1.0.0-rc.3",
56
+ "@gunshi/plugin-renderer": "1.0.0-rc.3",
57
57
  "deno": "^2.7.14",
58
- "gunshi": "1.0.0-rc.1",
58
+ "gunshi": "1.0.0-rc.3",
59
59
  "jsr": "^0.14.3",
60
60
  "jsr-exports-lint": "^0.4.2",
61
61
  "publint": "^0.3.20",