@gunshi/bone 0.37.2 → 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.
- package/lib/index.d.ts +217 -86
- package/lib/index.js +1060 -145
- package/package.json +5 -5
package/lib/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
//#region ../../node_modules/.pnpm/args-tokens@0.
|
|
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
|
|
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 &&
|
|
76
|
+
if (groupCount === 1 && hasShortGroupValue) {
|
|
77
77
|
value = remainings.shift();
|
|
78
|
-
|
|
79
|
-
|
|
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 (
|
|
106
|
-
else if (!allowCompatible && shortableOption.codePointAt(0) === EQUAL_CODE)
|
|
107
|
-
else
|
|
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
|
-
|
|
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`
|
|
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`
|
|
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.
|
|
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.
|
|
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,14 +278,31 @@ 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
|
/**
|
|
288
|
+
* Brand that marks {@link ArgsValidationError} instances.
|
|
289
|
+
*
|
|
290
|
+
* The brand is looked up in the global symbol registry with `Symbol.for`, so it stays
|
|
291
|
+
* identical across bundled copies of this module and across realms. It lets
|
|
292
|
+
* {@link isArgsValidationError} recognize errors created by another copy of `args-tokens`,
|
|
293
|
+
* where `instanceof` cannot match.
|
|
294
|
+
*/
|
|
295
|
+
const ARGS_VALIDATION_ERROR_BRAND = Symbol.for("args-tokens.ArgsValidationError");
|
|
296
|
+
/**
|
|
262
297
|
* An error that contains structured metadata for argument validation failures.
|
|
263
298
|
*
|
|
264
299
|
* The `message` remains the English fallback message. Renderers can use `code`
|
|
265
300
|
* and `values` to localize the error, falling back to `message` when localization
|
|
266
301
|
* is unavailable.
|
|
302
|
+
*
|
|
303
|
+
* Each instance carries a non-enumerable brand keyed by
|
|
304
|
+
* `Symbol.for('args-tokens.ArgsValidationError')`, which {@link isArgsValidationError}
|
|
305
|
+
* uses to recognize instances created by another bundled copy of `args-tokens`.
|
|
267
306
|
*/
|
|
268
307
|
var ArgsValidationError = class extends Error {
|
|
269
308
|
/**
|
|
@@ -287,18 +326,45 @@ var ArgsValidationError = class extends Error {
|
|
|
287
326
|
this.name = "ArgsValidationError";
|
|
288
327
|
this.code = options.code;
|
|
289
328
|
this.values = options.values ?? {};
|
|
329
|
+
Object.defineProperty(this, ARGS_VALIDATION_ERROR_BRAND, {
|
|
330
|
+
value: true,
|
|
331
|
+
enumerable: false,
|
|
332
|
+
writable: false,
|
|
333
|
+
configurable: false
|
|
334
|
+
});
|
|
290
335
|
}
|
|
291
336
|
};
|
|
292
337
|
/**
|
|
293
338
|
* Check whether the given value is an {@link ArgsValidationError}.
|
|
294
339
|
*
|
|
340
|
+
* This guard also recognizes errors created by another bundled copy of `args-tokens`
|
|
341
|
+
* (0.29.0 or later), where `instanceof` does not match. Such an error must have an own brand
|
|
342
|
+
* keyed by `Symbol.for('args-tokens.ArgsValidationError')` set to `true`, and a `values` object.
|
|
343
|
+
* The guard does not rely on `error.name`, so subclasses such as {@link ArgResolveError} that
|
|
344
|
+
* override `name` are still recognized.
|
|
345
|
+
*
|
|
346
|
+
* The guard narrows to `ArgsValidationError` only. Across bundled copies,
|
|
347
|
+
* `instanceof ArgResolveError` still does not match.
|
|
348
|
+
*
|
|
295
349
|
* @param error - value to check
|
|
296
350
|
* @returns `true` when the value is an `ArgsValidationError`
|
|
297
351
|
*/
|
|
298
|
-
function isArgsValidationError(error) {
|
|
299
|
-
|
|
352
|
+
function isArgsValidationError$1(error) {
|
|
353
|
+
if (error instanceof ArgsValidationError) return true;
|
|
354
|
+
if (typeof error !== "object" || error === null) return false;
|
|
355
|
+
if (!Object.hasOwn(error, ARGS_VALIDATION_ERROR_BRAND) || error[ARGS_VALIDATION_ERROR_BRAND] !== true) return false;
|
|
356
|
+
const values = error.values;
|
|
357
|
+
return typeof values === "object" && values !== null;
|
|
300
358
|
}
|
|
301
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
|
+
]);
|
|
302
368
|
/**
|
|
303
369
|
* Resolve command line arguments.
|
|
304
370
|
*
|
|
@@ -345,12 +411,13 @@ function resolveArgs(args, tokens, { shortGrouping = false, skipPositional = SKI
|
|
|
345
411
|
}
|
|
346
412
|
function checkLongTokenName(option, schema, token) {
|
|
347
413
|
if (token.rawName == void 0 || !hasLongOptionPrefix(token.rawName)) return false;
|
|
348
|
-
return token.name === option ||
|
|
414
|
+
return token.name === option || isNegatedToken(token, option, schema);
|
|
349
415
|
}
|
|
350
416
|
function toShortValue() {
|
|
351
417
|
if (expandableShortOptions.length === 0) return;
|
|
352
418
|
else {
|
|
353
|
-
|
|
419
|
+
let value = "";
|
|
420
|
+
for (let i = 0; i < expandableShortOptions.length; i++) value += expandableShortOptions[i].name ?? "";
|
|
354
421
|
expandableShortOptions.length = 0;
|
|
355
422
|
return value;
|
|
356
423
|
}
|
|
@@ -364,7 +431,7 @@ function resolveArgs(args, tokens, { shortGrouping = false, skipPositional = SKI
|
|
|
364
431
|
}
|
|
365
432
|
function applyShortOptionValue(value) {
|
|
366
433
|
if (currentShortOption) {
|
|
367
|
-
currentShortOption.value = value
|
|
434
|
+
currentShortOption.value = value ?? toShortValue();
|
|
368
435
|
optionTokens.push({ ...currentShortOption });
|
|
369
436
|
currentShortOption = void 0;
|
|
370
437
|
}
|
|
@@ -375,7 +442,15 @@ function resolveArgs(args, tokens, { shortGrouping = false, skipPositional = SKI
|
|
|
375
442
|
*/
|
|
376
443
|
const schemas = Object.values(args);
|
|
377
444
|
const booleanLongOptionNames = /* @__PURE__ */ new Set();
|
|
378
|
-
for (
|
|
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
|
+
}
|
|
379
454
|
if (schema.type !== "boolean") continue;
|
|
380
455
|
const arg = toKebab || schema.toKebab ? kebabnize(rawArg) : rawArg;
|
|
381
456
|
booleanLongOptionNames.add(arg);
|
|
@@ -385,12 +460,12 @@ function resolveArgs(args, tokens, { shortGrouping = false, skipPositional = SKI
|
|
|
385
460
|
for (let i = 0; i < tokens.length; i++) {
|
|
386
461
|
const token = tokens[i];
|
|
387
462
|
if (token.kind === "positional") {
|
|
388
|
-
if (terminated
|
|
463
|
+
if (terminated) {
|
|
389
464
|
rest.push(token.value);
|
|
390
465
|
continue;
|
|
391
466
|
}
|
|
392
467
|
if (currentShortOption) {
|
|
393
|
-
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) {
|
|
394
469
|
positionalTokens.push({ ...token });
|
|
395
470
|
applyShortOptionValue();
|
|
396
471
|
} else applyShortOptionValue(token.value);
|
|
@@ -402,11 +477,11 @@ function resolveArgs(args, tokens, { shortGrouping = false, skipPositional = SKI
|
|
|
402
477
|
} else positionalTokens.push({ ...token });
|
|
403
478
|
} else if (token.kind === "option") {
|
|
404
479
|
if (token.rawName) {
|
|
405
|
-
if (
|
|
480
|
+
if (token.rawName.startsWith("--")) {
|
|
406
481
|
applyLongOptionValue();
|
|
482
|
+
applyShortOptionValue();
|
|
407
483
|
if (token.inlineValue) optionTokens.push({ ...token });
|
|
408
484
|
else currentLongOption = { ...token };
|
|
409
|
-
applyShortOptionValue();
|
|
410
485
|
} else if (isShortOption(token.rawName)) {
|
|
411
486
|
if (currentShortOption) {
|
|
412
487
|
if (currentShortOption.index === token.index) {
|
|
@@ -427,8 +502,10 @@ function resolveArgs(args, tokens, { shortGrouping = false, skipPositional = SKI
|
|
|
427
502
|
}
|
|
428
503
|
}
|
|
429
504
|
} else {
|
|
430
|
-
if (currentShortOption && currentShortOption.index == token.index
|
|
431
|
-
|
|
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;
|
|
432
509
|
optionTokens.push({ ...currentShortOption });
|
|
433
510
|
currentShortOption = void 0;
|
|
434
511
|
}
|
|
@@ -462,36 +539,37 @@ function resolveArgs(args, tokens, { shortGrouping = false, skipPositional = SKI
|
|
|
462
539
|
return requiredPositionalsAfter[rawArg] ?? 0;
|
|
463
540
|
}
|
|
464
541
|
let positionalsCount = 0;
|
|
465
|
-
for (
|
|
542
|
+
for (let argIndex = 0; argIndex < argEntries.length; argIndex++) {
|
|
543
|
+
const entry = argEntries[argIndex];
|
|
544
|
+
const rawArg = entry[0];
|
|
545
|
+
const schema = entry[1];
|
|
466
546
|
const arg = getOptionName(rawArg, schema);
|
|
467
547
|
explicit[rawArg] = false;
|
|
468
548
|
if (schema.type === "positional") {
|
|
469
549
|
if (skipPositionalIndex > SKIP_POSITIONAL_DEFAULT) while (positionalsCount <= getPositionalSkipIndex()) positionalsCount++;
|
|
470
550
|
if (schema.multiple) {
|
|
471
551
|
const availablePositionals = Math.max(positionalTokens.length - positionalsCount, 0);
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
const
|
|
475
|
-
if (
|
|
476
|
-
const
|
|
477
|
-
|
|
478
|
-
const
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
if (error) errors.push(error);
|
|
483
|
-
else parsed.push(parsedValue);
|
|
484
|
-
}
|
|
485
|
-
values[rawArg] = parsed;
|
|
486
|
-
} else {
|
|
487
|
-
const valuesArray = [];
|
|
488
|
-
for (let i = positionalsCount; i < endPositionals; i++) valuesArray.push(positionalTokens[i].value);
|
|
489
|
-
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);
|
|
490
562
|
}
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
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;
|
|
494
571
|
} else if (schema.required) errors.push(createRequireError(rawArg, arg, schema));
|
|
572
|
+
else if (hasDefault(schema)) values[rawArg] = getDefaultValue(schema);
|
|
495
573
|
} else {
|
|
496
574
|
const positional = positionalTokens[positionalsCount];
|
|
497
575
|
if (shouldRequireMissingSinglePositional(schema)) {
|
|
@@ -523,27 +601,37 @@ function resolveArgs(args, tokens, { shortGrouping = false, skipPositional = SKI
|
|
|
523
601
|
continue;
|
|
524
602
|
}
|
|
525
603
|
}
|
|
604
|
+
let resolved = false;
|
|
526
605
|
for (let i = 0; i < optionTokens.length; i++) {
|
|
527
606
|
const token = optionTokens[i];
|
|
528
607
|
if (checkLongTokenName(arg, schema, token) || schema.short === token.name && token.rawName != void 0 && isShortOption(token.rawName)) {
|
|
529
|
-
const invalid = validateRequire(token, rawArg, arg, schema);
|
|
530
|
-
if (invalid) {
|
|
531
|
-
errors.push(invalid);
|
|
532
|
-
continue;
|
|
533
|
-
}
|
|
534
608
|
explicit[rawArg] = true;
|
|
535
609
|
const rawName = token.rawName;
|
|
536
610
|
const actualInputName = isShortOption(rawName) ? `-${token.name}` : rawName;
|
|
537
611
|
actualInputNames.set(rawArg, actualInputName);
|
|
538
|
-
const
|
|
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);
|
|
539
621
|
if (error) errors.push(error);
|
|
540
|
-
else
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
622
|
+
else {
|
|
623
|
+
resolved = true;
|
|
624
|
+
if (schema.multiple) {
|
|
625
|
+
values[rawArg] ||= [];
|
|
626
|
+
values[rawArg].push(parsedValue);
|
|
627
|
+
} else values[rawArg] = parsedValue;
|
|
628
|
+
}
|
|
544
629
|
}
|
|
545
630
|
}
|
|
546
|
-
if (
|
|
631
|
+
if (!resolved && schema.default != null) {
|
|
632
|
+
if (hasDefaultOutsideChoices(schema)) errors.push(createDefaultChoiceError(rawArg, arg, schema));
|
|
633
|
+
else values[rawArg] = getDefaultValue(schema);
|
|
634
|
+
}
|
|
547
635
|
}
|
|
548
636
|
const conflictErrors = checkConflicts(args, explicit, toKebab, actualInputNames);
|
|
549
637
|
errors.push(...conflictErrors);
|
|
@@ -555,27 +643,73 @@ function resolveArgs(args, tokens, { shortGrouping = false, skipPositional = SKI
|
|
|
555
643
|
explicit
|
|
556
644
|
};
|
|
557
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
|
+
*/
|
|
558
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)];
|
|
559
674
|
if (typeof schema.parse === "function") {
|
|
560
675
|
if (schema.type === "boolean") {
|
|
561
|
-
const boolValue =
|
|
676
|
+
const [boolValue, error] = resolveBooleanValue(token, rawArg, option, schema);
|
|
677
|
+
if (error) return [void 0, error];
|
|
562
678
|
return parseSchemaValue(String(boolValue), rawArg, option, schema);
|
|
563
679
|
}
|
|
564
|
-
return parseSchemaValue(token.value
|
|
680
|
+
return parseSchemaValue(token.value, rawArg, option, schema);
|
|
565
681
|
}
|
|
566
682
|
switch (schema.type) {
|
|
567
|
-
case "string": return typeof token.value === "string" ? [token.value
|
|
568
|
-
case "boolean": return
|
|
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);
|
|
569
685
|
case "number":
|
|
570
|
-
if (!isNumeric(token.value)) return [void 0, createTypeError(rawArg, option, schema, token.value)];
|
|
571
|
-
return
|
|
572
|
-
case "enum":
|
|
573
|
-
if (schema.choices && !schema.choices.includes(token.value)) return [void 0, createChoiceError(rawArg, option, schema, token.value)];
|
|
574
|
-
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];
|
|
575
689
|
case "custom": throw new TypeError(`argument '${option}' should have a 'parse' function`);
|
|
576
690
|
default: throw new Error(`Unsupported argument type '${schema.type}' for option '${option}'`);
|
|
577
691
|
}
|
|
578
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
|
+
}
|
|
579
713
|
function parseSchemaValue(value, rawArg, option, schema) {
|
|
580
714
|
try {
|
|
581
715
|
return [schema.parse(value), void 0];
|
|
@@ -586,7 +720,10 @@ function parseSchemaValue(value, rawArg, option, schema) {
|
|
|
586
720
|
function createRequireError(rawArg, option, schema) {
|
|
587
721
|
return new ArgResolveError(schema.type === "positional" ? `Positional argument '${option}' is required` : `Optional argument ${createOptionDisplayName(option, schema)} is required`, option, "required", schema, {
|
|
588
722
|
code: schema.type === "positional" ? ArgsValidationErrorKeys.requiredPositional : ArgsValidationErrorKeys.requiredOption,
|
|
589
|
-
values: schema.type === "positional" ? {
|
|
723
|
+
values: schema.type === "positional" ? {
|
|
724
|
+
displayName: createArgumentDisplayName(option, schema),
|
|
725
|
+
name: rawArg
|
|
726
|
+
} : {
|
|
590
727
|
displayName: createOptionDisplayName(option, schema),
|
|
591
728
|
name: rawArg
|
|
592
729
|
}
|
|
@@ -602,6 +739,46 @@ function resolveSinglePositionalValue(values, errors, rawArg, option, schema, po
|
|
|
602
739
|
function hasDefault(schema) {
|
|
603
740
|
return schema.default != null;
|
|
604
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
|
+
}
|
|
605
782
|
function shouldRequireMissingSinglePositional(schema) {
|
|
606
783
|
if (schema.required === true) return true;
|
|
607
784
|
if (schema.required === false) return false;
|
|
@@ -625,9 +802,18 @@ function createRequiredPositionalsAfter(argEntries) {
|
|
|
625
802
|
}
|
|
626
803
|
/**
|
|
627
804
|
* An error that occurs when resolving arguments.
|
|
628
|
-
*
|
|
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()`.
|
|
629
808
|
*/
|
|
630
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
|
+
*/
|
|
631
817
|
name;
|
|
632
818
|
schema;
|
|
633
819
|
type;
|
|
@@ -635,7 +821,7 @@ var ArgResolveError = class extends ArgsValidationError {
|
|
|
635
821
|
* Create an `ArgResolveError` instance.
|
|
636
822
|
*
|
|
637
823
|
* @param message - the error message
|
|
638
|
-
* @param name - the name of the argument
|
|
824
|
+
* @param name - the name of the argument on the command line, in kebab-case with `toKebab`
|
|
639
825
|
* @param type - the type of the error: 'type', 'required', or 'conflict'
|
|
640
826
|
* @param schema - the argument schema that caused the error
|
|
641
827
|
* @param options - structured validation metadata
|
|
@@ -653,17 +839,166 @@ function validateRequire(token, rawArg, option, schema) {
|
|
|
653
839
|
function isNumeric(str) {
|
|
654
840
|
return str.trim() !== "" && !isNaN(str);
|
|
655
841
|
}
|
|
656
|
-
function createTypeError(rawArg, option, schema, actual) {
|
|
657
|
-
return new ArgResolveError(`Optional argument ${createOptionDisplayName(option, schema)} should be '${
|
|
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, {
|
|
658
844
|
code: ArgsValidationErrorKeys.invalidType,
|
|
659
845
|
values: {
|
|
660
846
|
displayName: createOptionDisplayName(option, schema),
|
|
661
847
|
name: rawArg,
|
|
662
|
-
expected
|
|
848
|
+
expected,
|
|
663
849
|
...actual != null ? { actual } : {}
|
|
664
850
|
}
|
|
665
851
|
});
|
|
666
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
|
+
}
|
|
667
1002
|
function createChoiceError(rawArg, option, schema, actual) {
|
|
668
1003
|
const choices = schema.choices ?? [];
|
|
669
1004
|
return new ArgResolveError(`Optional argument ${createOptionDisplayName(option, schema)} should be chosen from '${schema.type}' [${formatChoices(choices)}] values`, option, "type", schema, {
|
|
@@ -678,11 +1013,35 @@ function createChoiceError(rawArg, option, schema, actual) {
|
|
|
678
1013
|
}
|
|
679
1014
|
});
|
|
680
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
|
+
}
|
|
681
1042
|
function createCustomParseError(error, rawArg, option, schema, value) {
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
return error;
|
|
685
|
-
}
|
|
1043
|
+
const reused = reuseValidationError(error, rawArg, option, schema, value);
|
|
1044
|
+
if (reused) return reused;
|
|
686
1045
|
const reason = getErrorReason(error);
|
|
687
1046
|
return new ArgsValidationError(reason, {
|
|
688
1047
|
code: ArgsValidationErrorKeys.customParse,
|
|
@@ -694,6 +1053,26 @@ function createCustomParseError(error, rawArg, option, schema, value) {
|
|
|
694
1053
|
cause: error
|
|
695
1054
|
});
|
|
696
1055
|
}
|
|
1056
|
+
/**
|
|
1057
|
+
* Reuse an {@link ArgsValidationError} thrown from a custom `parse` function, filling in missing values.
|
|
1058
|
+
*
|
|
1059
|
+
* @param error - The value thrown from `parse`
|
|
1060
|
+
* @param rawArg - The argument key in the schema
|
|
1061
|
+
* @param option - The option name used on the command line
|
|
1062
|
+
* @param schema - The argument schema
|
|
1063
|
+
* @param value - The raw input value
|
|
1064
|
+
* @returns The same error when it can be reused, otherwise `undefined` so the caller wraps it.
|
|
1065
|
+
* Inspecting or updating the thrown value can throw, for example when its `values` object is frozen
|
|
1066
|
+
* or an accessor throws; such values are not reused, so a custom `parse` cannot make `resolveArgs` throw this way.
|
|
1067
|
+
*/
|
|
1068
|
+
function reuseValidationError(error, rawArg, option, schema, value) {
|
|
1069
|
+
try {
|
|
1070
|
+
if (isArgsValidationError$1(error)) {
|
|
1071
|
+
augmentValidationError(error, rawArg, option, schema, value);
|
|
1072
|
+
return error;
|
|
1073
|
+
}
|
|
1074
|
+
} catch {}
|
|
1075
|
+
}
|
|
697
1076
|
function augmentValidationError(error, rawArg, option, schema, value) {
|
|
698
1077
|
const values = error.values;
|
|
699
1078
|
values.name ??= rawArg;
|
|
@@ -709,6 +1088,35 @@ function createArgumentDisplayName(option, schema) {
|
|
|
709
1088
|
function createOptionDisplayName(option, schema) {
|
|
710
1089
|
return `'--${option}'${schema.short ? ` or '-${schema.short}'` : ""}`;
|
|
711
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
|
+
}
|
|
712
1120
|
function checkConflicts(args, explicit, toKebab, actualInputNames) {
|
|
713
1121
|
for (const rawArg in args) {
|
|
714
1122
|
const schema = args[rawArg];
|
|
@@ -720,13 +1128,13 @@ function checkConflicts(args, explicit, toKebab, actualInputNames) {
|
|
|
720
1128
|
if (!explicit[conflictingArg]) continue;
|
|
721
1129
|
const arg = toKebab || schema.toKebab ? kebabnize(rawArg) : rawArg;
|
|
722
1130
|
const conflictingArgKebab = toKebab || args[conflictingArg]?.toKebab ? kebabnize(conflictingArg) : conflictingArg;
|
|
723
|
-
return [
|
|
1131
|
+
return [createConflictError(rawArg, arg, schema, schema.type === "positional" ? arg : actualInputNames.get(rawArg) || `--${arg}`, conflictingArg, args[conflictingArg]?.type === "positional" ? conflictingArgKebab : actualInputNames.get(conflictingArg) || `--${conflictingArgKebab}`)];
|
|
724
1132
|
}
|
|
725
1133
|
}
|
|
726
1134
|
return [];
|
|
727
1135
|
}
|
|
728
1136
|
//#endregion
|
|
729
|
-
//#region ../../node_modules/.pnpm/args-tokens@0.
|
|
1137
|
+
//#region ../../node_modules/.pnpm/args-tokens@1.0.0-beta.1/node_modules/args-tokens/lib/index.js
|
|
730
1138
|
/**
|
|
731
1139
|
* @author kazuya kawaguchi (a.k.a. kazupon)
|
|
732
1140
|
* @license MIT
|
|
@@ -774,14 +1182,20 @@ const CLI_OPTIONS_DEFAULT = {
|
|
|
774
1182
|
* Check if the given command is a {@link LazyCommand}.
|
|
775
1183
|
*
|
|
776
1184
|
* @param cmd - A command to check
|
|
777
|
-
* @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.
|
|
778
1189
|
*/
|
|
779
1190
|
function isLazyCommand(cmd) {
|
|
780
|
-
return typeof cmd === "function" && "commandName" in cmd
|
|
1191
|
+
return typeof cmd === "function" && "commandName" in cmd;
|
|
781
1192
|
}
|
|
782
1193
|
/**
|
|
783
1194
|
* Resolve a lazy command to a {@link Command}.
|
|
784
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
|
+
*
|
|
785
1199
|
* @param cmd - A {@link Commandable} or {@link LazyCommand} to resolve
|
|
786
1200
|
* @param name - Optional name of the command, if not provided, it will use the name from the command itself.
|
|
787
1201
|
* @param needRunResolving - Whether to run the resolving function of the lazy command.
|
|
@@ -797,6 +1211,8 @@ async function resolveLazyCommand(cmd, name, needRunResolving = false) {
|
|
|
797
1211
|
examples: cmd.examples,
|
|
798
1212
|
internal: cmd.internal,
|
|
799
1213
|
entry: cmd.entry,
|
|
1214
|
+
toKebab: cmd.toKebab,
|
|
1215
|
+
rendering: cmd.rendering,
|
|
800
1216
|
subCommands: cmd.subCommands
|
|
801
1217
|
};
|
|
802
1218
|
if ("resource" in cmd && cmd.resource) baseCommand.resource = cmd.resource;
|
|
@@ -806,13 +1222,20 @@ async function resolveLazyCommand(cmd, name, needRunResolving = false) {
|
|
|
806
1222
|
if (typeof loaded === "function") command.run = loaded;
|
|
807
1223
|
else if (typeof loaded === "object") {
|
|
808
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
|
+
*/
|
|
809
1230
|
command.run = loaded.run;
|
|
810
|
-
command.name = loaded.name;
|
|
811
|
-
command.description = loaded.description;
|
|
812
|
-
command.args = loaded.args;
|
|
813
|
-
command.examples = loaded.examples;
|
|
814
|
-
command.internal = loaded.internal;
|
|
815
|
-
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;
|
|
816
1239
|
command.subCommands = loaded.subCommands || cmd.subCommands;
|
|
817
1240
|
if ("resource" in loaded && loaded.resource) command.resource = loaded.resource;
|
|
818
1241
|
} else throw new TypeError(`Cannot resolve command: ${cmd.name || name}`);
|
|
@@ -831,6 +1254,37 @@ function create(obj = null) {
|
|
|
831
1254
|
return Object.create(obj);
|
|
832
1255
|
}
|
|
833
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
|
+
/**
|
|
834
1288
|
* Log a message to the console.
|
|
835
1289
|
*
|
|
836
1290
|
* @param args - Arguments to log
|
|
@@ -953,7 +1407,7 @@ async function createCommandContext({ args = {}, explicit = {}, values = {}, pos
|
|
|
953
1407
|
if (extension.onFactory) await extension.onFactory(core, command);
|
|
954
1408
|
}
|
|
955
1409
|
}
|
|
956
|
-
return deepFreeze(core, ["extensions"]);
|
|
1410
|
+
return deepFreeze(core, ["extensions", "entryCommand"]);
|
|
957
1411
|
}
|
|
958
1412
|
function getCommandName(cmd) {
|
|
959
1413
|
if (isLazyCommand(cmd)) return cmd.commandName || cmd.name || "(anonymous)";
|
|
@@ -1039,7 +1493,33 @@ function createDecorators() {
|
|
|
1039
1493
|
*/
|
|
1040
1494
|
const CommandNotFoundErrorKeys = { notFound: "err:cmd:not-found" };
|
|
1041
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
|
+
/**
|
|
1508
|
+
* Brand that marks {@link CommandNotFoundError} instances.
|
|
1509
|
+
*
|
|
1510
|
+
* The brand is looked up in the global symbol registry with `Symbol.for`, so it stays
|
|
1511
|
+
* identical across bundled copies of gunshi (`gunshi`, `@gunshi/plugin`, `@gunshi/bone`)
|
|
1512
|
+
* and across realms. It lets {@link isCommandNotFoundError} recognize errors created by
|
|
1513
|
+
* another copy, where `instanceof` cannot match.
|
|
1514
|
+
*/
|
|
1515
|
+
const COMMAND_NOT_FOUND_ERROR_BRAND = Symbol.for("gunshi.CommandNotFoundError");
|
|
1516
|
+
const COMMAND_RESOLUTION_ERROR_BRAND = Symbol.for("gunshi.CommandResolutionError");
|
|
1517
|
+
/**
|
|
1042
1518
|
* Error raised when a command cannot be resolved.
|
|
1519
|
+
*
|
|
1520
|
+
* Each instance carries a non-enumerable brand keyed by
|
|
1521
|
+
* `Symbol.for('gunshi.CommandNotFoundError')`, so that {@link isCommandNotFoundError}
|
|
1522
|
+
* recognizes it even when it was created by another bundled copy of gunshi.
|
|
1043
1523
|
*/
|
|
1044
1524
|
var CommandNotFoundError = class extends Error {
|
|
1045
1525
|
code;
|
|
@@ -1061,16 +1541,124 @@ var CommandNotFoundError = class extends Error {
|
|
|
1061
1541
|
this.commandName = options.commandName;
|
|
1062
1542
|
this.candidates = options.candidates || [];
|
|
1063
1543
|
this.commandPath = options.commandPath || [];
|
|
1544
|
+
Object.defineProperty(this, COMMAND_NOT_FOUND_ERROR_BRAND, {
|
|
1545
|
+
value: true,
|
|
1546
|
+
enumerable: false,
|
|
1547
|
+
writable: false,
|
|
1548
|
+
configurable: false
|
|
1549
|
+
});
|
|
1550
|
+
}
|
|
1551
|
+
};
|
|
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
|
+
});
|
|
1064
1583
|
}
|
|
1065
1584
|
};
|
|
1066
1585
|
/**
|
|
1067
1586
|
* Check whether an error is a {@link CommandNotFoundError}.
|
|
1068
1587
|
*
|
|
1588
|
+
* `instanceof` alone is not enough: `@gunshi/plugin` is bundled with its own copy of this
|
|
1589
|
+
* class (`noExternal: ['gunshi/plugin']`), so an error thrown by `gunshi` is never an instance
|
|
1590
|
+
* of the class a plugin imports. Errors from another copy are recognized through the
|
|
1591
|
+
* `Symbol.for('gunshi.CommandNotFoundError')` brand, which does not depend on `error.name`.
|
|
1592
|
+
*
|
|
1069
1593
|
* @param error - An unknown error
|
|
1070
1594
|
* @returns `true` if the error is a {@link CommandNotFoundError}
|
|
1071
1595
|
*/
|
|
1072
1596
|
function isCommandNotFoundError(error) {
|
|
1073
|
-
|
|
1597
|
+
if (error instanceof CommandNotFoundError) return true;
|
|
1598
|
+
if (!isRecord(error) || !hasCommandNotFoundErrorShape(error)) return false;
|
|
1599
|
+
if (Object.hasOwn(error, COMMAND_NOT_FOUND_ERROR_BRAND) && error[COMMAND_NOT_FOUND_ERROR_BRAND] === true) return true;
|
|
1600
|
+
return error instanceof Error && error.name === "CommandNotFoundError";
|
|
1601
|
+
}
|
|
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
|
+
/**
|
|
1614
|
+
* Check whether an error is an {@link ArgsValidationError}.
|
|
1615
|
+
*
|
|
1616
|
+
* Prefer this over the `args-tokens` guard of the same name. Both recognize errors from another
|
|
1617
|
+
* bundled copy through the `Symbol.for('args-tokens.ArgsValidationError')` brand that
|
|
1618
|
+
* `args-tokens` 0.29.0 or later sets, including subclasses such as `ArgResolveError` that
|
|
1619
|
+
* override `name` with the argument name. This guard additionally:
|
|
1620
|
+
*
|
|
1621
|
+
* - recognizes direct `ArgsValidationError` instances from copies bundling `args-tokens`
|
|
1622
|
+
* older than 0.29.0, which do not set the brand
|
|
1623
|
+
* - checks that `code` and `values` of an error from another copy have the expected types
|
|
1624
|
+
*
|
|
1625
|
+
* The guard narrows only to {@link ArgsValidationError}: across copies,
|
|
1626
|
+
* `instanceof ArgResolveError` still fails, so do not rely on `type` or `schema` for such errors.
|
|
1627
|
+
*
|
|
1628
|
+
* @param error - An unknown error
|
|
1629
|
+
* @returns `true` if the error is an {@link ArgsValidationError}
|
|
1630
|
+
*/
|
|
1631
|
+
function isArgsValidationError(error) {
|
|
1632
|
+
if (error instanceof ArgsValidationError) return true;
|
|
1633
|
+
if (!isRecord(error) || !hasArgsValidationErrorShape(error)) return false;
|
|
1634
|
+
if (isArgsValidationError$1(error)) return true;
|
|
1635
|
+
return error instanceof Error && error.name === "ArgsValidationError";
|
|
1636
|
+
}
|
|
1637
|
+
function isRecord(value) {
|
|
1638
|
+
return typeof value === "object" && value !== null;
|
|
1639
|
+
}
|
|
1640
|
+
function isStringArray(value) {
|
|
1641
|
+
return Array.isArray(value) && value.every((item) => typeof item === "string");
|
|
1642
|
+
}
|
|
1643
|
+
/**
|
|
1644
|
+
* Check whether `code` is an own or inherited property that is a string or `undefined`.
|
|
1645
|
+
*
|
|
1646
|
+
* Constructors always assign `code`, even when the option is omitted.
|
|
1647
|
+
*
|
|
1648
|
+
* @param error - An error from another copy
|
|
1649
|
+
* @returns `true` if `code` has the expected type
|
|
1650
|
+
*/
|
|
1651
|
+
function hasOptionalStringCode(error) {
|
|
1652
|
+
return "code" in error && (error.code === void 0 || typeof error.code === "string");
|
|
1653
|
+
}
|
|
1654
|
+
function hasCommandNotFoundErrorShape(error) {
|
|
1655
|
+
return hasOptionalStringCode(error) && isRecord(error.values) && typeof error.commandName === "string" && isStringArray(error.candidates) && isStringArray(error.commandPath);
|
|
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
|
+
}
|
|
1660
|
+
function hasArgsValidationErrorShape(error) {
|
|
1661
|
+
return hasOptionalStringCode(error) && isRecord(error.values);
|
|
1074
1662
|
}
|
|
1075
1663
|
/**
|
|
1076
1664
|
* Check whether validation errors should be handled before version, help, or command execution.
|
|
@@ -1079,7 +1667,7 @@ function isCommandNotFoundError(error) {
|
|
|
1079
1667
|
* @returns `true` if the validation error must be handled with priority
|
|
1080
1668
|
*/
|
|
1081
1669
|
function hasPriorityValidationError(error) {
|
|
1082
|
-
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;
|
|
1083
1671
|
}
|
|
1084
1672
|
//#endregion
|
|
1085
1673
|
//#region ../gunshi/src/plugin/context.ts
|
|
@@ -1112,6 +1700,22 @@ function createPluginContext(decorators, initialSubCommands) {
|
|
|
1112
1700
|
addGlobalOption(name, schema) {
|
|
1113
1701
|
if (!name) throw new Error("Option name must be a non-empty string");
|
|
1114
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
|
+
}
|
|
1115
1719
|
globalOptions.set(name, schema);
|
|
1116
1720
|
},
|
|
1117
1721
|
get subCommands() {
|
|
@@ -1139,6 +1743,16 @@ function createPluginContext(decorators, initialSubCommands) {
|
|
|
1139
1743
|
}
|
|
1140
1744
|
});
|
|
1141
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
|
+
}
|
|
1142
1756
|
//#endregion
|
|
1143
1757
|
//#region ../gunshi/src/plugin/dependency.ts
|
|
1144
1758
|
/**
|
|
@@ -1156,12 +1770,13 @@ function resolveDependencies(plugins) {
|
|
|
1156
1770
|
const visited = /* @__PURE__ */ new Set();
|
|
1157
1771
|
const visiting = /* @__PURE__ */ new Set();
|
|
1158
1772
|
const pluginMap = /* @__PURE__ */ new Map();
|
|
1159
|
-
for (const plugin of plugins)
|
|
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");
|
|
1160
1775
|
if (pluginMap.has(plugin.id)) console.warn(`Duplicate plugin id detected: \`${plugin.id}\``);
|
|
1161
1776
|
pluginMap.set(plugin.id, plugin);
|
|
1162
1777
|
}
|
|
1163
1778
|
function visit(plugin) {
|
|
1164
|
-
if (
|
|
1779
|
+
if (typeof plugin.id !== "string" || plugin.id.length === 0) throw new Error("Plugin id must be a non-empty string");
|
|
1165
1780
|
if (visited.has(plugin.id)) return;
|
|
1166
1781
|
if (visiting.has(plugin.id)) throw new Error(`Circular dependency detected: \`${[...visiting].join(` -> `) + " -> " + plugin.id}\``);
|
|
1167
1782
|
visiting.add(plugin.id);
|
|
@@ -1195,15 +1810,30 @@ function resolveDependencies(plugins) {
|
|
|
1195
1810
|
* @param entry - A {@link Command | entry command}, an {@link CommandRunner | inline command runner}, or a {@link LazyCommand | lazily-loaded command}
|
|
1196
1811
|
* @param options - A {@link CliOptions | CLI options}
|
|
1197
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
|
|
1198
1814
|
* @returns A rendered usage or undefined. if you will use {@link CliOptions.usageSilent} option, it will return rendered usage string.
|
|
1199
1815
|
*/
|
|
1200
|
-
async function cliCore(argv, entry, options, plugins) {
|
|
1816
|
+
async function cliCore(argv, entry, options, plugins, usageOnly = false) {
|
|
1201
1817
|
const decorators = createDecorators();
|
|
1202
|
-
|
|
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);
|
|
1203
1826
|
const resolvedPlugins = await applyPlugins(pluginContext, [...plugins, ...options.plugins || []]);
|
|
1204
|
-
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;
|
|
1205
1834
|
const tokens = parseArgs(argv);
|
|
1206
|
-
const
|
|
1835
|
+
const selection = resolveCommandSelection(tokens, entry, cliOptions, pluginContext.globalOptions);
|
|
1836
|
+
const resolved = selection.context;
|
|
1207
1837
|
const { commandName: name, command, callMode, commandPath, depth, levelSubCommands } = resolved;
|
|
1208
1838
|
let targetCommand = command;
|
|
1209
1839
|
let targetCommandName = name;
|
|
@@ -1212,7 +1842,7 @@ async function cliCore(argv, entry, options, plugins) {
|
|
|
1212
1842
|
let targetDepth = depth;
|
|
1213
1843
|
let targetOmitted = resolved.omitted;
|
|
1214
1844
|
let targetLevelSubCommands = levelSubCommands;
|
|
1215
|
-
const additionalValidationErrors = [];
|
|
1845
|
+
const additionalValidationErrors = selection.error ? [selection.error] : [];
|
|
1216
1846
|
if (!targetCommand) {
|
|
1217
1847
|
if (!resolved.parentCommand || !resolved.unresolvedCommandName) throw new Error(`Command not found: ${name || ""}`);
|
|
1218
1848
|
targetCommand = resolved.parentCommand;
|
|
@@ -1224,16 +1854,34 @@ async function cliCore(argv, entry, options, plugins) {
|
|
|
1224
1854
|
targetLevelSubCommands = resolved.parentSubCommands;
|
|
1225
1855
|
additionalValidationErrors.push(createCommandNotFoundError(resolved));
|
|
1226
1856
|
}
|
|
1857
|
+
const routingOptions = Object.assign(create(), cliOptions, { subCommands: new Map(cliOptions.subCommands) });
|
|
1227
1858
|
if (targetLevelSubCommands) cliOptions.subCommands = targetLevelSubCommands;
|
|
1228
1859
|
const resolvedCommand = isLazyCommand(targetCommand) ? await resolveLazyCommand(targetCommand, targetCommandName, true) : targetCommand;
|
|
1229
|
-
|
|
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);
|
|
1230
1871
|
const skipPositional = targetDepth > 0 ? targetDepth - 1 : -1;
|
|
1231
|
-
const
|
|
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, {
|
|
1232
1880
|
shortGrouping: true,
|
|
1233
1881
|
toKebab: resolvedCommand.toKebab,
|
|
1234
1882
|
skipPositional
|
|
1235
1883
|
});
|
|
1236
|
-
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 })) : []]);
|
|
1237
1885
|
return await executeCommand(resolvedCommand, await createCommandContext({
|
|
1238
1886
|
args,
|
|
1239
1887
|
explicit,
|
|
@@ -1251,11 +1899,35 @@ async function cliCore(argv, entry, options, plugins) {
|
|
|
1251
1899
|
cliOptions
|
|
1252
1900
|
}), decorators.commandDecorators);
|
|
1253
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
|
+
}
|
|
1254
1927
|
async function applyPlugins(pluginContext, plugins) {
|
|
1255
1928
|
const sortedPlugins = resolveDependencies(plugins);
|
|
1256
|
-
try {
|
|
1257
|
-
|
|
1258
|
-
/**
|
|
1929
|
+
for (const plugin of sortedPlugins) try {
|
|
1930
|
+
/**
|
|
1259
1931
|
* NOTE(kazupon):
|
|
1260
1932
|
* strictly `Args` are not required for plugin installation.
|
|
1261
1933
|
* because the strictly `Args` required by each plugin are unknown,
|
|
@@ -1263,18 +1935,39 @@ async function applyPlugins(pluginContext, plugins) {
|
|
|
1263
1935
|
*/
|
|
1264
1936
|
await plugin(pluginContext);
|
|
1265
1937
|
} catch (error) {
|
|
1266
|
-
|
|
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 });
|
|
1267
1947
|
}
|
|
1268
1948
|
return sortedPlugins;
|
|
1269
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
|
+
}
|
|
1270
1966
|
function getCommandArgs(cmd) {
|
|
1271
1967
|
if (isLazyCommand(cmd)) return cmd.args || create();
|
|
1272
1968
|
else if (typeof cmd === "object") return cmd.args || create();
|
|
1273
1969
|
else return create();
|
|
1274
1970
|
}
|
|
1275
|
-
function resolveArguments(pluginContext, args) {
|
|
1276
|
-
return Object.assign(create(), Object.fromEntries(pluginContext.globalOptions), args);
|
|
1277
|
-
}
|
|
1278
1971
|
const NEGATABLE_OPTION_PREFIX = "no-";
|
|
1279
1972
|
function findUnknownOptions(args, tokens, options) {
|
|
1280
1973
|
const knownLongOptions = /* @__PURE__ */ new Set();
|
|
@@ -1292,12 +1985,16 @@ function findUnknownOptions(args, tokens, options) {
|
|
|
1292
1985
|
if (schema.type === "positional") continue;
|
|
1293
1986
|
const optionName = resolveOptionName(name, schema, options);
|
|
1294
1987
|
knownLongOptions.add(optionName);
|
|
1295
|
-
|
|
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);
|
|
1296
1993
|
if (schema.short) knownShortOptions.add(schema.short);
|
|
1297
1994
|
if (schema.type === "boolean" && schema.negatable) {
|
|
1298
1995
|
const negatableOptionName = `${NEGATABLE_OPTION_PREFIX}${optionName}`;
|
|
1299
1996
|
knownNegatableOptions.add(negatableOptionName);
|
|
1300
|
-
addLongOptionCandidate(negatableOptionName);
|
|
1997
|
+
if (!schema.hidden) addLongOptionCandidate(negatableOptionName);
|
|
1301
1998
|
}
|
|
1302
1999
|
}
|
|
1303
2000
|
const unknownOptions = [];
|
|
@@ -1336,45 +2033,60 @@ function mergeValidationErrors(error, additionalErrors) {
|
|
|
1336
2033
|
return new AggregateError(error ? [...error.errors, ...additionalErrors] : additionalErrors, error?.message || additionalErrors[0]?.message);
|
|
1337
2034
|
}
|
|
1338
2035
|
const isObject = (val) => val !== null && typeof val === "object";
|
|
1339
|
-
|
|
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) {
|
|
1340
2053
|
const hasSubCommands = options.subCommands ? options.subCommands instanceof Map ? options.subCommands.size > 0 : isObject(options.subCommands) && Object.keys(options.subCommands).length > 0 : false;
|
|
1341
2054
|
const subCommands = new Map(options.subCommands instanceof Map ? options.subCommands : []);
|
|
1342
2055
|
if (!(options.subCommands instanceof Map) && isObject(options.subCommands)) for (const [name, cmd] of Object.entries(options.subCommands)) subCommands.set(name, cmd);
|
|
1343
|
-
if (hasSubCommands)
|
|
1344
|
-
if (isLazyCommand(entryCmd)) {
|
|
1345
|
-
const entryCopy = Object.assign((...args) => entryCmd(...args), entryCmd, { entry: true });
|
|
1346
|
-
subCommands.set(resolveEntryName(entryCopy), entryCopy);
|
|
1347
|
-
} else if (typeof entryCmd === "object") {
|
|
1348
|
-
const entryCopy = Object.assign(create(), entryCmd, { entry: true });
|
|
1349
|
-
subCommands.set(resolveEntryName(entryCopy), entryCopy);
|
|
1350
|
-
} else if (typeof entryCmd === "function") {
|
|
1351
|
-
const name = entryCmd.name || "(anonymous)";
|
|
1352
|
-
subCommands.set(name, {
|
|
1353
|
-
run: entryCmd,
|
|
1354
|
-
name,
|
|
1355
|
-
entry: true
|
|
1356
|
-
});
|
|
1357
|
-
}
|
|
1358
|
-
}
|
|
2056
|
+
if (hasSubCommands && entryCommand) subCommands.set(resolveEntryName(entryCommand), entryCommand);
|
|
1359
2057
|
return subCommands;
|
|
1360
2058
|
}
|
|
1361
|
-
function normalizeCliOptions(options, decorators, pluginContext) {
|
|
2059
|
+
function normalizeCliOptions(options, decorators, pluginContext, entryCommand) {
|
|
1362
2060
|
const subCommands = new Map(pluginContext.subCommands);
|
|
1363
|
-
|
|
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
|
+
});
|
|
1364
2069
|
if (resolvedOptions.renderHeader === void 0) resolvedOptions.renderHeader = decorators.getHeaderRenderer();
|
|
1365
2070
|
if (resolvedOptions.renderUsage === void 0) resolvedOptions.renderUsage = decorators.getUsageRenderer();
|
|
1366
2071
|
if (resolvedOptions.renderValidationErrors === void 0) resolvedOptions.renderValidationErrors = decorators.getValidationErrorsRenderer();
|
|
1367
2072
|
return resolvedOptions;
|
|
1368
2073
|
}
|
|
1369
2074
|
function getPositionalTokens(tokens) {
|
|
1370
|
-
|
|
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;
|
|
1371
2081
|
}
|
|
1372
2082
|
function resolveCommandTree(tokens, entry, options) {
|
|
1373
|
-
|
|
2083
|
+
return resolveCommandTreeFromPositionals(getPositionalTokens(tokens), entry, options);
|
|
2084
|
+
}
|
|
2085
|
+
function resolveCommandTreeFromPositionals(positionals, entry, options) {
|
|
1374
2086
|
function resolveAsEntry() {
|
|
1375
2087
|
if (typeof entry === "function") {
|
|
1376
|
-
if (
|
|
1377
|
-
commandName: entry
|
|
2088
|
+
if (isLazyCommand(entry)) return {
|
|
2089
|
+
commandName: resolveEntryName(entry),
|
|
1378
2090
|
command: entry,
|
|
1379
2091
|
callMode: "entry",
|
|
1380
2092
|
commandPath: [],
|
|
@@ -1483,6 +2195,209 @@ function resolveCommandTree(tokens, entry, options) {
|
|
|
1483
2195
|
levelSubCommands
|
|
1484
2196
|
};
|
|
1485
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
|
+
}
|
|
1486
2401
|
function createCommandNotFoundError(resolved) {
|
|
1487
2402
|
const commandName = resolved.unresolvedCommandName || resolved.commandName || "";
|
|
1488
2403
|
return new CommandNotFoundError(`Command not found: ${commandName}`, {
|