@gunshi/plugin 0.37.3 → 1.0.0-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- //#region ../../node_modules/.pnpm/args-tokens@0.29.0/node_modules/args-tokens/lib/parser-DT7Ztcch.d.ts
1
+ //#region ../../node_modules/.pnpm/args-tokens@1.0.0-beta.1/node_modules/args-tokens/lib/parser-DhESN1gR.d.ts
2
2
  //#region src/parser.d.ts
3
3
  /**
4
4
  * Entry point of argument parser.
@@ -42,20 +42,24 @@ interface ArgToken {
42
42
  */
43
43
  rawName?: string;
44
44
  /**
45
- * Option value, e.g. `--foo=bar` => `bar`, `-x=bar` => `bar`.
45
+ * Option value, e.g. `--foo=bar` => `bar`. The value of a short option, such as `bar` of
46
+ * `-x=bar`, `-1` of `-x=-1` or `-x-1`, and `''` of `-x=`, is in a token of its own after the
47
+ * option, which has no `name` and `rawName`.
46
48
  * If the `allowCompatible` option is `true`, short option value will be same as Node.js `parseArgs` behavior.
47
49
  */
48
- value?: string;
50
+ value?: string | undefined;
49
51
  /**
50
- * Inline value, e.g. `--foo=bar` => `true`, `-x=bar` => `true`.
52
+ * Inline value, e.g. `--foo=bar` => `true`, `-x=bar` => `true`, `-x-1` => `false`, since no `=`
53
+ * is written. Unlike Node.js `parseArgs`, `false` does not mean that the value is the next
54
+ * argument: the value token of `-x-1` has the `index` of that argument.
51
55
  */
52
- inlineValue?: boolean;
56
+ inlineValue?: boolean | undefined;
53
57
  }
54
58
  /**
55
59
  * Parser Options.
56
60
  */
57
61
  //#endregion
58
- //#region ../../node_modules/.pnpm/args-tokens@0.29.0/node_modules/args-tokens/lib/resolver.d.ts
62
+ //#region ../../node_modules/.pnpm/args-tokens@1.0.0-beta.1/node_modules/args-tokens/lib/resolver.d.ts
59
63
  //#region src/resolver.d.ts
60
64
  /**
61
65
  * An argument schema definition for command-line argument parsing.
@@ -101,19 +105,25 @@ interface ArgSchema {
101
105
  /**
102
106
  * Type of the argument value.
103
107
  *
104
- * - `'string'`: Text value (default if not specified)
105
- * - `'boolean'`: `true`/`false` flag (can be negatable with `--no-` prefix)
108
+ * - `'string'`: Text value
109
+ * - `'boolean'`: `true`/`false` flag (can be negatable with `--no-` prefix). `--flag=true` and
110
+ * `--flag=false` set the value explicitly; any other value after `=` is a type error
106
111
  * - `'number'`: Numeric value (parsed as integer or float)
107
- * - `'enum'`: One of predefined string values (requires `choices` property)
112
+ * - `'enum'`: One of predefined string values (requires `choices` property, unless the argument
113
+ * has a `parse` function)
108
114
  * - `'positional'`: Non-option argument by position
109
115
  * - `'custom'`: Custom parsing with user-defined `parse` function
110
116
  *
117
+ * Any other `type`, or no `type`, is a mistake that only untyped code can make: if the argument
118
+ * has no `parse` function, {@link resolveArgs} and `parse()` throw an `Error`, whether or not the
119
+ * argument is given.
120
+ *
111
121
  * @example
112
122
  * Different argument types:
113
123
  * ```ts
114
124
  * {
115
125
  * name: { type: 'string' }, // --name value
116
- * verbose: { type: 'boolean' }, // --verbose or --no-verbose
126
+ * verbose: { type: 'boolean' }, // --verbose (--no-verbose needs negatable: true)
117
127
  * port: { type: 'number' }, // --port 3000
118
128
  * level: { type: 'enum', choices: ['debug', 'info'] },
119
129
  * file: { type: 'positional' }, // first positional arg
@@ -188,14 +198,32 @@ interface ArgSchema {
188
198
  /**
189
199
  * Marks the argument as required.
190
200
  *
191
- * When `true`, the argument must be provided by the user.
192
- * If missing, an `ArgResolveError` with type 'required' will be thrown.
193
- *
194
- * For single-value positional arguments, omitting `required` keeps the argument
195
- * required for compatibility. Set `required: false` to make a positional argument
196
- * optional. Optional positional arguments leave enough input values for later
201
+ * When `true`, the argument must be provided by the user. If it is missing, the error is an
202
+ * `ArgResolveError` with type 'required' and the code `err:arg:required-option`
203
+ * ({@link ArgsValidationErrorKeys}.requiredOption), or `err:arg:required-positional`
204
+ * ({@link ArgsValidationErrorKeys}.requiredPositional) for a positional argument. Its
205
+ * `values` has the `displayName` as in the message, such as `'--name'` for an option
206
+ * (`'--name' or '-n'` with the short name `n`) and `'file'` for a positional argument, and
207
+ * the `name`, which is the schema key.
208
+ * An option that is given without a value is reported as `err:arg:missing-value`
209
+ * ({@link ArgsValidationErrorKeys}.missingValue) instead, because the option itself was given.
210
+ * An explicit empty value, such as `--name=` or `-n ''`, is still reported as required, but the
211
+ * option counts as given: it is `true` in `explicit` and takes part in conflicts, as any other
212
+ * given option does.
213
+ *
214
+ * For single-value positional arguments, omitting `required` keeps the argument required for
215
+ * compatibility, unless it has a `default`, which makes it optional. A `multiple` positional
216
+ * argument is optional unless `required: true` is set. Set `required: false` to make a positional
217
+ * argument explicitly optional. Optional positional arguments leave enough input values for later
197
218
  * required positional arguments before consuming a value.
198
219
  *
220
+ * In the type of the values, such as {@link ArgValues}, a single-value positional argument whose
221
+ * `required` may be `false`, such as one of type `boolean`, is optional, as it may be missing,
222
+ * unless it has a `default`. An optional `required` of type `boolean`, as declared here, says
223
+ * nothing, and keeps it required. TypeScript widens a `required: true` to `boolean` in a schema
224
+ * written apart from the call, such as `{ type: 'positional' as const, required: true }`, which
225
+ * types the argument as optional: write such a schema `as const`.
226
+ *
199
227
  * @example
200
228
  * Required arguments:
201
229
  * ```ts
@@ -216,8 +244,9 @@ interface ArgSchema {
216
244
  /**
217
245
  * Allows the argument to accept multiple values.
218
246
  *
219
- * When `true`, the resolved value becomes an array.
220
- * For options: can be specified multiple times (--tag foo --tag bar)
247
+ * When `true`, the resolved value becomes an array. When the argument is not given and has no
248
+ * `default`, its value is `undefined`, not an empty array.
249
+ * For options: can be specified multiple times (--tags foo --tags bar)
221
250
  * For positional: collects remaining positional arguments after preserving values for
222
251
  * later required positional arguments.
223
252
  *
@@ -249,6 +278,12 @@ interface ArgSchema {
249
278
  *
250
279
  * Only applicable to `type: 'boolean'` arguments.
251
280
  *
281
+ * The negated name is always `no-` followed by the full option name. An option named
282
+ * `no-cache` is negated by `--no-no-cache`, and `--no-cache` sets it to `true`.
283
+ *
284
+ * The negated form does not take a value. `--no-flag=<value>` is reported as
285
+ * `err:arg:unexpected-value` ({@link ArgsValidationErrorKeys}.unexpectedValue).
286
+ *
252
287
  * @example
253
288
  * Negatable boolean:
254
289
  * ```ts
@@ -267,8 +302,17 @@ interface ArgSchema {
267
302
  /**
268
303
  * Array of allowed string values for enum-type arguments.
269
304
  *
270
- * Required when `type: 'enum'`. The argument value must be one of these choices,
271
- * otherwise an `ArgResolveError` with type 'type' will be thrown.
305
+ * Required when `type: 'enum'`, unless the argument has a `parse` function: if `choices` is
306
+ * missing or not an array, {@link resolveArgs} and `parse()` throw a `TypeError`, whether or not
307
+ * the argument is given. With a `parse` function and no `choices`, the value is passed to the
308
+ * function as for a `string` argument with a `parse` function.
309
+ *
310
+ * The argument value must be one of these choices, otherwise the error is an `ArgResolveError`
311
+ * with type 'type' and the code `err:arg:invalid-choice`
312
+ * ({@link ArgsValidationErrorKeys}.invalidChoice).
313
+ *
314
+ * The value is checked before `parse` is called, so a `parse` function receives only one of
315
+ * these choices and can change it, for example to upper case.
272
316
  *
273
317
  * Supports both mutable arrays and readonly arrays for type safety.
274
318
  *
@@ -292,18 +336,37 @@ interface ArgSchema {
292
336
  */
293
337
  choices?: string[] | readonly string[];
294
338
  /**
295
- * Default value used when the argument is not provided.
339
+ * Default value used when the argument is not provided. An option that is given without a value,
340
+ * or with a value that is rejected, also gets its default, along with the error.
296
341
  *
297
342
  * The type must match the argument's `type` property:
298
343
  * - `string` type: string default
299
344
  * - `boolean` type: boolean default
300
345
  * - `number` type: number default
301
- * - `enum` type: must be one of the `choices` values
346
+ * - `enum` type: one of the `choices` values, or a value that a `parse` of your own returns
302
347
  * - `positional`/`custom` type: string, boolean, or number default
303
348
  *
304
- * For single-value positional arguments, the default is used when the positional
305
- * value is missing or when the value is preserved for later required positional
306
- * arguments, unless `required: true` is set.
349
+ * The default is used as is and never goes through `parse`, including when an option is given
350
+ * without a value. An explicit empty value, such as `--name=` or `-n ''`, is a value, not a
351
+ * missing one: a `string` option without `parse` gets `''` instead of the default, unless it is
352
+ * `required`. What `parse` returns is a value too, even `undefined` or `null`, and the default
353
+ * does not replace it.
354
+ *
355
+ * The value of a `multiple` argument is an array, so its default becomes the only element of the
356
+ * array: `default: 'latest'` gives `['latest']`.
357
+ *
358
+ * The default of an `enum` option with `choices` is checked when it would be used, that is, when
359
+ * no value from the command line is used: one that is not one of the choices is reported as an
360
+ * `ArgResolveError` with type 'type' and the code `err:arg:invalid-default`
361
+ * ({@link ArgsValidationErrorKeys}.invalidDefault), and is not used. With a `parse` function of
362
+ * your own, or a `map()` transform, the default is a value that the function returns, which need
363
+ * not be one of the choices, and it is not checked. `choice()` returns the value as is, so its
364
+ * default is checked.
365
+ *
366
+ * For positional arguments, `multiple` ones included, the default is used when no value is left
367
+ * for the argument: when the positional values run out, or when the remaining ones are preserved
368
+ * for later required positional arguments. With `required: true`, the default is not used, and
369
+ * the argument is reported as required instead.
307
370
  *
308
371
  * @example
309
372
  * Default values by type:
@@ -336,7 +399,8 @@ interface ArgSchema {
336
399
  * When `true`, a property like `maxCount` becomes available as `--max-count`.
337
400
  * This allows [CAC](https://github.com/cacjs/cac) user-friendly property names while maintaining CLI conventions.
338
401
  *
339
- * Can be overridden globally with `resolveArgs({ toKebab: true })`.
402
+ * The `toKebab` option of {@link resolveArgs} and `parse()` applies it to all arguments, as in
403
+ * `resolveArgs(args, tokens, { toKebab: true })`.
340
404
  *
341
405
  * Note: Only `true` is allowed (not `false`) to make intent explicit.
342
406
  *
@@ -360,8 +424,19 @@ interface ArgSchema {
360
424
  /**
361
425
  * Names of other options that conflict with this option.
362
426
  *
363
- * When this option is used together with any of the conflicting options,
364
- * an `ArgResolveError` with type 'conflict' will be thrown.
427
+ * When this option is used together with any of the conflicting options, the error is an
428
+ * `ArgResolveError` with type 'conflict' and the code `err:arg:conflict`
429
+ * ({@link ArgsValidationErrorKeys}.conflict). Its `values` has the `displayName` and `name` of
430
+ * the argument whose `conflicts` names the other one, and the `conflictDisplayName` and
431
+ * `conflictName` of the other one. `displayName` and `conflictDisplayName` show an option as
432
+ * it was written, such as `'-p'`, and `name` and `conflictName` are the schema keys. When both
433
+ * name each other, `name` is the one that comes first in the schema.
434
+ *
435
+ * A positional argument can be on either side, such as `[file]` and `--stdin`. It conflicts when
436
+ * it is given, and it is shown by its name, such as `'file'` (in kebab-case with `toKebab`), as
437
+ * in its other errors. The message starts with the kind of the argument given as `name`:
438
+ * `Positional argument 'file' conflicts with '--stdin'` or
439
+ * `Optional argument '--stdin' conflicts with 'file'`.
365
440
  *
366
441
  * Conflicts only need to be defined on one side - if option A defines a conflict
367
442
  * with option B, the conflict is automatically detected when both are used,
@@ -399,7 +474,7 @@ interface ArgSchema {
399
474
  * // No conflicts defined, but still cannot use with --summer
400
475
  * }
401
476
  * }
402
- * // Usage: --summer --autumn will throw error
477
+ * // Usage: --summer --autumn reports an error
403
478
  * // Error: "Optional argument '--summer' conflicts with '--autumn'"
404
479
  * ```
405
480
  *
@@ -451,6 +526,10 @@ interface ArgSchema {
451
526
  * Particularly useful for `type: 'custom'` arguments where the type
452
527
  * name would otherwise be unhelpful.
453
528
  *
529
+ * For a `custom` option that is given without a value, it is also the `expected` in the `values`
530
+ * of the `err:arg:missing-value` error ({@link ArgsValidationErrorKeys}.missingValue), which is
531
+ * `'custom'` without it.
532
+ *
454
533
  * @example
455
534
  * Metavar usage:
456
535
  * ```ts
@@ -467,13 +546,37 @@ interface ArgSchema {
467
546
  */
468
547
  metavar?: string;
469
548
  /**
470
- * Custom parsing function for `type: 'custom'` arguments.
549
+ * Custom parsing function, used in place of the parsing of the argument's `type`.
471
550
  *
472
- * Required when `type: 'custom'`. Receives the raw string value and must
473
- * return the parsed result. Should throw an Error (or subclass) if parsing fails.
551
+ * Required when `type: 'custom'`: if it is missing or not a function, {@link resolveArgs} and
552
+ * `parse()` throw a `TypeError`, whether or not the argument is given. The function receives the
553
+ * raw string value and must return the parsed result. It should throw an Error (or subclass) if
554
+ * parsing fails.
474
555
  *
475
556
  * The function's return type becomes the resolved argument type.
476
557
  *
558
+ * `parse` is called synchronously, and what it returns becomes the value, even `undefined` or
559
+ * `null`, so throw to reject a value. An `async` function returns a promise, and the promise
560
+ * becomes the value as is: it is not awaited, and its rejection is not reported as an error.
561
+ * Await the value, or each of its elements with `multiple` (for example with `Promise.all()`),
562
+ * and handle the rejection yourself: a rejection that nothing handles is an unhandled rejection,
563
+ * which ends a Node.js process by default.
564
+ *
565
+ * A `boolean` option calls `parse` with `'true'`, or `'false'` for the negated form. Other
566
+ * options call it only with a value from the command line: when the option is given without a
567
+ * value, `parse` is not called and the missing value is reported as `err:arg:missing-value`
568
+ * ({@link ArgsValidationErrorKeys}.missingValue). When that error may suggest the argument after
569
+ * the option as its value, such as `--port=-5` for `--port -5`, a `parse` function of your own
570
+ * is not called to check it either: only the `parse` functions of `string()`, `number()`,
571
+ * `integer()`, `float()` and `choice()`, which have no side effects, are called for that.
572
+ * An explicit empty value, such as `--name=` or `-n=`, is passed as `''` unless
573
+ * `required: true` is set.
574
+ *
575
+ * An `enum` option with `choices` calls it only with one of them. Any other value, an explicit
576
+ * empty one included, is reported as `err:arg:invalid-choice`
577
+ * ({@link ArgsValidationErrorKeys}.invalidChoice), except that a required option reports an
578
+ * explicit empty value as required.
579
+ *
477
580
  * @param value - Raw string value from command line
478
581
  * @returns Parsed value of any type
479
582
  * @throws {Error} Error or subclass when value is invalid
@@ -513,6 +616,10 @@ interface ArgSchema {
513
616
  *
514
617
  * Each code identifies a validation failure category and is also suitable as an
515
618
  * i18n resource key for localized rendering.
619
+ *
620
+ * {@link resolveArgs} and `parse()` do not report `unknownOption`. An option that is not in the
621
+ * schema takes the argument after it as its value, unless that argument is an option, and the value
622
+ * is dropped: with no `foo` in the schema, `--foo bar` gives no positional argument.
516
623
  */
517
624
  declare const ArgsValidationErrorKeys: {
518
625
  readonly requiredOption: 'err:arg:required-option';
@@ -521,6 +628,10 @@ declare const ArgsValidationErrorKeys: {
521
628
  readonly invalidChoice: 'err:arg:invalid-choice';
522
629
  readonly customParse: 'err:arg:custom-parse';
523
630
  readonly unknownOption: 'err:arg:unknown-option';
631
+ readonly unexpectedValue: 'err:arg:unexpected-value';
632
+ readonly missingValue: 'err:arg:missing-value';
633
+ readonly conflict: 'err:arg:conflict';
634
+ readonly invalidDefault: 'err:arg:invalid-default';
524
635
  };
525
636
  /**
526
637
  * A machine-readable argument validation error code.
@@ -546,7 +657,7 @@ declare class ArgsValidationError extends Error {
546
657
  *
547
658
  * This code can also be used as an i18n resource key.
548
659
  */
549
- readonly code?: ArgsValidationErrorCode;
660
+ readonly code?: ArgsValidationErrorCode | undefined;
550
661
  /**
551
662
  * Interpolation values for `code`.
552
663
  */
@@ -574,6 +685,20 @@ interface Args {
574
685
  /**
575
686
  * An object that contains the values of the arguments.
576
687
  *
688
+ * The value of an argument whose schema is a union, such as
689
+ * `strict ? multiple(integer()) : string()` with the combinators, is typed as a value of any of its
690
+ * schemas: `number[] | string`. The argument is typed as present only when each schema of the
691
+ * union gives it a value, with a default, with `required: true` or as a required positional
692
+ * argument.
693
+ *
694
+ * When the type of one schema covers that of the other, as the type of `integer()` covers that of
695
+ * `multiple(integer())`, TypeScript types a `?:` expression of them as the covering schema alone:
696
+ * the value of `strict ? multiple(integer()) : integer()` is typed without the array, and
697
+ * `strict ? multiple(positional()) : positional()` as present, although it may be missing. Give
698
+ * each schema its own argument instead, or give the expression the type of both schemas with `as`,
699
+ * as in `(strict ? many : one) as typeof many | typeof one` for `const many = multiple(integer())`
700
+ * and `const one = integer()`.
701
+ *
577
702
  * @typeParam T - {@link Args | Arguments} which is an object that defines the command line arguments.
578
703
  */
579
704
  type ArgValues<T> = T extends Args ? ResolveArgValues<T, { [Arg in keyof T]: ExtractOptionValue<T[Arg]> }> : {
@@ -581,22 +706,41 @@ type ArgValues<T> = T extends Args ? ResolveArgValues<T, { [Arg in keyof T]: Ext
581
706
  };
582
707
  /**
583
708
  * Extracts the value type from the argument schema.
709
+ * For a union of schemas, it is the union of the value types of its schemas.
584
710
  *
585
711
  * @typeParam A - {@link ArgSchema | Argument schema} which is an object that defines command line arguments.
586
712
  *
587
713
  * @internal
588
714
  */
589
- type ExtractOptionValue<A extends ArgSchema> = undefined extends A['parse'] ? A['type'] extends 'string' ? ResolveOptionValue<A, string> : A['type'] extends 'boolean' ? ResolveOptionValue<A, boolean> : A['type'] extends 'number' ? ResolveOptionValue<A, number> : A['type'] extends 'positional' ? ResolveOptionValue<A, string> : A['type'] extends 'enum' ? A['choices'] extends string[] | readonly string[] ? ResolveOptionValue<A, A['choices'][number]> : never : A['type'] extends 'custom' ? never : ResolveOptionValue<A, string | boolean | number> : A['parse'] extends ((value: string) => infer R) ? ResolveOptionValue<A, R> : never;
715
+ type ExtractOptionValue<A extends ArgSchema> = A extends ArgSchema ? ExtractSchemaValue<A> : never;
716
+ /**
717
+ * The value type of one schema, which {@link ExtractOptionValue} takes for each schema of a union.
718
+ */
719
+ type ExtractSchemaValue<A extends ArgSchema> = undefined extends A['parse'] ? A['type'] extends 'string' ? ResolveOptionValue<A, string> : A['type'] extends 'boolean' ? ResolveOptionValue<A, boolean> : A['type'] extends 'number' ? ResolveOptionValue<A, number> : A['type'] extends 'positional' ? ResolveOptionValue<A, string> : A['type'] extends 'enum' ? A['choices'] extends string[] | readonly string[] ? ResolveOptionValue<A, A['choices'][number]> : never : A['type'] extends 'custom' ? never : ResolveOptionValue<A, string | boolean | number> : A['parse'] extends ((value: string) => infer R) ? ResolveOptionValue<A, R> : never;
590
720
  type ResolveOptionValue<A extends ArgSchema, T> = A['multiple'] extends true ? T[] : T;
591
721
  /**
592
722
  * Resolved argument values.
593
723
  *
724
+ * Each argument is mapped as optional, and the ones that are present, as {@link IsPresentArg}
725
+ * says, are mapped again as present. The optional mapping types a present argument as `unknown`:
726
+ * TypeScript does not reduce an intersection such as
727
+ * `(string | number[] | undefined) & (string | number[])`, of a value type that is a union with an
728
+ * object type. It maps all the keys without renaming them, which lets TypeScript relate the values
729
+ * of related type parameters, so that a conversion such as `values as ArgValues<A>` compiles.
730
+ *
594
731
  * @typeParam A - {@link Arguments | Args} which is an object that defines the command line arguments.
595
732
  * @typeParam V - Resolvable argument values.
596
733
  *
597
734
  * @internal
598
735
  */
599
- type ResolveArgValues<A extends Args, V extends Record<keyof A, unknown>> = { -readonly [Arg in keyof A]?: V[Arg] } & FilterArgs<A, V, 'default'> & FilterArgs<A, V, 'required'> & FilterPositionalArgs<A, V> extends (infer P) ? { [K in keyof P]: P[K] } : never;
736
+ type ResolveArgValues<A extends Args, V extends Record<keyof A, unknown>> = { -readonly [Arg in keyof A]?: IsPresentArg<A[Arg]> extends true ? unknown : V[Arg] } & { -readonly [Arg in keyof A as IsPresentArg<A[Arg]> extends true ? Arg : never]: V[Arg] } extends (infer P) ? { [K in keyof P]: P[K] } : never;
737
+ /**
738
+ * Whether an argument with the schema `S` has a value: with a default, with `required: true` or as
739
+ * a required positional argument. For a union of schemas, only when each schema of the union has
740
+ * one. A `default` or `required` typed as `any`, and a schema typed as `any`, count as giving a
741
+ * value, as {@link FilterArgs} does.
742
+ */
743
+ type IsPresentArg<S extends ArgSchema> = S extends ArgSchema ? true extends (S['default'] extends {} ? true : S['required'] extends true ? true : false) ? true : IsRequiredPositionalArg<S> : never;
600
744
  /**
601
745
  * Filters the arguments based on their default values.
602
746
  *
@@ -606,17 +750,17 @@ type ResolveArgValues<A extends Args, V extends Record<keyof A, unknown>> = { -r
606
750
  *
607
751
  * @internal
608
752
  */
609
- type FilterArgs<A extends Args, V extends Record<keyof A, unknown>, K extends keyof ArgSchema> = { [Arg in keyof A as K extends 'required' ? A[Arg][K] extends true ? Arg : never : A[Arg][K] extends {} ? Arg : never]: V[Arg] };
753
+
754
+ type IsRequiredPositionalArg<A extends ArgSchema> = A['type'] extends 'positional' ? A['multiple'] extends true ? A['required'] extends true ? true : false : MayBeUnrequired<A> extends true ? A['default'] extends {} ? true : false : true : false;
610
755
  /**
611
- * Filters positional arguments from the argument schema.
612
- *
613
- * @typeParam A - {@link Args | Arguments}, which is an object that defines the command line arguments.
614
- * @typeParam V - Resolvable argument values.
615
- *
616
- * @internal
756
+ * Whether the `required` of `A` may be `false`. An optional `required` of type `boolean`, as in
757
+ * {@link ArgSchema}, says nothing, and is read as missing, so that a positional argument with it is
758
+ * required. A `required` that `A` always has may be `false` when its type is `boolean` or
759
+ * `boolean | undefined`.
617
760
  */
618
- type FilterPositionalArgs<A extends Args, V extends Record<keyof A, unknown>> = { [Arg in keyof A as IsRequiredPositionalArg<A[Arg]> extends true ? Arg : never]: V[Arg] };
619
- type IsRequiredPositionalArg<A extends ArgSchema> = A['type'] extends 'positional' ? A['multiple'] extends true ? A['required'] extends true ? true : false : A['required'] extends false ? A['default'] extends {} ? true : false : true : false;
761
+ type MayBeUnrequired<A extends ArgSchema> = false extends A['required'] ? [A] extends [{
762
+ required: unknown;
763
+ }] ? true : boolean | undefined extends A['required'] ? false : true : false;
620
764
  /**
621
765
  * An arguments for {@link resolveArgs | resolve arguments}.
622
766
  */
@@ -624,8 +768,12 @@ type IsRequiredPositionalArg<A extends ArgSchema> = A['type'] extends 'positiona
624
768
  /**
625
769
  * Tracks which arguments were explicitly provided by the user.
626
770
  *
627
- * Each property indicates whether the corresponding argument was explicitly
628
- * provided (true) or is using a default value or not provided (false).
771
+ * Each property is `true` when the argument is given on the command line, and `false` when it is
772
+ * not, whether it has a default or not. An option is given when one of its forms is, such as
773
+ * `--port`, `-p` or `--no-color`, even if its value is missing or rejected: the error is reported,
774
+ * and if no value from the command line is used, its default, if any, fills in the value. A
775
+ * positional argument is given when a positional value is used for it, even if `parse` rejects
776
+ * the value: the error is reported, and its default is not used.
629
777
  *
630
778
  * @typeParam A - {@link Args | Arguments}, which is an object that defines the command line arguments.
631
779
  */
@@ -817,7 +965,9 @@ Ext extends Record<string, unknown> = {},
817
965
  // for plugin extension type
818
966
  ResolvedDepExt extends GunshiParams = DependencyParams<Deps, DepExt>, PluginExt extends PluginExtension<Ext, ResolvedDepExt> = PluginExtension<Ext, ResolvedDepExt>, MergedExt extends GunshiParams = MergedPluginParams<Id, Deps, DepExt, Awaited<ReturnType<PluginExt>>>> {
819
967
  /**
820
- * Plugin unique identifier
968
+ * Plugin unique identifier.
969
+ *
970
+ * Must be a non-empty string. {@linkcode plugin} and the installer both reject an empty id.
821
971
  */
822
972
  id: Id;
823
973
  /**
@@ -1149,7 +1299,11 @@ interface CommandEnvironment<G extends GunshiParamsConstraint = DefaultGunshiPar
1149
1299
  */
1150
1300
  usageOptionValue: boolean;
1151
1301
  /**
1152
- * Whether to display the command usage.
1302
+ * Whether to keep usage, header, version, and validation-error text off the terminal
1303
+ * (they are still returned as strings) and to silence {@linkcode CommandContext.log}.
1304
+ *
1305
+ * Output that must still appear — machine-readable results for an agent, warnings for the
1306
+ * CLI author — should use `console.log` / `console.warn`, not `ctx.log`.
1153
1307
  *
1154
1308
  * @default false
1155
1309
  * @see {@linkcode CliOptions.usageSilent}
@@ -1168,6 +1322,26 @@ interface CommandEnvironment<G extends GunshiParamsConstraint = DefaultGunshiPar
1168
1322
  * @see {@linkcode CliOptions.subCommands}
1169
1323
  */
1170
1324
  subCommands: Map<string, Command<any> | LazyCommand<any>> | undefined;
1325
+ /**
1326
+ * The entry command of the CLI, marked with `entry: true`.
1327
+ *
1328
+ * It is available whether or not the CLI has sub-commands, while {@linkcode CommandEnvironment.subCommands}
1329
+ * includes the entry command only when the sub-commands are given with {@linkcode CliOptions.subCommands}.
1330
+ * It is not frozen, like the commands in {@linkcode CommandEnvironment.subCommands}.
1331
+ */
1332
+ entryCommand?: Command<any> | LazyCommand<any>;
1333
+ /**
1334
+ * The global options that are in effect for the command being executed.
1335
+ *
1336
+ * A plugin registers a global option with `addGlobalOption`, and gunshi merges it into the arguments
1337
+ * of the command that runs. An argument that the command declares under the same name replaces it,
1338
+ * and the option is then not in effect: the value under that name is the command's, and the plugin
1339
+ * that registered it must not read it as its own.
1340
+ *
1341
+ * The schema is the one in effect, which may have given up its short name to an argument of the
1342
+ * command that claims the same letter.
1343
+ */
1344
+ globalOptions?: ReadonlyMap<string, ArgSchema>;
1171
1345
  /**
1172
1346
  * Render function the command usage.
1173
1347
  */
@@ -1246,7 +1420,13 @@ interface CliOptions<G extends GunshiParamsConstraint = DefaultGunshiParams> {
1246
1420
  */
1247
1421
  usageOptionValue?: boolean;
1248
1422
  /**
1249
- * Whether to display the command usage.
1423
+ * Whether to keep usage, header, version, and validation-error text off the terminal
1424
+ * (they are still returned as strings) and to silence {@linkcode CommandContext.log}.
1425
+ *
1426
+ * Output that must still appear — machine-readable results for an agent, warnings for the
1427
+ * CLI author — should use `console.log` / `console.warn`, not `ctx.log`.
1428
+ *
1429
+ * @default false
1250
1430
  */
1251
1431
  usageSilent?: boolean;
1252
1432
  /**
@@ -1805,6 +1985,20 @@ declare const CommandNotFoundErrorKeys: {
1805
1985
  * Command not found error code.
1806
1986
  */
1807
1987
  type CommandNotFoundErrorCode = (typeof CommandNotFoundErrorKeys)[keyof typeof CommandNotFoundErrorKeys];
1988
+ /**
1989
+ * Command resolution error resource keys.
1990
+ *
1991
+ * These errors describe an ambiguity or inconsistency while choosing a command from arguments.
1992
+ * They are kept separate from {@link CommandNotFoundError} so consumers can distinguish a typo
1993
+ * from an input whose command interpretation is not unique.
1994
+ */
1995
+ declare const CommandResolutionErrorKeys: {
1996
+ readonly ambiguous: "err:cmd:ambiguous";
1997
+ readonly inconsistentOptions: "err:cmd:inconsistent-options";
1998
+ readonly lazySchemaMismatch: "err:cmd:lazy-schema-mismatch";
1999
+ };
2000
+ /** Command resolution error code. */
2001
+ type CommandResolutionErrorCode = (typeof CommandResolutionErrorKeys)[keyof typeof CommandResolutionErrorKeys];
1808
2002
  /**
1809
2003
  * Options for {@link CommandNotFoundError}.
1810
2004
  */
@@ -1834,6 +2028,19 @@ type CommandNotFoundErrorOptions = {
1834
2028
  */
1835
2029
  cause?: unknown;
1836
2030
  };
2031
+ /** Options for {@link CommandResolutionError}. */
2032
+ type CommandResolutionErrorOptions = {
2033
+ /** Localization resource key for the resolution failure. */
2034
+ code?: CommandResolutionErrorCode;
2035
+ /** Values used when localizing the message. */
2036
+ values?: Record<string, unknown>;
2037
+ /** Command path at which the resolution failed. */
2038
+ commandPath?: readonly string[];
2039
+ /** Candidate command paths considered by the resolver. */
2040
+ candidatePaths?: readonly (readonly string[])[];
2041
+ /** Underlying cause. */
2042
+ cause?: unknown;
2043
+ };
1837
2044
  /**
1838
2045
  * Error raised when a command cannot be resolved.
1839
2046
  *
@@ -1855,6 +2062,26 @@ declare class CommandNotFoundError extends Error {
1855
2062
  */
1856
2063
  constructor(message: string, options: CommandNotFoundErrorOptions);
1857
2064
  }
2065
+ /**
2066
+ * Error raised when command routing cannot produce one consistent command.
2067
+ *
2068
+ * The own registry brand is the cross-bundle contract. Unlike the legacy command-not-found
2069
+ * guard, the new guard deliberately has no name-based fallback because this error type is new and
2070
+ * must not classify arbitrary errors from older versions.
2071
+ */
2072
+ declare class CommandResolutionError extends Error {
2073
+ readonly code?: CommandResolutionErrorCode;
2074
+ readonly values: Record<string, unknown>;
2075
+ readonly commandPath: readonly string[];
2076
+ readonly candidatePaths: readonly (readonly string[])[];
2077
+ /**
2078
+ * Create a command resolution error with structured routing metadata.
2079
+ *
2080
+ * @param message - Human-readable fallback message
2081
+ * @param options - Error code and command-routing metadata
2082
+ */
2083
+ constructor(message: string, options?: CommandResolutionErrorOptions);
2084
+ }
1858
2085
  /**
1859
2086
  * Check whether an error is a {@link CommandNotFoundError}.
1860
2087
  *
@@ -1867,6 +2094,13 @@ declare class CommandNotFoundError extends Error {
1867
2094
  * @returns `true` if the error is a {@link CommandNotFoundError}
1868
2095
  */
1869
2096
  declare function isCommandNotFoundError(error: unknown): error is CommandNotFoundError;
2097
+ /**
2098
+ * Check whether an error is a {@link CommandResolutionError}.
2099
+ *
2100
+ * @param error - An unknown error
2101
+ * @returns `true` when the error has the command-resolution brand and shape
2102
+ */
2103
+ declare function isCommandResolutionError(error: unknown): error is CommandResolutionError;
1870
2104
  /**
1871
2105
  * Check whether an error is an {@link ArgsValidationError}.
1872
2106
  *
@@ -1901,4 +2135,4 @@ declare function hasPriorityValidationError(error: AggregateError | undefined):
1901
2135
  */
1902
2136
 
1903
2137
  //#endregion
1904
- export { ANONYMOUS_COMMAND_NAME, type ArgSchema, type ArgToken, type ArgValues, type Args, ArgsValidationError, ArgsValidationErrorCode, ArgsValidationErrorKeys, Awaitable, CLI_OPTIONS_DEFAULT, Command, CommandContext, CommandContextCore, CommandContextExtension, CommandContextParams, CommandDecorator, CommandExamplesFetcher, CommandNotFoundError, CommandNotFoundErrorCode, CommandNotFoundErrorKeys, CommandNotFoundErrorOptions, CommandRunner, DefaultGunshiParams, ExtendContext, ExtractArgs, ExtractExtensions, GunshiParams, GunshiParamsConstraint, LazyCommand, MergeGunshiExtensions, NormalizeToGunshiParams, OnPluginExtension, Plugin, PluginContext, PluginDependency, PluginExtension, PluginFunction, PluginOptions, PluginWithExtension, PluginWithoutExtension, Prettify, RendererDecorator, ValidationErrorsDecorator, createCommandContext, hasPriorityValidationError, isArgsValidationError, isCommandNotFoundError, plugin };
2138
+ export { ANONYMOUS_COMMAND_NAME, type ArgSchema, type ArgToken, type ArgValues, type Args, ArgsValidationError, ArgsValidationErrorCode, ArgsValidationErrorKeys, Awaitable, CLI_OPTIONS_DEFAULT, Command, CommandContext, CommandContextCore, CommandContextExtension, CommandContextParams, CommandDecorator, CommandExamplesFetcher, CommandNotFoundError, CommandNotFoundErrorCode, CommandNotFoundErrorKeys, CommandNotFoundErrorOptions, CommandResolutionError, CommandResolutionErrorCode, CommandResolutionErrorKeys, CommandResolutionErrorOptions, CommandRunner, DefaultGunshiParams, ExtendContext, ExtractArgs, ExtractExtensions, GunshiParams, GunshiParamsConstraint, LazyCommand, MergeGunshiExtensions, NormalizeToGunshiParams, OnPluginExtension, Plugin, PluginContext, PluginDependency, PluginExtension, PluginFunction, PluginOptions, PluginWithExtension, PluginWithoutExtension, Prettify, RendererDecorator, ValidationErrorsDecorator, createCommandContext, hasPriorityValidationError, isArgsValidationError, isCommandNotFoundError, isCommandResolutionError, plugin };
package/lib/index.js CHANGED
@@ -36,10 +36,13 @@ const CLI_OPTIONS_DEFAULT = {
36
36
  * Check if the given command is a {@link LazyCommand}.
37
37
  *
38
38
  * @param cmd - A command to check
39
- * @returns `true` if the command is a {@link LazyCommand}, otherwise `false
39
+ * @returns `true` if the command is a {@link LazyCommand}, otherwise `false`
40
+ *
41
+ * A lazy command is identified by its `commandName` property. The property may be
42
+ * `undefined` when the lazy command has no definition name.
40
43
  */
41
44
  function isLazyCommand(cmd) {
42
- return typeof cmd === "function" && "commandName" in cmd && !!cmd.commandName;
45
+ return typeof cmd === "function" && "commandName" in cmd;
43
46
  }
44
47
  /**
45
48
  * Create an object with the specified prototype. A shorthand for `Object.create`.
@@ -155,7 +158,7 @@ async function createCommandContext({ args = {}, explicit = {}, values = {}, pos
155
158
  if (extension.onFactory) await extension.onFactory(core, command);
156
159
  }
157
160
  }
158
- return deepFreeze(core, ["extensions"]);
161
+ return deepFreeze(core, ["extensions", "entryCommand"]);
159
162
  }
160
163
  function getCommandName(cmd) {
161
164
  if (isLazyCommand(cmd)) return cmd.commandName || cmd.name || "(anonymous)";
@@ -173,7 +176,11 @@ function getCommandName(cmd) {
173
176
  "-".codePointAt(0);
174
177
  "=".codePointAt(0);
175
178
  //#endregion
176
- //#region ../../node_modules/.pnpm/args-tokens@0.29.0/node_modules/args-tokens/lib/resolver.js
179
+ //#region ../../node_modules/.pnpm/args-tokens@1.0.0-beta.1/node_modules/args-tokens/lib/resolver-CAlgxe_R.js
180
+ /**
181
+ * @author kazuya kawaguchi (a.k.a. kazupon)
182
+ * @license MIT
183
+ */
177
184
  /**
178
185
  * Entry point of argument options resolver.
179
186
  *
@@ -188,6 +195,10 @@ function getCommandName(cmd) {
188
195
  *
189
196
  * Each code identifies a validation failure category and is also suitable as an
190
197
  * i18n resource key for localized rendering.
198
+ *
199
+ * {@link resolveArgs} and `parse()` do not report `unknownOption`. An option that is not in the
200
+ * schema takes the argument after it as its value, unless that argument is an option, and the value
201
+ * is dropped: with no `foo` in the schema, `--foo bar` gives no positional argument.
191
202
  */
192
203
  const ArgsValidationErrorKeys = {
193
204
  requiredOption: "err:arg:required-option",
@@ -195,7 +206,11 @@ const ArgsValidationErrorKeys = {
195
206
  invalidType: "err:arg:invalid-type",
196
207
  invalidChoice: "err:arg:invalid-choice",
197
208
  customParse: "err:arg:custom-parse",
198
- unknownOption: "err:arg:unknown-option"
209
+ unknownOption: "err:arg:unknown-option",
210
+ unexpectedValue: "err:arg:unexpected-value",
211
+ missingValue: "err:arg:missing-value",
212
+ conflict: "err:arg:conflict",
213
+ invalidDefault: "err:arg:invalid-default"
199
214
  };
200
215
  /**
201
216
  * Brand that marks {@link ArgsValidationError} instances.
@@ -270,7 +285,7 @@ function isArgsValidationError$1(error) {
270
285
  return typeof values === "object" && values !== null;
271
286
  }
272
287
  //#endregion
273
- //#region ../../node_modules/.pnpm/args-tokens@0.29.0/node_modules/args-tokens/lib/index.js
288
+ //#region ../../node_modules/.pnpm/args-tokens@1.0.0-beta.1/node_modules/args-tokens/lib/index.js
274
289
  /**
275
290
  * @author kazuya kawaguchi (a.k.a. kazupon)
276
291
  * @license MIT
@@ -290,6 +305,18 @@ function isArgsValidationError$1(error) {
290
305
  */
291
306
  const CommandNotFoundErrorKeys = { notFound: "err:cmd:not-found" };
292
307
  /**
308
+ * Command resolution error resource keys.
309
+ *
310
+ * These errors describe an ambiguity or inconsistency while choosing a command from arguments.
311
+ * They are kept separate from {@link CommandNotFoundError} so consumers can distinguish a typo
312
+ * from an input whose command interpretation is not unique.
313
+ */
314
+ const CommandResolutionErrorKeys = {
315
+ ambiguous: "err:cmd:ambiguous",
316
+ inconsistentOptions: "err:cmd:inconsistent-options",
317
+ lazySchemaMismatch: "err:cmd:lazy-schema-mismatch"
318
+ };
319
+ /**
293
320
  * Brand that marks {@link CommandNotFoundError} instances.
294
321
  *
295
322
  * The brand is looked up in the global symbol registry with `Symbol.for`, so it stays
@@ -298,6 +325,7 @@ const CommandNotFoundErrorKeys = { notFound: "err:cmd:not-found" };
298
325
  * another copy, where `instanceof` cannot match.
299
326
  */
300
327
  const COMMAND_NOT_FOUND_ERROR_BRAND = Symbol.for("gunshi.CommandNotFoundError");
328
+ const COMMAND_RESOLUTION_ERROR_BRAND = Symbol.for("gunshi.CommandResolutionError");
301
329
  /**
302
330
  * Error raised when a command cannot be resolved.
303
331
  *
@@ -334,6 +362,39 @@ var CommandNotFoundError = class extends Error {
334
362
  }
335
363
  };
336
364
  /**
365
+ * Error raised when command routing cannot produce one consistent command.
366
+ *
367
+ * The own registry brand is the cross-bundle contract. Unlike the legacy command-not-found
368
+ * guard, the new guard deliberately has no name-based fallback because this error type is new and
369
+ * must not classify arbitrary errors from older versions.
370
+ */
371
+ var CommandResolutionError = class extends Error {
372
+ code;
373
+ values;
374
+ commandPath;
375
+ candidatePaths;
376
+ /**
377
+ * Create a command resolution error with structured routing metadata.
378
+ *
379
+ * @param message - Human-readable fallback message
380
+ * @param options - Error code and command-routing metadata
381
+ */
382
+ constructor(message, options = {}) {
383
+ super(message, { cause: options.cause });
384
+ this.name = "CommandResolutionError";
385
+ this.code = options.code;
386
+ this.values = options.values || {};
387
+ this.commandPath = options.commandPath || [];
388
+ this.candidatePaths = options.candidatePaths || [];
389
+ Object.defineProperty(this, COMMAND_RESOLUTION_ERROR_BRAND, {
390
+ value: true,
391
+ enumerable: false,
392
+ writable: false,
393
+ configurable: false
394
+ });
395
+ }
396
+ };
397
+ /**
337
398
  * Check whether an error is a {@link CommandNotFoundError}.
338
399
  *
339
400
  * `instanceof` alone is not enough: `@gunshi/plugin` is bundled with its own copy of this
@@ -351,6 +412,17 @@ function isCommandNotFoundError(error) {
351
412
  return error instanceof Error && error.name === "CommandNotFoundError";
352
413
  }
353
414
  /**
415
+ * Check whether an error is a {@link CommandResolutionError}.
416
+ *
417
+ * @param error - An unknown error
418
+ * @returns `true` when the error has the command-resolution brand and shape
419
+ */
420
+ function isCommandResolutionError(error) {
421
+ if (error instanceof CommandResolutionError) return true;
422
+ if (!isRecord(error) || !hasCommandResolutionErrorShape(error)) return false;
423
+ return Object.hasOwn(error, COMMAND_RESOLUTION_ERROR_BRAND) && error[COMMAND_RESOLUTION_ERROR_BRAND] === true;
424
+ }
425
+ /**
354
426
  * Check whether an error is an {@link ArgsValidationError}.
355
427
  *
356
428
  * Prefer this over the `args-tokens` guard of the same name. Both recognize errors from another
@@ -394,6 +466,9 @@ function hasOptionalStringCode(error) {
394
466
  function hasCommandNotFoundErrorShape(error) {
395
467
  return hasOptionalStringCode(error) && isRecord(error.values) && typeof error.commandName === "string" && isStringArray(error.candidates) && isStringArray(error.commandPath);
396
468
  }
469
+ function hasCommandResolutionErrorShape(error) {
470
+ return hasOptionalStringCode(error) && isRecord(error.values) && isStringArray(error.commandPath) && Array.isArray(error.candidatePaths) && error.candidatePaths.every((path) => isStringArray(path));
471
+ }
397
472
  function hasArgsValidationErrorShape(error) {
398
473
  return hasOptionalStringCode(error) && isRecord(error.values);
399
474
  }
@@ -404,7 +479,7 @@ function hasArgsValidationErrorShape(error) {
404
479
  * @returns `true` if the validation error must be handled with priority
405
480
  */
406
481
  function hasPriorityValidationError(error) {
407
- return error?.errors.some((error) => isCommandNotFoundError(error) || isArgsValidationError(error) && error.code === ArgsValidationErrorKeys.unknownOption) ?? false;
482
+ return error?.errors.some((error) => isCommandNotFoundError(error) || isCommandResolutionError(error) || isArgsValidationError(error) && error.code === ArgsValidationErrorKeys.unknownOption) ?? false;
408
483
  }
409
484
  //#endregion
410
485
  //#region ../gunshi/src/plugin/core.ts
@@ -425,6 +500,7 @@ const NOOP_EXTENSION = () => {
425
500
  */
426
501
  function plugin(options = {}) {
427
502
  const { id, name, setup, onExtension, dependencies } = options;
503
+ if (typeof id !== "string" || id.length === 0) throw new Error("Plugin id must be a non-empty string");
428
504
  const extension = options.extension || NOOP_EXTENSION;
429
505
  const pluginFn = async (ctx) => {
430
506
  if (setup) await setup(ctx);
@@ -470,4 +546,4 @@ function plugin(options = {}) {
470
546
  * @license MIT
471
547
  */
472
548
  //#endregion
473
- export { ANONYMOUS_COMMAND_NAME, ArgsValidationError, ArgsValidationErrorKeys, CLI_OPTIONS_DEFAULT, CommandNotFoundError, CommandNotFoundErrorKeys, createCommandContext, hasPriorityValidationError, isArgsValidationError, isCommandNotFoundError, plugin };
549
+ export { ANONYMOUS_COMMAND_NAME, ArgsValidationError, ArgsValidationErrorKeys, CLI_OPTIONS_DEFAULT, CommandNotFoundError, CommandNotFoundErrorKeys, CommandResolutionError, CommandResolutionErrorKeys, createCommandContext, hasPriorityValidationError, isArgsValidationError, isCommandNotFoundError, isCommandResolutionError, plugin };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@gunshi/plugin",
3
3
  "description": "plugin development kit for gunshi",
4
- "version": "0.37.3",
4
+ "version": "1.0.0-beta.0",
5
5
  "author": {
6
6
  "name": "kazuya kawaguchi",
7
7
  "email": "kawakazu80@gmail.com"
@@ -56,7 +56,7 @@
56
56
  "jsr-exports-lint": "^0.4.2",
57
57
  "publint": "^0.3.20",
58
58
  "tsdown": "0.21.0",
59
- "gunshi": "0.37.3"
59
+ "gunshi": "1.0.0-beta.0"
60
60
  },
61
61
  "scripts": {
62
62
  "build": "tsdown",