@gunshi/bone 0.37.3 → 1.0.0-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/lib/index.d.ts +217 -47
  2. package/lib/index.js +929 -138
  3. package/package.json +5 -5
package/lib/index.js CHANGED
@@ -1,4 +1,4 @@
1
- //#region ../../node_modules/.pnpm/args-tokens@0.29.0/node_modules/args-tokens/lib/parser.js
1
+ //#region ../../node_modules/.pnpm/args-tokens@1.0.0-beta.1/node_modules/args-tokens/lib/parser.js
2
2
  /**
3
3
  * forked from `nodejs/node` (`pkgjs/parseargs`)
4
4
  * repository url: https://github.com/nodejs/node (https://github.com/pkgjs/parseargs)
@@ -38,11 +38,11 @@ function parseArgs(args, options = {}) {
38
38
  const remainings = [...args];
39
39
  let index = -1;
40
40
  let groupCount = 0;
41
- let hasShortValueSeparator = false;
41
+ let hasShortGroupValue = false;
42
+ let shortGroupValueInline = true;
42
43
  while (remainings.length > 0) {
43
44
  const arg = remainings.shift();
44
45
  if (arg == void 0) break;
45
- const nextArg = remainings[0];
46
46
  if (groupCount > 0) groupCount--;
47
47
  else index++;
48
48
  if (arg === TERMINATOR) {
@@ -73,12 +73,10 @@ function parseArgs(args, options = {}) {
73
73
  value,
74
74
  inlineValue
75
75
  });
76
- if (groupCount === 1 && hasOptionValue(nextArg)) {
76
+ if (groupCount === 1 && hasShortGroupValue) {
77
77
  value = remainings.shift();
78
- if (hasShortValueSeparator) {
79
- inlineValue = true;
80
- hasShortValueSeparator = false;
81
- }
78
+ inlineValue = shortGroupValueInline;
79
+ hasShortGroupValue = false;
82
80
  tokens.push({
83
81
  kind: "option",
84
82
  index,
@@ -99,14 +97,22 @@ function parseArgs(args, options = {}) {
99
97
  }
100
98
  if (isShortOptionGroup(arg)) {
101
99
  const expanded = [];
100
+ let separated = false;
101
+ let dashed = false;
102
102
  let shortValue = "";
103
103
  for (let i = 1; i < arg.length; i++) {
104
104
  const shortableOption = arg.charAt(i);
105
- if (hasShortValueSeparator) shortValue += shortableOption;
106
- else if (!allowCompatible && shortableOption.codePointAt(0) === EQUAL_CODE) hasShortValueSeparator = true;
107
- else expanded.push(`${SHORT_OPTION_PREFIX}${shortableOption}`);
105
+ if (separated) shortValue += shortableOption;
106
+ else if (!allowCompatible && shortableOption.codePointAt(0) === EQUAL_CODE && expanded.length > 0) separated = true;
107
+ else if (!allowCompatible && shortableOption.codePointAt(0) === HYPHEN_CODE) {
108
+ separated = true;
109
+ dashed = true;
110
+ shortValue += shortableOption;
111
+ } else expanded.push(`${SHORT_OPTION_PREFIX}${shortableOption}`);
108
112
  }
109
- if (shortValue) expanded.push(shortValue);
113
+ hasShortGroupValue = separated;
114
+ shortGroupValueInline = !dashed;
115
+ if (separated) expanded.push(shortValue);
110
116
  remainings.unshift(...expanded);
111
117
  groupCount = expanded.length;
112
118
  continue;
@@ -185,25 +191,17 @@ function isLongOptionAndValue(arg) {
185
191
  return hasLongOptionPrefix(arg) && arg.includes(EQUAL_CHAR, 3);
186
192
  }
187
193
  /**
188
- * Check if `arg` is a long option prefix (e.g. `--`).
194
+ * Check if `arg` starts with the long option prefix `--` and has more after it, such as `--foo`.
195
+ * The option terminator `--` alone does not.
189
196
  *
190
197
  * @param arg - An argument to check
191
- * @returns Whether `arg` is a long option prefix.
198
+ * @returns Whether `arg` has the long option prefix and more after it.
192
199
  */
193
200
  function hasLongOptionPrefix(arg) {
194
201
  return arg.startsWith(LONG_OPTION_PREFIX) && arg.length > 2;
195
202
  }
196
- /**
197
- * Check if a `value` is an option value.
198
- *
199
- * @param value - A value to check
200
- * @returns Whether a `value` is an option value.
201
- */
202
- function hasOptionValue(value) {
203
- return !(value == null) && value.codePointAt(0) !== HYPHEN_CODE;
204
- }
205
203
  //#endregion
206
- //#region ../../node_modules/.pnpm/args-tokens@0.29.0/node_modules/args-tokens/lib/utils.js
204
+ //#region ../../node_modules/.pnpm/args-tokens@1.0.0-beta.1/node_modules/args-tokens/lib/utils.js
207
205
  /**
208
206
  * Entry point of utils.
209
207
  *
@@ -234,7 +232,27 @@ function formatChoices(choices) {
234
232
  return choices.map((value) => JSON.stringify(value)).join(", ");
235
233
  }
236
234
  //#endregion
237
- //#region ../../node_modules/.pnpm/args-tokens@0.29.0/node_modules/args-tokens/lib/resolver.js
235
+ //#region ../../node_modules/.pnpm/args-tokens@1.0.0-beta.1/node_modules/args-tokens/lib/resolver-CAlgxe_R.js
236
+ /**
237
+ * Internal definitions shared by the modules of `args-tokens`.
238
+ *
239
+ * This module is not an entry point: it is not in the `exports` of `package.json` and `jsr.json`,
240
+ * so what it exports is not part of the public API.
241
+ */
242
+ /**
243
+ * @author kazuya kawaguchi (a.k.a. kazupon)
244
+ * @license MIT
245
+ */
246
+ /**
247
+ * Brand of a `parse` function that has no side effects, set by `string()`, `number()`,
248
+ * `integer()`, `float()`, `choice()` and `positional()` without a parser, so that the resolver may
249
+ * call it with a value that the option was not given, to check the value before suggesting it.
250
+ *
251
+ * The brand is looked up in the global symbol registry with `Symbol.for`, so it stays identical
252
+ * across bundled copies of `args-tokens`, where the resolver and the combinators may come from
253
+ * different copies.
254
+ */
255
+ const PURE_PARSE = Symbol.for("args-tokens.pureParse");
238
256
  /**
239
257
  * Entry point of argument options resolver.
240
258
  *
@@ -249,6 +267,10 @@ function formatChoices(choices) {
249
267
  *
250
268
  * Each code identifies a validation failure category and is also suitable as an
251
269
  * i18n resource key for localized rendering.
270
+ *
271
+ * {@link resolveArgs} and `parse()` do not report `unknownOption`. An option that is not in the
272
+ * schema takes the argument after it as its value, unless that argument is an option, and the value
273
+ * is dropped: with no `foo` in the schema, `--foo bar` gives no positional argument.
252
274
  */
253
275
  const ArgsValidationErrorKeys = {
254
276
  requiredOption: "err:arg:required-option",
@@ -256,7 +278,11 @@ const ArgsValidationErrorKeys = {
256
278
  invalidType: "err:arg:invalid-type",
257
279
  invalidChoice: "err:arg:invalid-choice",
258
280
  customParse: "err:arg:custom-parse",
259
- unknownOption: "err:arg:unknown-option"
281
+ unknownOption: "err:arg:unknown-option",
282
+ unexpectedValue: "err:arg:unexpected-value",
283
+ missingValue: "err:arg:missing-value",
284
+ conflict: "err:arg:conflict",
285
+ invalidDefault: "err:arg:invalid-default"
260
286
  };
261
287
  /**
262
288
  * Brand that marks {@link ArgsValidationError} instances.
@@ -331,6 +357,14 @@ function isArgsValidationError$1(error) {
331
357
  return typeof values === "object" && values !== null;
332
358
  }
333
359
  const SKIP_POSITIONAL_DEFAULT = -1;
360
+ const ARG_TYPES = /* @__PURE__ */ new Set([
361
+ "string",
362
+ "boolean",
363
+ "number",
364
+ "enum",
365
+ "positional",
366
+ "custom"
367
+ ]);
334
368
  /**
335
369
  * Resolve command line arguments.
336
370
  *
@@ -377,12 +411,13 @@ function resolveArgs(args, tokens, { shortGrouping = false, skipPositional = SKI
377
411
  }
378
412
  function checkLongTokenName(option, schema, token) {
379
413
  if (token.rawName == void 0 || !hasLongOptionPrefix(token.rawName)) return false;
380
- return token.name === option || schema.type === "boolean" && schema.negatable === true && token.name === `no-${option}`;
414
+ return token.name === option || isNegatedToken(token, option, schema);
381
415
  }
382
416
  function toShortValue() {
383
417
  if (expandableShortOptions.length === 0) return;
384
418
  else {
385
- const value = expandableShortOptions.map((token) => token.name).join("");
419
+ let value = "";
420
+ for (let i = 0; i < expandableShortOptions.length; i++) value += expandableShortOptions[i].name ?? "";
386
421
  expandableShortOptions.length = 0;
387
422
  return value;
388
423
  }
@@ -396,7 +431,7 @@ function resolveArgs(args, tokens, { shortGrouping = false, skipPositional = SKI
396
431
  }
397
432
  function applyShortOptionValue(value) {
398
433
  if (currentShortOption) {
399
- currentShortOption.value = value || toShortValue();
434
+ currentShortOption.value = value ?? toShortValue();
400
435
  optionTokens.push({ ...currentShortOption });
401
436
  currentShortOption = void 0;
402
437
  }
@@ -407,7 +442,15 @@ function resolveArgs(args, tokens, { shortGrouping = false, skipPositional = SKI
407
442
  */
408
443
  const schemas = Object.values(args);
409
444
  const booleanLongOptionNames = /* @__PURE__ */ new Set();
410
- for (const [rawArg, schema] of Object.entries(args)) {
445
+ for (let i = 0; i < argEntries.length; i++) {
446
+ const entry = argEntries[i];
447
+ const rawArg = entry[0];
448
+ const schema = entry[1];
449
+ if (typeof schema.parse !== "function") {
450
+ if (schema.type === "custom") throw new TypeError(`argument '${getOptionName(rawArg, schema)}' should have a 'parse' function`);
451
+ if (schema.type === "enum" && !Array.isArray(schema.choices)) throw new TypeError(`argument '${getOptionName(rawArg, schema)}' should have a 'choices' array`);
452
+ if (!ARG_TYPES.has(schema.type)) throw new Error(`Unsupported argument type '${schema.type}' for option '${getOptionName(rawArg, schema)}'`);
453
+ }
411
454
  if (schema.type !== "boolean") continue;
412
455
  const arg = toKebab || schema.toKebab ? kebabnize(rawArg) : rawArg;
413
456
  booleanLongOptionNames.add(arg);
@@ -417,12 +460,12 @@ function resolveArgs(args, tokens, { shortGrouping = false, skipPositional = SKI
417
460
  for (let i = 0; i < tokens.length; i++) {
418
461
  const token = tokens[i];
419
462
  if (token.kind === "positional") {
420
- if (terminated && token.value) {
463
+ if (terminated) {
421
464
  rest.push(token.value);
422
465
  continue;
423
466
  }
424
467
  if (currentShortOption) {
425
- if (schemas.find((schema) => schema.short === currentShortOption.name && schema.type === "boolean")) {
468
+ if (schemas.find((schema) => schema.short === currentShortOption.name && schema.type === "boolean") || expandableShortOptions.length > 0) {
426
469
  positionalTokens.push({ ...token });
427
470
  applyShortOptionValue();
428
471
  } else applyShortOptionValue(token.value);
@@ -434,11 +477,11 @@ function resolveArgs(args, tokens, { shortGrouping = false, skipPositional = SKI
434
477
  } else positionalTokens.push({ ...token });
435
478
  } else if (token.kind === "option") {
436
479
  if (token.rawName) {
437
- if (hasLongOptionPrefix(token.rawName)) {
480
+ if (token.rawName.startsWith("--")) {
438
481
  applyLongOptionValue();
482
+ applyShortOptionValue();
439
483
  if (token.inlineValue) optionTokens.push({ ...token });
440
484
  else currentLongOption = { ...token };
441
- applyShortOptionValue();
442
485
  } else if (isShortOption(token.rawName)) {
443
486
  if (currentShortOption) {
444
487
  if (currentShortOption.index === token.index) {
@@ -459,8 +502,10 @@ function resolveArgs(args, tokens, { shortGrouping = false, skipPositional = SKI
459
502
  }
460
503
  }
461
504
  } else {
462
- if (currentShortOption && currentShortOption.index == token.index && token.inlineValue) {
463
- currentShortOption.value = token.value;
505
+ if (currentShortOption && currentShortOption.index == token.index) {
506
+ const letters = toShortValue();
507
+ currentShortOption.value = letters === void 0 ? token.value : `${letters}${token.inlineValue ? "=" : ""}${token.value ?? ""}`;
508
+ currentShortOption.inlineValue = token.inlineValue;
464
509
  optionTokens.push({ ...currentShortOption });
465
510
  currentShortOption = void 0;
466
511
  }
@@ -494,36 +539,37 @@ function resolveArgs(args, tokens, { shortGrouping = false, skipPositional = SKI
494
539
  return requiredPositionalsAfter[rawArg] ?? 0;
495
540
  }
496
541
  let positionalsCount = 0;
497
- for (const [rawArg, schema] of argEntries) {
542
+ for (let argIndex = 0; argIndex < argEntries.length; argIndex++) {
543
+ const entry = argEntries[argIndex];
544
+ const rawArg = entry[0];
545
+ const schema = entry[1];
498
546
  const arg = getOptionName(rawArg, schema);
499
547
  explicit[rawArg] = false;
500
548
  if (schema.type === "positional") {
501
549
  if (skipPositionalIndex > SKIP_POSITIONAL_DEFAULT) while (positionalsCount <= getPositionalSkipIndex()) positionalsCount++;
502
550
  if (schema.multiple) {
503
551
  const availablePositionals = Math.max(positionalTokens.length - positionalsCount, 0);
504
- if (availablePositionals > 0) {
505
- const requiredPositionals = getRequiredPositionalsAfter(rawArg);
506
- const positionalsToConsume = Math.max(availablePositionals - requiredPositionals, 0);
507
- if (positionalsToConsume > 0) {
508
- const endPositionals = positionalsCount + positionalsToConsume;
509
- if (typeof schema.parse === "function") {
510
- const parsed = [];
511
- for (let i = positionalsCount; i < endPositionals; i++) {
512
- const p = positionalTokens[i];
513
- const [parsedValue, error] = parseSchemaValue(p.value, rawArg, arg, schema);
514
- if (error) errors.push(error);
515
- else parsed.push(parsedValue);
516
- }
517
- values[rawArg] = parsed;
518
- } else {
519
- const valuesArray = [];
520
- for (let i = positionalsCount; i < endPositionals; i++) valuesArray.push(positionalTokens[i].value);
521
- values[rawArg] = valuesArray;
552
+ const positionalsToConsume = availablePositionals > 0 ? Math.max(availablePositionals - getRequiredPositionalsAfter(rawArg), 0) : 0;
553
+ if (positionalsToConsume > 0) {
554
+ const endPositionals = positionalsCount + positionalsToConsume;
555
+ if (typeof schema.parse === "function") {
556
+ const parsed = [];
557
+ for (let i = positionalsCount; i < endPositionals; i++) {
558
+ const p = positionalTokens[i];
559
+ const [parsedValue, error] = parseSchemaValue(p.value, rawArg, arg, schema);
560
+ if (error) errors.push(error);
561
+ else parsed.push(parsedValue);
522
562
  }
523
- positionalsCount = endPositionals;
524
- explicit[rawArg] = true;
525
- } else if (schema.required) errors.push(createRequireError(rawArg, arg, schema));
563
+ values[rawArg] = parsed;
564
+ } else {
565
+ const valuesArray = [];
566
+ for (let i = positionalsCount; i < endPositionals; i++) valuesArray.push(positionalTokens[i].value);
567
+ values[rawArg] = valuesArray;
568
+ }
569
+ positionalsCount = endPositionals;
570
+ explicit[rawArg] = true;
526
571
  } else if (schema.required) errors.push(createRequireError(rawArg, arg, schema));
572
+ else if (hasDefault(schema)) values[rawArg] = getDefaultValue(schema);
527
573
  } else {
528
574
  const positional = positionalTokens[positionalsCount];
529
575
  if (shouldRequireMissingSinglePositional(schema)) {
@@ -555,27 +601,37 @@ function resolveArgs(args, tokens, { shortGrouping = false, skipPositional = SKI
555
601
  continue;
556
602
  }
557
603
  }
604
+ let resolved = false;
558
605
  for (let i = 0; i < optionTokens.length; i++) {
559
606
  const token = optionTokens[i];
560
607
  if (checkLongTokenName(arg, schema, token) || schema.short === token.name && token.rawName != void 0 && isShortOption(token.rawName)) {
561
- const invalid = validateRequire(token, rawArg, arg, schema);
562
- if (invalid) {
563
- errors.push(invalid);
564
- continue;
565
- }
566
608
  explicit[rawArg] = true;
567
609
  const rawName = token.rawName;
568
610
  const actualInputName = isShortOption(rawName) ? `-${token.name}` : rawName;
569
611
  actualInputNames.set(rawArg, actualInputName);
570
- const [parsedValue, error] = parse(token, rawArg, arg, schema);
612
+ const missing = schema.type !== "boolean" && token.value === void 0;
613
+ if (!missing) {
614
+ const invalid = validateRequire(token, rawArg, arg, schema);
615
+ if (invalid) {
616
+ errors.push(invalid);
617
+ continue;
618
+ }
619
+ }
620
+ const [parsedValue, error] = missing ? [void 0, createMissingValueError(rawArg, arg, schema, findOptionLikeNextArgument(tokens, optionTokens, i, argEntries, toKebab))] : parse(token, rawArg, arg, schema);
571
621
  if (error) errors.push(error);
572
- else if (schema.multiple) {
573
- values[rawArg] ||= [];
574
- values[rawArg].push(parsedValue);
575
- } else values[rawArg] = parsedValue;
622
+ else {
623
+ resolved = true;
624
+ if (schema.multiple) {
625
+ values[rawArg] ||= [];
626
+ values[rawArg].push(parsedValue);
627
+ } else values[rawArg] = parsedValue;
628
+ }
576
629
  }
577
630
  }
578
- if (values[rawArg] == null && schema.default != null) values[rawArg] = schema.default;
631
+ if (!resolved && schema.default != null) {
632
+ if (hasDefaultOutsideChoices(schema)) errors.push(createDefaultChoiceError(rawArg, arg, schema));
633
+ else values[rawArg] = getDefaultValue(schema);
634
+ }
579
635
  }
580
636
  const conflictErrors = checkConflicts(args, explicit, toKebab, actualInputNames);
581
637
  errors.push(...conflictErrors);
@@ -587,27 +643,73 @@ function resolveArgs(args, tokens, { shortGrouping = false, skipPositional = SKI
587
643
  explicit
588
644
  };
589
645
  }
646
+ /**
647
+ * Check whether an option token is the negated form (`--no-<option>`) of a negatable boolean option.
648
+ *
649
+ * The negated name is always `no-` followed by the full option name, so an option named
650
+ * `no-cache` is negated only by `--no-no-cache`, and `--no-cache` is the option itself.
651
+ *
652
+ * @param token - The option token
653
+ * @param option - The option name used on the command line (after `toKebab` conversion)
654
+ * @param schema - The argument schema
655
+ * @returns Whether the token negates the option.
656
+ */
657
+ function isNegatedToken(token, option, schema) {
658
+ return schema.type === "boolean" && schema.negatable === true && token.name === `no-${option}`;
659
+ }
660
+ /**
661
+ * Resolve the value of an option token that matches the schema.
662
+ *
663
+ * A token of a non-boolean option always has a value here: `resolveArgs()` reports an option
664
+ * given without a value before calling this function.
665
+ *
666
+ * @param token - The option token
667
+ * @param rawArg - The argument key in the schema
668
+ * @param option - The option name used on the command line
669
+ * @param schema - The argument schema
670
+ * @returns The resolved value, or a validation error
671
+ */
590
672
  function parse(token, rawArg, option, schema) {
673
+ if (schema.type === "enum" && schema.choices && !schema.choices.includes(token.value)) return [void 0, createChoiceError(rawArg, option, schema, token.value)];
591
674
  if (typeof schema.parse === "function") {
592
675
  if (schema.type === "boolean") {
593
- const boolValue = !(schema.negatable && token.name.startsWith("no-"));
676
+ const [boolValue, error] = resolveBooleanValue(token, rawArg, option, schema);
677
+ if (error) return [void 0, error];
594
678
  return parseSchemaValue(String(boolValue), rawArg, option, schema);
595
679
  }
596
- return parseSchemaValue(token.value ?? String(schema.default ?? ""), rawArg, option, schema);
680
+ return parseSchemaValue(token.value, rawArg, option, schema);
597
681
  }
598
682
  switch (schema.type) {
599
- case "string": return typeof token.value === "string" ? [token.value || schema.default, void 0] : [void 0, createTypeError(rawArg, option, schema, token.value)];
600
- case "boolean": return [!(schema.negatable && token.name.startsWith("no-")), void 0];
683
+ case "string": return typeof token.value === "string" ? [token.value, void 0] : [void 0, createTypeError(rawArg, option, schema, token.value)];
684
+ case "boolean": return resolveBooleanValue(token, rawArg, option, schema);
601
685
  case "number":
602
- if (!isNumeric(token.value)) return [void 0, createTypeError(rawArg, option, schema, token.value)];
603
- return token.value ? [+token.value, void 0] : [+(schema.default || ""), void 0];
604
- case "enum":
605
- if (schema.choices && !schema.choices.includes(token.value)) return [void 0, createChoiceError(rawArg, option, schema, token.value)];
606
- return [token.value || schema.default, void 0];
686
+ if (typeof token.value !== "string" || !isNumeric(token.value)) return [void 0, createTypeError(rawArg, option, schema, token.value)];
687
+ return [+token.value, void 0];
688
+ case "enum": return [token.value, void 0];
607
689
  case "custom": throw new TypeError(`argument '${option}' should have a 'parse' function`);
608
690
  default: throw new Error(`Unsupported argument type '${schema.type}' for option '${option}'`);
609
691
  }
610
692
  }
693
+ /**
694
+ * Resolve the value of a boolean option token.
695
+ *
696
+ * `--flag` is `true` and `--no-flag` is `false`. An explicit inline value (`--flag=true`,
697
+ * `--flag=false`, `-f=false`) is read instead; any other inline value is a type error.
698
+ * The negated form does not take a value, so `--no-flag=<value>` is an error.
699
+ *
700
+ * @param token - The option token
701
+ * @param rawArg - The argument key in the schema
702
+ * @param option - The option name used on the command line
703
+ * @param schema - The argument schema
704
+ * @returns The resolved boolean, or a validation error
705
+ */
706
+ function resolveBooleanValue(token, rawArg, option, schema) {
707
+ const negated = isNegatedToken(token, option, schema);
708
+ if (!token.inlineValue) return [!negated, void 0];
709
+ if (negated) return [void 0, createUnexpectedValueError(rawArg, option, schema, token)];
710
+ if (token.value !== "true" && token.value !== "false") return [void 0, createTypeError(rawArg, option, schema, token.value)];
711
+ return [token.value === "true", void 0];
712
+ }
611
713
  function parseSchemaValue(value, rawArg, option, schema) {
612
714
  try {
613
715
  return [schema.parse(value), void 0];
@@ -618,7 +720,10 @@ function parseSchemaValue(value, rawArg, option, schema) {
618
720
  function createRequireError(rawArg, option, schema) {
619
721
  return new ArgResolveError(schema.type === "positional" ? `Positional argument '${option}' is required` : `Optional argument ${createOptionDisplayName(option, schema)} is required`, option, "required", schema, {
620
722
  code: schema.type === "positional" ? ArgsValidationErrorKeys.requiredPositional : ArgsValidationErrorKeys.requiredOption,
621
- values: schema.type === "positional" ? { name: rawArg } : {
723
+ values: schema.type === "positional" ? {
724
+ displayName: createArgumentDisplayName(option, schema),
725
+ name: rawArg
726
+ } : {
622
727
  displayName: createOptionDisplayName(option, schema),
623
728
  name: rawArg
624
729
  }
@@ -634,6 +739,46 @@ function resolveSinglePositionalValue(values, errors, rawArg, option, schema, po
634
739
  function hasDefault(schema) {
635
740
  return schema.default != null;
636
741
  }
742
+ /**
743
+ * Get the value that the default of an argument gives.
744
+ *
745
+ * The value of a `multiple` argument is an array, so its default becomes the only element of an
746
+ * array. A default that is an array already, which only untyped code can give, is used as is.
747
+ *
748
+ * @param schema - The argument schema
749
+ * @returns The value that the default gives
750
+ */
751
+ function getDefaultValue(schema) {
752
+ const value = schema.default;
753
+ return schema.multiple && !Array.isArray(value) ? [value] : value;
754
+ }
755
+ /**
756
+ * Check whether the default of an `enum` option is not one of its `choices`.
757
+ *
758
+ * The default does not go through `parse`, so with a `parse` function of your own, or a `map()`
759
+ * transform, it is a value that the function returns, which need not be one of the choices, and it
760
+ * is not checked. The `parse` function of `choice()` returns the value as is, so its default is
761
+ * checked: among the schemas that the combinators make, it is the only `enum` schema whose `parse`
762
+ * has the {@link PURE_PARSE} brand. An `enum` schema written by hand with another branded `parse`
763
+ * would be checked too.
764
+ *
765
+ * Only a string, number or boolean default, as the type of `default` allows, is checked against an
766
+ * array of choices. Anything else, which only untyped code can give, is used as before.
767
+ *
768
+ * @param schema - The argument schema
769
+ * @returns Whether the default is not one of the choices
770
+ */
771
+ function hasDefaultOutsideChoices(schema) {
772
+ const defaultType = typeof schema.default;
773
+ if (schema.type !== "enum" || !Array.isArray(schema.choices) || defaultType !== "string" && defaultType !== "number" && defaultType !== "boolean" || schema.choices.includes(schema.default)) return false;
774
+ const { parse } = schema;
775
+ if (typeof parse !== "function") return true;
776
+ try {
777
+ return hasPureParseBrand(parse);
778
+ } catch {
779
+ return false;
780
+ }
781
+ }
637
782
  function shouldRequireMissingSinglePositional(schema) {
638
783
  if (schema.required === true) return true;
639
784
  if (schema.required === false) return false;
@@ -657,9 +802,18 @@ function createRequiredPositionalsAfter(argEntries) {
657
802
  }
658
803
  /**
659
804
  * An error that occurs when resolving arguments.
660
- * This error is thrown when the argument is not valid.
805
+ *
806
+ * It is not thrown: when an argument is not valid, {@link resolveArgs} returns it in the `errors`
807
+ * of the `AggregateError` in `error`, and so does `parse()`.
661
808
  */
662
809
  var ArgResolveError = class extends ArgsValidationError {
810
+ /**
811
+ * The name of the argument on the command line, without the leading dashes: the schema key, in
812
+ * kebab-case with `toKebab`, such as `input-file` for `inputFile`, whether the option is given in
813
+ * the long form, as a short option or in the negated form. For a conflict, it is the name of the
814
+ * argument whose `conflicts` names the other one (the first in the schema when both name each
815
+ * other). `values.name` has the schema key.
816
+ */
663
817
  name;
664
818
  schema;
665
819
  type;
@@ -667,7 +821,7 @@ var ArgResolveError = class extends ArgsValidationError {
667
821
  * Create an `ArgResolveError` instance.
668
822
  *
669
823
  * @param message - the error message
670
- * @param name - the name of the argument
824
+ * @param name - the name of the argument on the command line, in kebab-case with `toKebab`
671
825
  * @param type - the type of the error: 'type', 'required', or 'conflict'
672
826
  * @param schema - the argument schema that caused the error
673
827
  * @param options - structured validation metadata
@@ -685,17 +839,166 @@ function validateRequire(token, rawArg, option, schema) {
685
839
  function isNumeric(str) {
686
840
  return str.trim() !== "" && !isNaN(str);
687
841
  }
688
- function createTypeError(rawArg, option, schema, actual) {
689
- return new ArgResolveError(`Optional argument ${createOptionDisplayName(option, schema)} should be '${schema.type}'`, option, "type", schema, {
842
+ function createTypeError(rawArg, option, schema, actual, expected = schema.type) {
843
+ return new ArgResolveError(`Optional argument ${createOptionDisplayName(option, schema)} should be '${expected}'`, option, "type", schema, {
690
844
  code: ArgsValidationErrorKeys.invalidType,
691
845
  values: {
692
846
  displayName: createOptionDisplayName(option, schema),
693
847
  name: rawArg,
694
- expected: schema.type,
848
+ expected,
695
849
  ...actual != null ? { actual } : {}
696
850
  }
697
851
  });
698
852
  }
853
+ /**
854
+ * Create the error for an option that is given without a value.
855
+ *
856
+ * `expected` names what the option takes: its type, or for a `custom` type its `metavar` (for
857
+ * example `'integer'` for the `integer()` combinator). An `enum` also gets its choices. When the
858
+ * argument after the option may be a value that starts with `-`, and the option may take it (see
859
+ * `acceptsSuggestedValue()`), the error suggests the long form with `=`, which passes such a value in
860
+ * every mode of the tokenizer.
861
+ *
862
+ * @param rawArg - The argument key in the schema
863
+ * @param option - The option name used on the command line
864
+ * @param schema - The argument schema
865
+ * @param next - The argument after the option, when it may be a value that starts with `-`
866
+ * @returns The validation error
867
+ */
868
+ function createMissingValueError(rawArg, option, schema, next) {
869
+ const displayName = createOptionDisplayName(option, schema);
870
+ const suggestion = next === void 0 || !acceptsSuggestedValue(schema, next) ? void 0 : `--${option}=${next}`;
871
+ const hint = suggestion === void 0 ? "" : ` (to pass '${next}' as its value, write '${suggestion}')`;
872
+ const choices = schema.choices ?? [];
873
+ return new ArgResolveError(`Optional argument ${displayName} requires a value${hint}`, option, "type", schema, {
874
+ code: ArgsValidationErrorKeys.missingValue,
875
+ values: {
876
+ displayName,
877
+ name: rawArg,
878
+ expected: schema.type === "custom" ? schema.metavar ?? schema.type : schema.type,
879
+ ...schema.type === "enum" ? {
880
+ choices: formatChoices(choices),
881
+ choiceValues: [...choices]
882
+ } : {},
883
+ ...suggestion === void 0 ? {} : {
884
+ next,
885
+ suggestion
886
+ }
887
+ }
888
+ });
889
+ }
890
+ /**
891
+ * Find the argument right after an option that is given without a value, when it may be a value
892
+ * that starts with `-`.
893
+ *
894
+ * The option must end its own argument (with `shortGrouping`, `-pv` gives `-p` no value because of
895
+ * `-v`), and the next argument must be read as options that are not all defined, such as `-5` or
896
+ * `--foo`. Without `shortGrouping`, a group is read as its first option, which takes the other
897
+ * letters as its value, so `-p5` is defined when `-p` is. The argument is rebuilt from its tokens.
898
+ * Without `allowCompatible`, a short option written with a value, such as `-x=1`, `-x=` or `-x-1`,
899
+ * has a value, and is not suggested.
900
+ *
901
+ * @param tokens - The tokens given to `resolveArgs()`
902
+ * @param optionTokens - The option tokens that `resolveArgs()` resolves
903
+ * @param position - The position of the option given without a value in `optionTokens`
904
+ * @param argEntries - The argument schemas
905
+ * @param toKebab - Whether every option name is converted to kebab-case
906
+ * @returns The next argument rebuilt from its tokens, or `undefined` when there is nothing to
907
+ * suggest
908
+ */
909
+ function findOptionLikeNextArgument(tokens, optionTokens, position, argEntries, toKebab) {
910
+ const token = optionTokens[position];
911
+ for (let i = position + 1; i < optionTokens.length; i++) if (optionTokens[i].index === token.index) return;
912
+ const nextArg = tokens.filter((t) => t.index === token.index + 1);
913
+ if (nextArg.length === 0 || nextArg.some((t) => t.kind !== "option" || t.rawName == null)) return;
914
+ let text;
915
+ let known;
916
+ if (nextArg.length === 1 && nextArg[0].rawName.startsWith("--")) {
917
+ const [option] = nextArg;
918
+ text = option.inlineValue ? `${option.rawName}=${option.value}` : option.rawName;
919
+ known = createKnownOptionNames(argEntries, toKebab).long.has(option.name);
920
+ } else if (nextArg.every((t) => isShortOption(t.rawName) && t.value === void 0)) {
921
+ text = `-${nextArg.map((t) => t.name).join("")}`;
922
+ const { short } = createKnownOptionNames(argEntries, toKebab);
923
+ known = optionTokens.every((t) => t.index !== token.index + 1 || short.has(t.name));
924
+ } else return;
925
+ return known ? void 0 : text;
926
+ }
927
+ /**
928
+ * Collect the names of the defined options: the long names, with the negated form of negatable
929
+ * booleans, and the short names.
930
+ *
931
+ * @param argEntries - The argument schemas
932
+ * @param toKebab - Whether every option name is converted to kebab-case
933
+ * @returns The long and short option names
934
+ */
935
+ function createKnownOptionNames(argEntries, toKebab) {
936
+ const long = /* @__PURE__ */ new Set();
937
+ const short = /* @__PURE__ */ new Set();
938
+ for (const [rawArg, schema] of argEntries) {
939
+ if (schema.type === "positional") continue;
940
+ const name = toKebab || schema.toKebab ? kebabnize(rawArg) : rawArg;
941
+ long.add(name);
942
+ if (schema.type === "boolean" && schema.negatable === true) long.add(`no-${name}`);
943
+ if (schema.short) short.add(schema.short);
944
+ }
945
+ return {
946
+ long,
947
+ short
948
+ };
949
+ }
950
+ /**
951
+ * Check whether the argument after an option given without a value may be suggested as its value.
952
+ *
953
+ * The value of a `number` option must be numeric, as the error expects a number, and the value of
954
+ * an `enum` option with `choices` must be one of them, which is checked before any `parse`
955
+ * function. A `parse` function with its own {@link PURE_PARSE} brand is then called with the
956
+ * value, which must not throw. Any other `parse` function may have side effects, so it is not
957
+ * called: a `number` option or an `enum` option with `choices` is then checked only as above, and
958
+ * any other option is not suggested.
959
+ *
960
+ * @param schema - The argument schema
961
+ * @param value - The argument after the option
962
+ * @returns Whether the value may be suggested
963
+ */
964
+ function acceptsSuggestedValue(schema, value) {
965
+ if (schema.type === "number" && !isNumeric(value)) return false;
966
+ if (schema.type === "enum" && schema.choices && !schema.choices.includes(value)) return false;
967
+ const { parse } = schema;
968
+ if (typeof parse !== "function") return true;
969
+ try {
970
+ if (!hasPureParseBrand(parse)) return schema.type === "number" || schema.type === "enum" && schema.choices !== void 0;
971
+ parse(value);
972
+ return true;
973
+ } catch {
974
+ return false;
975
+ }
976
+ }
977
+ /**
978
+ * Check whether a `parse` function has its own {@link PURE_PARSE} brand.
979
+ *
980
+ * Only an own brand counts, as for `isArgsValidationError()`. Reading it may throw, for example for
981
+ * a revoked proxy, so call this function in `try`.
982
+ *
983
+ * @param parse - The `parse` function of a schema
984
+ * @returns Whether the function has no side effects
985
+ */
986
+ function hasPureParseBrand(parse) {
987
+ return Object.hasOwn(parse, PURE_PARSE) && parse[PURE_PARSE] === true;
988
+ }
989
+ function createUnexpectedValueError(rawArg, option, schema, token) {
990
+ const rawName = token.rawName;
991
+ const displayName = `'${rawName}'`;
992
+ return new ArgResolveError(`Optional argument ${displayName} does not take a value`, option, "type", schema, {
993
+ code: ArgsValidationErrorKeys.unexpectedValue,
994
+ values: {
995
+ displayName,
996
+ name: rawArg,
997
+ rawName,
998
+ ...token.value != null ? { actual: token.value } : {}
999
+ }
1000
+ });
1001
+ }
699
1002
  function createChoiceError(rawArg, option, schema, actual) {
700
1003
  const choices = schema.choices ?? [];
701
1004
  return new ArgResolveError(`Optional argument ${createOptionDisplayName(option, schema)} should be chosen from '${schema.type}' [${formatChoices(choices)}] values`, option, "type", schema, {
@@ -710,6 +1013,32 @@ function createChoiceError(rawArg, option, schema, actual) {
710
1013
  }
711
1014
  });
712
1015
  }
1016
+ /**
1017
+ * Create the error for the default of an `enum` option that is not one of its `choices`.
1018
+ *
1019
+ * Its `values` have the same keys as those of `err:arg:invalid-choice`, with the default as
1020
+ * `actual`.
1021
+ *
1022
+ * @param rawArg - The argument key in the schema
1023
+ * @param option - The option name used on the command line
1024
+ * @param schema - The argument schema
1025
+ * @returns The error
1026
+ */
1027
+ function createDefaultChoiceError(rawArg, option, schema) {
1028
+ const choices = schema.choices ?? [];
1029
+ const displayName = createOptionDisplayName(option, schema);
1030
+ return new ArgResolveError(`Optional argument ${displayName} has the default ${typeof schema.default === "string" ? JSON.stringify(schema.default) : String(schema.default)}, which is not one of '${schema.type}' [${formatChoices(choices)}] values`, option, "type", schema, {
1031
+ code: ArgsValidationErrorKeys.invalidDefault,
1032
+ values: {
1033
+ displayName,
1034
+ name: rawArg,
1035
+ expected: schema.type,
1036
+ choices: formatChoices(choices),
1037
+ choiceValues: [...choices],
1038
+ actual: schema.default
1039
+ }
1040
+ });
1041
+ }
713
1042
  function createCustomParseError(error, rawArg, option, schema, value) {
714
1043
  const reused = reuseValidationError(error, rawArg, option, schema, value);
715
1044
  if (reused) return reused;
@@ -759,6 +1088,35 @@ function createArgumentDisplayName(option, schema) {
759
1088
  function createOptionDisplayName(option, schema) {
760
1089
  return `'--${option}'${schema.short ? ` or '-${schema.short}'` : ""}`;
761
1090
  }
1091
+ /**
1092
+ * Create the error for two arguments that conflict.
1093
+ *
1094
+ * An option is shown as it was written, such as `'-p'` or `'--no-color'`, and a positional argument
1095
+ * by its name, such as `'file'`, as in the message. The message starts with "Positional argument"
1096
+ * when `schema` is a positional argument, and with "Optional argument" otherwise.
1097
+ *
1098
+ * @param rawArg - The argument key of the argument whose `conflicts` names the other one
1099
+ * @param option - The name of that argument used on the command line
1100
+ * @param schema - The argument schema of that argument
1101
+ * @param actualName - That option as it was written, or the name of that positional argument
1102
+ * @param conflictingArg - The argument key of the other argument
1103
+ * @param conflictingActualName - The other option as it was written, or the name of the other
1104
+ * positional argument
1105
+ * @returns The validation error
1106
+ */
1107
+ function createConflictError(rawArg, option, schema, actualName, conflictingArg, conflictingActualName) {
1108
+ const displayName = `'${actualName}'`;
1109
+ const conflictDisplayName = `'${conflictingActualName}'`;
1110
+ return new ArgResolveError(`${schema.type === "positional" ? "Positional" : "Optional"} argument ${displayName} conflicts with ${conflictDisplayName}`, option, "conflict", schema, {
1111
+ code: ArgsValidationErrorKeys.conflict,
1112
+ values: {
1113
+ displayName,
1114
+ name: rawArg,
1115
+ conflictDisplayName,
1116
+ conflictName: conflictingArg
1117
+ }
1118
+ });
1119
+ }
762
1120
  function checkConflicts(args, explicit, toKebab, actualInputNames) {
763
1121
  for (const rawArg in args) {
764
1122
  const schema = args[rawArg];
@@ -770,13 +1128,13 @@ function checkConflicts(args, explicit, toKebab, actualInputNames) {
770
1128
  if (!explicit[conflictingArg]) continue;
771
1129
  const arg = toKebab || schema.toKebab ? kebabnize(rawArg) : rawArg;
772
1130
  const conflictingArgKebab = toKebab || args[conflictingArg]?.toKebab ? kebabnize(conflictingArg) : conflictingArg;
773
- return [new ArgResolveError(`Optional argument '${actualInputNames.get(rawArg) || `--${arg}`}' conflicts with '${actualInputNames.get(conflictingArg) || `--${conflictingArgKebab}`}'`, rawArg, "conflict", schema)];
1131
+ return [createConflictError(rawArg, arg, schema, schema.type === "positional" ? arg : actualInputNames.get(rawArg) || `--${arg}`, conflictingArg, args[conflictingArg]?.type === "positional" ? conflictingArgKebab : actualInputNames.get(conflictingArg) || `--${conflictingArgKebab}`)];
774
1132
  }
775
1133
  }
776
1134
  return [];
777
1135
  }
778
1136
  //#endregion
779
- //#region ../../node_modules/.pnpm/args-tokens@0.29.0/node_modules/args-tokens/lib/index.js
1137
+ //#region ../../node_modules/.pnpm/args-tokens@1.0.0-beta.1/node_modules/args-tokens/lib/index.js
780
1138
  /**
781
1139
  * @author kazuya kawaguchi (a.k.a. kazupon)
782
1140
  * @license MIT
@@ -824,14 +1182,20 @@ const CLI_OPTIONS_DEFAULT = {
824
1182
  * Check if the given command is a {@link LazyCommand}.
825
1183
  *
826
1184
  * @param cmd - A command to check
827
- * @returns `true` if the command is a {@link LazyCommand}, otherwise `false
1185
+ * @returns `true` if the command is a {@link LazyCommand}, otherwise `false`
1186
+ *
1187
+ * A lazy command is identified by its `commandName` property. The property may be
1188
+ * `undefined` when the lazy command has no definition name.
828
1189
  */
829
1190
  function isLazyCommand(cmd) {
830
- return typeof cmd === "function" && "commandName" in cmd && !!cmd.commandName;
1191
+ return typeof cmd === "function" && "commandName" in cmd;
831
1192
  }
832
1193
  /**
833
1194
  * Resolve a lazy command to a {@link Command}.
834
1195
  *
1196
+ * If the loader returns a command, the properties of the loaded command take precedence,
1197
+ * and the properties that it does not define fall back to the definition that is given to `lazy`.
1198
+ *
835
1199
  * @param cmd - A {@link Commandable} or {@link LazyCommand} to resolve
836
1200
  * @param name - Optional name of the command, if not provided, it will use the name from the command itself.
837
1201
  * @param needRunResolving - Whether to run the resolving function of the lazy command.
@@ -847,6 +1211,8 @@ async function resolveLazyCommand(cmd, name, needRunResolving = false) {
847
1211
  examples: cmd.examples,
848
1212
  internal: cmd.internal,
849
1213
  entry: cmd.entry,
1214
+ toKebab: cmd.toKebab,
1215
+ rendering: cmd.rendering,
850
1216
  subCommands: cmd.subCommands
851
1217
  };
852
1218
  if ("resource" in cmd && cmd.resource) baseCommand.resource = cmd.resource;
@@ -856,13 +1222,20 @@ async function resolveLazyCommand(cmd, name, needRunResolving = false) {
856
1222
  if (typeof loaded === "function") command.run = loaded;
857
1223
  else if (typeof loaded === "object") {
858
1224
  if (loaded.run == null) throw new TypeError(`'run' is required in command: ${cmd.name || name}`);
1225
+ /**
1226
+ * NOTE(kazupon): the loaded command wins, and the definition that is given to `lazy` is the fallback
1227
+ * for what the loaded command does not define. A loader that returns `{ run }` keeps the whole definition,
1228
+ * like a loader that returns the runner itself.
1229
+ */
859
1230
  command.run = loaded.run;
860
- command.name = loaded.name;
861
- command.description = loaded.description;
862
- command.args = loaded.args;
863
- command.examples = loaded.examples;
864
- command.internal = loaded.internal;
865
- command.entry = loaded.entry;
1231
+ command.name = loaded.name ?? cmd.commandName;
1232
+ command.description = loaded.description ?? cmd.description;
1233
+ command.args = loaded.args ?? cmd.args;
1234
+ command.examples = loaded.examples ?? cmd.examples;
1235
+ command.internal = loaded.internal ?? cmd.internal;
1236
+ command.entry = loaded.entry ?? cmd.entry;
1237
+ command.toKebab = loaded.toKebab ?? cmd.toKebab;
1238
+ command.rendering = loaded.rendering ?? cmd.rendering;
866
1239
  command.subCommands = loaded.subCommands || cmd.subCommands;
867
1240
  if ("resource" in loaded && loaded.resource) command.resource = loaded.resource;
868
1241
  } else throw new TypeError(`Cannot resolve command: ${cmd.name || name}`);
@@ -881,6 +1254,37 @@ function create(obj = null) {
881
1254
  return Object.create(obj);
882
1255
  }
883
1256
  /**
1257
+ * Resolve the arguments of a command, the way gunshi parses and renders them.
1258
+ *
1259
+ * The global options belong to no command definition, so they are merged into the arguments of the
1260
+ * command that runs. An argument of the command shadows the global option of the same name, and it
1261
+ * shadows the same way by short name: a global option gives up its short name to an argument of the
1262
+ * command that claims the same letter, and keeps its long name.
1263
+ *
1264
+ * @param globalOptions - The global options that plugins registered with `addGlobalOption`
1265
+ * @param args - The arguments that the command declares
1266
+ * @returns The merged arguments
1267
+ */
1268
+ function resolveCommandArgs(globalOptions, args) {
1269
+ return Object.assign(create(), resolveGlobalOptions(globalOptions, args), args);
1270
+ }
1271
+ function resolveGlobalOptions(globalOptions, args) {
1272
+ if (!globalOptions) return;
1273
+ const shortNames = /* @__PURE__ */ new Set();
1274
+ for (const schema of Object.values(args || {})) if (schema.type !== "positional" && schema.short) shortNames.add(schema.short);
1275
+ const resolved = create();
1276
+ for (const [name, schema] of globalOptions)
1277
+ /**
1278
+ * NOTE(kazupon): a copy, because the schema is the one that the plugin registered, which every
1279
+ * command of the CLI shares. Only this command gives up the short name.
1280
+ */
1281
+ resolved[name] = schema.short && shortNames.has(schema.short) ? {
1282
+ ...schema,
1283
+ short: void 0
1284
+ } : schema;
1285
+ return resolved;
1286
+ }
1287
+ /**
884
1288
  * Log a message to the console.
885
1289
  *
886
1290
  * @param args - Arguments to log
@@ -1003,7 +1407,7 @@ async function createCommandContext({ args = {}, explicit = {}, values = {}, pos
1003
1407
  if (extension.onFactory) await extension.onFactory(core, command);
1004
1408
  }
1005
1409
  }
1006
- return deepFreeze(core, ["extensions"]);
1410
+ return deepFreeze(core, ["extensions", "entryCommand"]);
1007
1411
  }
1008
1412
  function getCommandName(cmd) {
1009
1413
  if (isLazyCommand(cmd)) return cmd.commandName || cmd.name || "(anonymous)";
@@ -1089,6 +1493,18 @@ function createDecorators() {
1089
1493
  */
1090
1494
  const CommandNotFoundErrorKeys = { notFound: "err:cmd:not-found" };
1091
1495
  /**
1496
+ * Command resolution error resource keys.
1497
+ *
1498
+ * These errors describe an ambiguity or inconsistency while choosing a command from arguments.
1499
+ * They are kept separate from {@link CommandNotFoundError} so consumers can distinguish a typo
1500
+ * from an input whose command interpretation is not unique.
1501
+ */
1502
+ const CommandResolutionErrorKeys = {
1503
+ ambiguous: "err:cmd:ambiguous",
1504
+ inconsistentOptions: "err:cmd:inconsistent-options",
1505
+ lazySchemaMismatch: "err:cmd:lazy-schema-mismatch"
1506
+ };
1507
+ /**
1092
1508
  * Brand that marks {@link CommandNotFoundError} instances.
1093
1509
  *
1094
1510
  * The brand is looked up in the global symbol registry with `Symbol.for`, so it stays
@@ -1097,6 +1513,7 @@ const CommandNotFoundErrorKeys = { notFound: "err:cmd:not-found" };
1097
1513
  * another copy, where `instanceof` cannot match.
1098
1514
  */
1099
1515
  const COMMAND_NOT_FOUND_ERROR_BRAND = Symbol.for("gunshi.CommandNotFoundError");
1516
+ const COMMAND_RESOLUTION_ERROR_BRAND = Symbol.for("gunshi.CommandResolutionError");
1100
1517
  /**
1101
1518
  * Error raised when a command cannot be resolved.
1102
1519
  *
@@ -1133,6 +1550,39 @@ var CommandNotFoundError = class extends Error {
1133
1550
  }
1134
1551
  };
1135
1552
  /**
1553
+ * Error raised when command routing cannot produce one consistent command.
1554
+ *
1555
+ * The own registry brand is the cross-bundle contract. Unlike the legacy command-not-found
1556
+ * guard, the new guard deliberately has no name-based fallback because this error type is new and
1557
+ * must not classify arbitrary errors from older versions.
1558
+ */
1559
+ var CommandResolutionError = class extends Error {
1560
+ code;
1561
+ values;
1562
+ commandPath;
1563
+ candidatePaths;
1564
+ /**
1565
+ * Create a command resolution error with structured routing metadata.
1566
+ *
1567
+ * @param message - Human-readable fallback message
1568
+ * @param options - Error code and command-routing metadata
1569
+ */
1570
+ constructor(message, options = {}) {
1571
+ super(message, { cause: options.cause });
1572
+ this.name = "CommandResolutionError";
1573
+ this.code = options.code;
1574
+ this.values = options.values || {};
1575
+ this.commandPath = options.commandPath || [];
1576
+ this.candidatePaths = options.candidatePaths || [];
1577
+ Object.defineProperty(this, COMMAND_RESOLUTION_ERROR_BRAND, {
1578
+ value: true,
1579
+ enumerable: false,
1580
+ writable: false,
1581
+ configurable: false
1582
+ });
1583
+ }
1584
+ };
1585
+ /**
1136
1586
  * Check whether an error is a {@link CommandNotFoundError}.
1137
1587
  *
1138
1588
  * `instanceof` alone is not enough: `@gunshi/plugin` is bundled with its own copy of this
@@ -1150,6 +1600,17 @@ function isCommandNotFoundError(error) {
1150
1600
  return error instanceof Error && error.name === "CommandNotFoundError";
1151
1601
  }
1152
1602
  /**
1603
+ * Check whether an error is a {@link CommandResolutionError}.
1604
+ *
1605
+ * @param error - An unknown error
1606
+ * @returns `true` when the error has the command-resolution brand and shape
1607
+ */
1608
+ function isCommandResolutionError(error) {
1609
+ if (error instanceof CommandResolutionError) return true;
1610
+ if (!isRecord(error) || !hasCommandResolutionErrorShape(error)) return false;
1611
+ return Object.hasOwn(error, COMMAND_RESOLUTION_ERROR_BRAND) && error[COMMAND_RESOLUTION_ERROR_BRAND] === true;
1612
+ }
1613
+ /**
1153
1614
  * Check whether an error is an {@link ArgsValidationError}.
1154
1615
  *
1155
1616
  * Prefer this over the `args-tokens` guard of the same name. Both recognize errors from another
@@ -1193,6 +1654,9 @@ function hasOptionalStringCode(error) {
1193
1654
  function hasCommandNotFoundErrorShape(error) {
1194
1655
  return hasOptionalStringCode(error) && isRecord(error.values) && typeof error.commandName === "string" && isStringArray(error.candidates) && isStringArray(error.commandPath);
1195
1656
  }
1657
+ function hasCommandResolutionErrorShape(error) {
1658
+ return hasOptionalStringCode(error) && isRecord(error.values) && isStringArray(error.commandPath) && Array.isArray(error.candidatePaths) && error.candidatePaths.every((path) => isStringArray(path));
1659
+ }
1196
1660
  function hasArgsValidationErrorShape(error) {
1197
1661
  return hasOptionalStringCode(error) && isRecord(error.values);
1198
1662
  }
@@ -1203,7 +1667,7 @@ function hasArgsValidationErrorShape(error) {
1203
1667
  * @returns `true` if the validation error must be handled with priority
1204
1668
  */
1205
1669
  function hasPriorityValidationError(error) {
1206
- return error?.errors.some((error) => isCommandNotFoundError(error) || isArgsValidationError(error) && error.code === ArgsValidationErrorKeys.unknownOption) ?? false;
1670
+ return error?.errors.some((error) => isCommandNotFoundError(error) || isCommandResolutionError(error) || isArgsValidationError(error) && error.code === ArgsValidationErrorKeys.unknownOption) ?? false;
1207
1671
  }
1208
1672
  //#endregion
1209
1673
  //#region ../gunshi/src/plugin/context.ts
@@ -1236,6 +1700,22 @@ function createPluginContext(decorators, initialSubCommands) {
1236
1700
  addGlobalOption(name, schema) {
1237
1701
  if (!name) throw new Error("Option name must be a non-empty string");
1238
1702
  if (globalOptions.has(name)) throw new Error(`Global option '${name}' is already registered`);
1703
+ /**
1704
+ * NOTE(kazupon): a short name belongs to one option. The global options of a CLI come from
1705
+ * plugins that know nothing of each other, so two of them may reach for the same letter, and
1706
+ * the parser would then match both and give neither the value that was typed. The one that
1707
+ * asked first keeps the letter, and the other keeps its long name — the same way a global
1708
+ * option gives its short name up to an argument of the command that claims it.
1709
+ */
1710
+ const taken = schema.short && findGlobalOptionByShort(globalOptions, schema.short);
1711
+ if (taken) {
1712
+ console.warn(`Short name '-${schema.short}' of the global option '${name}' is already used by '${taken}'. Global option '${name}' is registered without it.`);
1713
+ globalOptions.set(name, {
1714
+ ...schema,
1715
+ short: void 0
1716
+ });
1717
+ return;
1718
+ }
1239
1719
  globalOptions.set(name, schema);
1240
1720
  },
1241
1721
  get subCommands() {
@@ -1263,6 +1743,16 @@ function createPluginContext(decorators, initialSubCommands) {
1263
1743
  }
1264
1744
  });
1265
1745
  }
1746
+ /**
1747
+ * Find the global option that already uses a short name.
1748
+ *
1749
+ * @param globalOptions - The global options registered so far
1750
+ * @param short - A short name, without the leading dash
1751
+ * @returns The name of the global option that uses it, or `undefined`
1752
+ */
1753
+ function findGlobalOptionByShort(globalOptions, short) {
1754
+ for (const [name, schema] of globalOptions) if (schema.short === short) return name;
1755
+ }
1266
1756
  //#endregion
1267
1757
  //#region ../gunshi/src/plugin/dependency.ts
1268
1758
  /**
@@ -1280,12 +1770,13 @@ function resolveDependencies(plugins) {
1280
1770
  const visited = /* @__PURE__ */ new Set();
1281
1771
  const visiting = /* @__PURE__ */ new Set();
1282
1772
  const pluginMap = /* @__PURE__ */ new Map();
1283
- for (const plugin of plugins) if (plugin.id) {
1773
+ for (const plugin of plugins) {
1774
+ if (typeof plugin.id !== "string" || plugin.id.length === 0) throw new Error("Plugin id must be a non-empty string");
1284
1775
  if (pluginMap.has(plugin.id)) console.warn(`Duplicate plugin id detected: \`${plugin.id}\``);
1285
1776
  pluginMap.set(plugin.id, plugin);
1286
1777
  }
1287
1778
  function visit(plugin) {
1288
- if (!plugin.id) return;
1779
+ if (typeof plugin.id !== "string" || plugin.id.length === 0) throw new Error("Plugin id must be a non-empty string");
1289
1780
  if (visited.has(plugin.id)) return;
1290
1781
  if (visiting.has(plugin.id)) throw new Error(`Circular dependency detected: \`${[...visiting].join(` -> `) + " -> " + plugin.id}\``);
1291
1782
  visiting.add(plugin.id);
@@ -1319,15 +1810,30 @@ function resolveDependencies(plugins) {
1319
1810
  * @param entry - A {@link Command | entry command}, an {@link CommandRunner | inline command runner}, or a {@link LazyCommand | lazily-loaded command}
1320
1811
  * @param options - A {@link CliOptions | CLI options}
1321
1812
  * @param plugins - An array of {@link Plugin | plugins} to be applied
1813
+ * @param usageOnly - Whether to render the usage of the command instead of running it, which is what `generate` of `gunshi/generator` asks for
1322
1814
  * @returns A rendered usage or undefined. if you will use {@link CliOptions.usageSilent} option, it will return rendered usage string.
1323
1815
  */
1324
- async function cliCore(argv, entry, options, plugins) {
1816
+ async function cliCore(argv, entry, options, plugins, usageOnly = false) {
1325
1817
  const decorators = createDecorators();
1326
- const pluginContext = createPluginContext(decorators, createInitialSubCommands(options, entry));
1818
+ /**
1819
+ * NOTE(kazupon): the decorator goes on before any plugin, which makes it the outermost one, so
1820
+ * that the usage is rendered whatever the command declares and the runner is never reached.
1821
+ */
1822
+ if (usageOnly) decorators.addCommandDecorator(usageOnlyDecorator());
1823
+ const entryCommand = createEntryCommand(entry);
1824
+ const initialSubCommands = createInitialSubCommands(options, entryCommand);
1825
+ const pluginContext = createPluginContext(decorators, initialSubCommands);
1327
1826
  const resolvedPlugins = await applyPlugins(pluginContext, [...plugins, ...options.plugins || []]);
1328
- const cliOptions = normalizeCliOptions(options, decorators, pluginContext);
1827
+ const cliOptions = normalizeCliOptions(options, decorators, pluginContext, entryCommand);
1828
+ /**
1829
+ * NOTE(kazupon): a CLI whose user declares no sub-commands has no command tree of its own,
1830
+ * so a positional argument must not become a command name just because a plugin added a command.
1831
+ * The user can still opt out with an explicit `fallbackToEntry: false`.
1832
+ */
1833
+ if (initialSubCommands.size === 0 && cliOptions.subCommands.size > 0 && options.fallbackToEntry === void 0) cliOptions.fallbackToEntry = true;
1329
1834
  const tokens = parseArgs(argv);
1330
- const resolved = resolveCommandTree(tokens, entry, cliOptions);
1835
+ const selection = resolveCommandSelection(tokens, entry, cliOptions, pluginContext.globalOptions);
1836
+ const resolved = selection.context;
1331
1837
  const { commandName: name, command, callMode, commandPath, depth, levelSubCommands } = resolved;
1332
1838
  let targetCommand = command;
1333
1839
  let targetCommandName = name;
@@ -1336,7 +1842,7 @@ async function cliCore(argv, entry, options, plugins) {
1336
1842
  let targetDepth = depth;
1337
1843
  let targetOmitted = resolved.omitted;
1338
1844
  let targetLevelSubCommands = levelSubCommands;
1339
- const additionalValidationErrors = [];
1845
+ const additionalValidationErrors = selection.error ? [selection.error] : [];
1340
1846
  if (!targetCommand) {
1341
1847
  if (!resolved.parentCommand || !resolved.unresolvedCommandName) throw new Error(`Command not found: ${name || ""}`);
1342
1848
  targetCommand = resolved.parentCommand;
@@ -1348,16 +1854,34 @@ async function cliCore(argv, entry, options, plugins) {
1348
1854
  targetLevelSubCommands = resolved.parentSubCommands;
1349
1855
  additionalValidationErrors.push(createCommandNotFoundError(resolved));
1350
1856
  }
1857
+ const routingOptions = Object.assign(create(), cliOptions, { subCommands: new Map(cliOptions.subCommands) });
1351
1858
  if (targetLevelSubCommands) cliOptions.subCommands = targetLevelSubCommands;
1352
1859
  const resolvedCommand = isLazyCommand(targetCommand) ? await resolveLazyCommand(targetCommand, targetCommandName, true) : targetCommand;
1353
- const args = resolveArguments(pluginContext, getCommandArgs(resolvedCommand));
1860
+ if (selection.error == null && isLazyCommand(targetCommand)) {
1861
+ const loaded = resolveCommandTreeFromPositionals(getRoutingPositionals(tokens, pluginContext.globalOptions, resolvedCommand), entry, routingOptions);
1862
+ if (!sameCommandPath(loaded.commandPath, targetCommandPath)) additionalValidationErrors.push(createLazySchemaMismatchError(targetCommandPath, loaded.commandPath));
1863
+ }
1864
+ const commandArgs = getCommandArgs(resolvedCommand);
1865
+ const args = resolveCommandArgs(pluginContext.globalOptions, commandArgs);
1866
+ /**
1867
+ * NOTE(kazupon): a plugin cannot tell on its own whether the global option it registered survived
1868
+ * the merge, so the core says which ones are in effect for this command (#745).
1869
+ */
1870
+ cliOptions.globalOptions = resolveEffectiveGlobalOptions(pluginContext.globalOptions, commandArgs, args);
1354
1871
  const skipPositional = targetDepth > 0 ? targetDepth - 1 : -1;
1355
- const { explicit, values, positionals, rest, error } = resolveArgs(args, tokens, {
1872
+ const diagnostic = selection.diagnostic === true;
1873
+ const { explicit, values, positionals, rest, error } = diagnostic ? {
1874
+ explicit: create(),
1875
+ values: create(),
1876
+ positionals: [],
1877
+ rest: [],
1878
+ error: void 0
1879
+ } : resolveArgs(args, tokens, {
1356
1880
  shortGrouping: true,
1357
1881
  toKebab: resolvedCommand.toKebab,
1358
1882
  skipPositional
1359
1883
  });
1360
- const validationError = mergeValidationErrors(error, [...additionalValidationErrors, ...cliOptions.strict ? createUnknownOptionErrors(findUnknownOptions(args, tokens, { toKebab: resolvedCommand.toKebab })) : []]);
1884
+ const validationError = mergeValidationErrors(error, [...additionalValidationErrors, ...cliOptions.strict && !diagnostic ? createUnknownOptionErrors(findUnknownOptions(args, tokens, { toKebab: resolvedCommand.toKebab })) : []]);
1361
1885
  return await executeCommand(resolvedCommand, await createCommandContext({
1362
1886
  args,
1363
1887
  explicit,
@@ -1375,11 +1899,35 @@ async function cliCore(argv, entry, options, plugins) {
1375
1899
  cliOptions
1376
1900
  }), decorators.commandDecorators);
1377
1901
  }
1902
+ /**
1903
+ * Create the decorator that renders the usage of the command instead of running it.
1904
+ *
1905
+ * NOTE(kazupon): `generate()` of `gunshi/generator` asks the core for a usage. It used to ask by
1906
+ * adding `-h` to the arguments, which made the answer depend on what the command calls its own
1907
+ * arguments: a command that declares one named `help` takes the schema of the global option, and
1908
+ * the usage was never rendered. A decorator is not an argument, so no command can take it away.
1909
+ *
1910
+ * @returns A {@linkcode CommandDecorator | command decorator} that renders the usage
1911
+ */
1912
+ function usageOnlyDecorator() {
1913
+ return () => async (ctx) => {
1914
+ if (hasPriorityValidationError(ctx.validationError)) throw ctx.validationError;
1915
+ const buf = [];
1916
+ if (ctx.env.renderHeader != null) {
1917
+ const header = await ctx.env.renderHeader(ctx);
1918
+ if (header) buf.push(header);
1919
+ }
1920
+ if (ctx.env.renderUsage == null) return;
1921
+ const usage = await ctx.env.renderUsage(ctx);
1922
+ if (!usage) return;
1923
+ buf.push(usage);
1924
+ return buf.join("\n");
1925
+ };
1926
+ }
1378
1927
  async function applyPlugins(pluginContext, plugins) {
1379
1928
  const sortedPlugins = resolveDependencies(plugins);
1380
- try {
1381
- for (const plugin of sortedPlugins)
1382
- /**
1929
+ for (const plugin of sortedPlugins) try {
1930
+ /**
1383
1931
  * NOTE(kazupon):
1384
1932
  * strictly `Args` are not required for plugin installation.
1385
1933
  * because the strictly `Args` required by each plugin are unknown,
@@ -1387,18 +1935,39 @@ async function applyPlugins(pluginContext, plugins) {
1387
1935
  */
1388
1936
  await plugin(pluginContext);
1389
1937
  } catch (error) {
1390
- console.error("Error loading plugin:", error.message);
1938
+ /**
1939
+ * NOTE(kazupon): a plugin that cannot be installed leaves the CLI without the options, the
1940
+ * commands and the decorators it was written to add, and the plugins behind it are not
1941
+ * installed either, while their context extensions are handed to the command all the same.
1942
+ * `resolveDependencies()` already ends the run for a circular or a missing dependency, so a
1943
+ * `setup` that throws ends it too, naming the plugin rather than leaving the failure to
1944
+ * surface somewhere else.
1945
+ */
1946
+ throw new Error(`Failed to install the plugin \`${plugin.id}\``, { cause: error });
1391
1947
  }
1392
1948
  return sortedPlugins;
1393
1949
  }
1950
+ /**
1951
+ * Resolve the global options that are in effect for the command being executed.
1952
+ *
1953
+ * A global option is in effect unless the command declares an argument of its own under the same
1954
+ * name, which replaces it. The schema is taken from the merged arguments, so it is the one in effect.
1955
+ *
1956
+ * @param globalOptions - The global options that plugins registered with `addGlobalOption`
1957
+ * @param commandArgs - The arguments that the command declares
1958
+ * @param args - The merged arguments
1959
+ * @returns The global options in effect, keyed by name
1960
+ */
1961
+ function resolveEffectiveGlobalOptions(globalOptions, commandArgs, args) {
1962
+ const effective = /* @__PURE__ */ new Map();
1963
+ for (const name of globalOptions.keys()) if (!Object.hasOwn(commandArgs, name)) effective.set(name, args[name]);
1964
+ return effective;
1965
+ }
1394
1966
  function getCommandArgs(cmd) {
1395
1967
  if (isLazyCommand(cmd)) return cmd.args || create();
1396
1968
  else if (typeof cmd === "object") return cmd.args || create();
1397
1969
  else return create();
1398
1970
  }
1399
- function resolveArguments(pluginContext, args) {
1400
- return Object.assign(create(), Object.fromEntries(pluginContext.globalOptions), args);
1401
- }
1402
1971
  const NEGATABLE_OPTION_PREFIX = "no-";
1403
1972
  function findUnknownOptions(args, tokens, options) {
1404
1973
  const knownLongOptions = /* @__PURE__ */ new Set();
@@ -1416,12 +1985,16 @@ function findUnknownOptions(args, tokens, options) {
1416
1985
  if (schema.type === "positional") continue;
1417
1986
  const optionName = resolveOptionName(name, schema, options);
1418
1987
  knownLongOptions.add(optionName);
1419
- addLongOptionCandidate(optionName);
1988
+ /**
1989
+ * NOTE(kazupon): a hidden option is still accepted, so it stays a known option. It is left out
1990
+ * of the candidates, which are what `@gunshi/plugin-suggestion` offers as "Did you mean".
1991
+ */
1992
+ if (!schema.hidden) addLongOptionCandidate(optionName);
1420
1993
  if (schema.short) knownShortOptions.add(schema.short);
1421
1994
  if (schema.type === "boolean" && schema.negatable) {
1422
1995
  const negatableOptionName = `${NEGATABLE_OPTION_PREFIX}${optionName}`;
1423
1996
  knownNegatableOptions.add(negatableOptionName);
1424
- addLongOptionCandidate(negatableOptionName);
1997
+ if (!schema.hidden) addLongOptionCandidate(negatableOptionName);
1425
1998
  }
1426
1999
  }
1427
2000
  const unknownOptions = [];
@@ -1460,45 +2033,60 @@ function mergeValidationErrors(error, additionalErrors) {
1460
2033
  return new AggregateError(error ? [...error.errors, ...additionalErrors] : additionalErrors, error?.message || additionalErrors[0]?.message);
1461
2034
  }
1462
2035
  const isObject = (val) => val !== null && typeof val === "object";
1463
- function createInitialSubCommands(options, entryCmd) {
2036
+ /**
2037
+ * Create the entry command that sub-commands and plugins can see.
2038
+ * The user-provided entry is copied, so that marking it with `entry: true` does not mutate it.
2039
+ *
2040
+ * @param entryCmd - The entry that is passed to `cli`
2041
+ * @returns The entry command marked with `entry: true`, or `undefined` if the entry is not a command
2042
+ */
2043
+ function createEntryCommand(entryCmd) {
2044
+ if (isLazyCommand(entryCmd)) return Object.assign((...args) => entryCmd(...args), entryCmd, { entry: true });
2045
+ else if (typeof entryCmd === "object") return Object.assign(create(), entryCmd, { entry: true });
2046
+ else if (typeof entryCmd === "function") return {
2047
+ run: entryCmd,
2048
+ name: entryCmd.name || "(anonymous)",
2049
+ entry: true
2050
+ };
2051
+ }
2052
+ function createInitialSubCommands(options, entryCommand) {
1464
2053
  const hasSubCommands = options.subCommands ? options.subCommands instanceof Map ? options.subCommands.size > 0 : isObject(options.subCommands) && Object.keys(options.subCommands).length > 0 : false;
1465
2054
  const subCommands = new Map(options.subCommands instanceof Map ? options.subCommands : []);
1466
2055
  if (!(options.subCommands instanceof Map) && isObject(options.subCommands)) for (const [name, cmd] of Object.entries(options.subCommands)) subCommands.set(name, cmd);
1467
- if (hasSubCommands) {
1468
- if (isLazyCommand(entryCmd)) {
1469
- const entryCopy = Object.assign((...args) => entryCmd(...args), entryCmd, { entry: true });
1470
- subCommands.set(resolveEntryName(entryCopy), entryCopy);
1471
- } else if (typeof entryCmd === "object") {
1472
- const entryCopy = Object.assign(create(), entryCmd, { entry: true });
1473
- subCommands.set(resolveEntryName(entryCopy), entryCopy);
1474
- } else if (typeof entryCmd === "function") {
1475
- const name = entryCmd.name || "(anonymous)";
1476
- subCommands.set(name, {
1477
- run: entryCmd,
1478
- name,
1479
- entry: true
1480
- });
1481
- }
1482
- }
2056
+ if (hasSubCommands && entryCommand) subCommands.set(resolveEntryName(entryCommand), entryCommand);
1483
2057
  return subCommands;
1484
2058
  }
1485
- function normalizeCliOptions(options, decorators, pluginContext) {
2059
+ function normalizeCliOptions(options, decorators, pluginContext, entryCommand) {
1486
2060
  const subCommands = new Map(pluginContext.subCommands);
1487
- const resolvedOptions = Object.assign(create(), CLI_OPTIONS_DEFAULT, options, { subCommands });
2061
+ /**
2062
+ * NOTE(kazupon): the entry command is part of `subCommands` only when the user passes sub-commands,
2063
+ * so it is exposed on its own for the plugins that add commands to a CLI without sub-commands.
2064
+ */
2065
+ const resolvedOptions = Object.assign(create(), CLI_OPTIONS_DEFAULT, options, {
2066
+ subCommands,
2067
+ entryCommand
2068
+ });
1488
2069
  if (resolvedOptions.renderHeader === void 0) resolvedOptions.renderHeader = decorators.getHeaderRenderer();
1489
2070
  if (resolvedOptions.renderUsage === void 0) resolvedOptions.renderUsage = decorators.getUsageRenderer();
1490
2071
  if (resolvedOptions.renderValidationErrors === void 0) resolvedOptions.renderValidationErrors = decorators.getValidationErrorsRenderer();
1491
2072
  return resolvedOptions;
1492
2073
  }
1493
2074
  function getPositionalTokens(tokens) {
1494
- return tokens.filter((t) => t.kind === "positional").map((t) => t.value).filter((v) => !!v);
2075
+ const positionals = [];
2076
+ for (const token of tokens) {
2077
+ if (token.kind === "option-terminator") break;
2078
+ if (token.kind === "positional" && token.value) positionals.push(token.value);
2079
+ }
2080
+ return positionals;
1495
2081
  }
1496
2082
  function resolveCommandTree(tokens, entry, options) {
1497
- const positionals = getPositionalTokens(tokens);
2083
+ return resolveCommandTreeFromPositionals(getPositionalTokens(tokens), entry, options);
2084
+ }
2085
+ function resolveCommandTreeFromPositionals(positionals, entry, options) {
1498
2086
  function resolveAsEntry() {
1499
2087
  if (typeof entry === "function") {
1500
- if ("commandName" in entry && entry.commandName) return {
1501
- commandName: entry.commandName,
2088
+ if (isLazyCommand(entry)) return {
2089
+ commandName: resolveEntryName(entry),
1502
2090
  command: entry,
1503
2091
  callMode: "entry",
1504
2092
  commandPath: [],
@@ -1607,6 +2195,209 @@ function resolveCommandTree(tokens, entry, options) {
1607
2195
  levelSubCommands
1608
2196
  };
1609
2197
  }
2198
+ /**
2199
+ * Select a command while accounting for option values that args-tokens removes during resolution.
2200
+ *
2201
+ * The routing pass deliberately projects each candidate's schemas down to the metadata needed to
2202
+ * classify tokens. It never copies `parse`, defaults, required checks, or other user code. A
2203
+ * candidate is accepted only when routing its own declaration reaches the same Map-key path in the
2204
+ * declaration tree.
2205
+ *
2206
+ * @param tokens - Tokenized command-line arguments
2207
+ * @param entry - Entry command definition or runner
2208
+ * @param options - Internal CLI options with the declared sub-command tree
2209
+ * @param globalOptions - Global option schemas used during candidate classification
2210
+ * @returns The selected command context or a diagnostic resolution error
2211
+ */
2212
+ function resolveCommandSelection(tokens, entry, options, globalOptions) {
2213
+ const rawPositionals = getPositionalTokens(tokens);
2214
+ const legacy = resolveCommandTree(tokens, entry, options);
2215
+ if (!tokens.some((token) => token.kind === "option")) return { context: legacy };
2216
+ const candidates = collectRoutingCandidates(rawPositionals, options.subCommands);
2217
+ const evaluations = candidates.map((candidate) => evaluateRoutingCandidate(candidate));
2218
+ const validExplicit = evaluations.filter((evaluation) => evaluation.result.command != null && evaluation.result.unresolvedCommandName == null && sameCommandPath(evaluation.result.commandPath, evaluation.path) && evaluation.path.length > 0);
2219
+ if (legacy.command != null && legacy.unresolvedCommandName == null && legacy.commandPath.length > 0) {
2220
+ const legacyMatch = validExplicit.find((evaluation) => sameCommandPath(evaluation.path, legacy.commandPath));
2221
+ if (legacyMatch) return { context: legacyMatch.result };
2222
+ }
2223
+ if (validExplicit.length === 1) return { context: validExplicit[0].result };
2224
+ if (validExplicit.length > 1) return createCommandResolutionResult(options, entry, CommandResolutionErrorKeys.ambiguous, validExplicit.map((evaluation) => evaluation.path));
2225
+ const entryEvaluation = evaluateRoutingCandidate({
2226
+ path: [],
2227
+ command: getEntryRoutingCommand(entry, options)
2228
+ });
2229
+ if (entryEvaluation.result.command != null && entryEvaluation.result.unresolvedCommandName == null && entryEvaluation.result.commandPath.length === 0) return { context: entryEvaluation.result };
2230
+ const failures = evaluations.filter((evaluation) => {
2231
+ const { result } = evaluation;
2232
+ if (!result.unresolvedCommandName) return false;
2233
+ const parentPath = result.parentCommandPath || [];
2234
+ return isPathPrefix(evaluation.path, parentPath);
2235
+ }).map((evaluation) => evaluation.result);
2236
+ if (entryEvaluation.result.unresolvedCommandName) failures.push(entryEvaluation.result);
2237
+ const deepestFailures = selectDeepestFailures(failures);
2238
+ if (deepestFailures.length === 1) return { context: deepestFailures[0] };
2239
+ if (deepestFailures.length > 1) {
2240
+ const paths = deepestFailures.map((result) => result.parentCommandPath || []);
2241
+ return createCommandResolutionResult(options, entry, CommandResolutionErrorKeys.ambiguous, paths);
2242
+ }
2243
+ return createCommandResolutionResult(options, entry, CommandResolutionErrorKeys.inconsistentOptions, candidates.map((candidate) => candidate.path));
2244
+ function evaluateRoutingCandidate(candidate) {
2245
+ const positionals = getRoutingPositionals(tokens, globalOptions, candidate.command);
2246
+ return {
2247
+ ...candidate,
2248
+ positionals,
2249
+ result: resolveCommandTreeFromPositionals(positionals, entry, options)
2250
+ };
2251
+ }
2252
+ }
2253
+ function collectRoutingCandidates(rawPositionals, root) {
2254
+ const candidates = [];
2255
+ const seen = /* @__PURE__ */ new Set();
2256
+ function collect(commands, offset, parentPath) {
2257
+ for (let index = offset; index < rawPositionals.length; index++) {
2258
+ const name = rawPositionals[index];
2259
+ const command = commands.get(name);
2260
+ if (command == null) continue;
2261
+ const path = [...parentPath, name];
2262
+ const key = JSON.stringify(path);
2263
+ const normalized = normalizeCommandReference(command, name);
2264
+ if (!seen.has(key)) {
2265
+ seen.add(key);
2266
+ candidates.push({
2267
+ path,
2268
+ command: normalized
2269
+ });
2270
+ }
2271
+ const nested = getCommandSubCommands(normalized);
2272
+ if (nested && nested.size > 0) collect(nested, index + 1, path);
2273
+ }
2274
+ }
2275
+ collect(root, 0, []);
2276
+ return candidates;
2277
+ }
2278
+ function normalizeCommandReference(command, name) {
2279
+ if (typeof command === "function" && command.commandName == null) return Object.assign((...args) => command(...args), command, { commandName: name });
2280
+ if (typeof command === "object" && command.name == null) return Object.assign(create(), command, { name });
2281
+ return command;
2282
+ }
2283
+ function getEntryRoutingCommand(entry, options) {
2284
+ if (options.entryCommand) return options.entryCommand;
2285
+ if (typeof entry === "function" && !isLazyCommand(entry)) return {
2286
+ run: entry,
2287
+ entry: true
2288
+ };
2289
+ return entry;
2290
+ }
2291
+ function getRoutingPositionals(tokens, globalOptions, command) {
2292
+ const effective = resolveCommandArgs(globalOptions, getCommandArgs(command));
2293
+ const routingArgs = create();
2294
+ for (const [name, schema] of Object.entries(effective)) {
2295
+ if (schema.type === "positional") continue;
2296
+ routingArgs[name] = {
2297
+ type: schema.type === "boolean" ? "boolean" : "string",
2298
+ short: schema.short,
2299
+ negatable: schema.negatable,
2300
+ toKebab: schema.toKebab
2301
+ };
2302
+ }
2303
+ /**
2304
+ * NOTE(kazupon): an empty argument is never a command name. `getPositionalTokens()` skips it when it
2305
+ * collects the candidates, and the routing of each candidate must skip it too; otherwise the routing
2306
+ * looks for a sub-command named `''`, and fails with `inconsistent-options` (#781).
2307
+ */
2308
+ return resolveArgs(routingArgs, tokens, {
2309
+ shortGrouping: true,
2310
+ toKebab: command.toKebab
2311
+ }).positionals.filter((value) => value !== "");
2312
+ }
2313
+ function sameCommandPath(left, right) {
2314
+ return left.length === right.length && left.every((name, index) => name === right[index]);
2315
+ }
2316
+ function isPathPrefix(prefix, path) {
2317
+ return prefix.length <= path.length && prefix.every((name, index) => name === path[index]);
2318
+ }
2319
+ function selectDeepestFailures(failures) {
2320
+ const unique = /* @__PURE__ */ new Map();
2321
+ for (const failure of failures) {
2322
+ const path = failure.parentCommandPath || [];
2323
+ const key = JSON.stringify(path);
2324
+ unique.set(key, failure);
2325
+ }
2326
+ const deepest = Math.max(-1, ...[...unique.values()].map((failure) => (failure.parentCommandPath || []).length));
2327
+ return [...unique.values()].filter((failure) => (failure.parentCommandPath || []).length === deepest);
2328
+ }
2329
+ function createCommandResolutionResult(options, entry, code, candidatePaths) {
2330
+ const normalizedPaths = candidatePaths.map((path) => [...path]);
2331
+ const commandPath = commonCommandPath(normalizedPaths);
2332
+ const parent = resolveCommandTreeFromPositionals(commandPath, entry, options);
2333
+ const command = createDiagnosticCommand(parent.command, commandPath.at(-1));
2334
+ const context = {
2335
+ ...parent,
2336
+ command,
2337
+ commandPath,
2338
+ depth: commandPath.length,
2339
+ commandName: parent.commandName || commandPath.at(-1),
2340
+ callMode: commandPath.length > 0 ? "subCommand" : "entry",
2341
+ omitted: false
2342
+ };
2343
+ const formattedPaths = normalizedPaths.map((path) => path.join(" ")).join(", ");
2344
+ const formattedPath = commandPath.join(" ");
2345
+ const values = {
2346
+ commandPath: formattedPath,
2347
+ candidatePaths: formattedPaths,
2348
+ candidates: formattedPaths
2349
+ };
2350
+ return {
2351
+ context,
2352
+ error: new CommandResolutionError(createCommandResolutionMessage(code, formattedPath, formattedPaths), {
2353
+ code,
2354
+ values,
2355
+ commandPath,
2356
+ candidatePaths: normalizedPaths
2357
+ }),
2358
+ diagnostic: true
2359
+ };
2360
+ }
2361
+ function commonCommandPath(paths) {
2362
+ if (paths.length === 0) return [];
2363
+ const common = [...paths[0]];
2364
+ for (const path of paths.slice(1)) {
2365
+ let length = 0;
2366
+ while (length < common.length && length < path.length && common[length] === path[length]) length++;
2367
+ common.length = length;
2368
+ }
2369
+ return common;
2370
+ }
2371
+ function createDiagnosticCommand(command, name) {
2372
+ if (typeof command === "function") return Object.assign(create(), command, {
2373
+ name: command.commandName || name,
2374
+ run: void 0
2375
+ });
2376
+ return Object.assign(create(), command || {}, {
2377
+ name: command?.name || name,
2378
+ run: void 0
2379
+ });
2380
+ }
2381
+ function createCommandResolutionMessage(code, commandPath, candidatePaths) {
2382
+ switch (code) {
2383
+ case CommandResolutionErrorKeys.ambiguous: return `Ambiguous command resolution. Move options after the command name: ${candidatePaths}`;
2384
+ case CommandResolutionErrorKeys.lazySchemaMismatch: return `Lazy command schema mismatch at ${commandPath}. Declare leading options in the lazy definition or move options after the command name.`;
2385
+ default: return "The options do not identify a consistent command. Move options after the command name.";
2386
+ }
2387
+ }
2388
+ function createLazySchemaMismatchError(commandPath, loadedPath) {
2389
+ const expected = [...commandPath];
2390
+ const actual = [...loadedPath];
2391
+ return new CommandResolutionError(`Lazy command schema mismatch at ${expected.join(" ")}. Declare leading options in the lazy definition or move options after the command name.`, {
2392
+ code: CommandResolutionErrorKeys.lazySchemaMismatch,
2393
+ values: {
2394
+ commandPath: expected.join(" "),
2395
+ loadedCommandPath: actual.join(" ")
2396
+ },
2397
+ commandPath: expected,
2398
+ candidatePaths: [expected, actual]
2399
+ });
2400
+ }
1610
2401
  function createCommandNotFoundError(resolved) {
1611
2402
  const commandName = resolved.unresolvedCommandName || resolved.commandName || "";
1612
2403
  return new CommandNotFoundError(`Command not found: ${commandName}`, {