@gunshi/shared 0.37.3 → 1.0.0-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/lib/index.d.ts +285 -100
  2. package/lib/index.js +117 -21
  3. package/package.json +4 -4
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,21 @@ 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
- /**
55
- * Parser Options.
56
- */
57
58
  //#endregion
58
- //#region ../../node_modules/.pnpm/args-tokens@0.29.0/node_modules/args-tokens/lib/resolver.d.ts
59
+ //#region ../../node_modules/.pnpm/args-tokens@1.0.0-beta.1/node_modules/args-tokens/lib/resolver.d.ts
59
60
  //#region src/resolver.d.ts
60
61
  /**
61
62
  * An argument schema definition for command-line argument parsing.
@@ -101,19 +102,25 @@ interface ArgSchema {
101
102
  /**
102
103
  * Type of the argument value.
103
104
  *
104
- * - `'string'`: Text value (default if not specified)
105
- * - `'boolean'`: `true`/`false` flag (can be negatable with `--no-` prefix)
105
+ * - `'string'`: Text value
106
+ * - `'boolean'`: `true`/`false` flag (can be negatable with `--no-` prefix). `--flag=true` and
107
+ * `--flag=false` set the value explicitly; any other value after `=` is a type error
106
108
  * - `'number'`: Numeric value (parsed as integer or float)
107
- * - `'enum'`: One of predefined string values (requires `choices` property)
109
+ * - `'enum'`: One of predefined string values (requires `choices` property, unless the argument
110
+ * has a `parse` function)
108
111
  * - `'positional'`: Non-option argument by position
109
112
  * - `'custom'`: Custom parsing with user-defined `parse` function
110
113
  *
114
+ * Any other `type`, or no `type`, is a mistake that only untyped code can make: if the argument
115
+ * has no `parse` function, {@link resolveArgs} and `parse()` throw an `Error`, whether or not the
116
+ * argument is given.
117
+ *
111
118
  * @example
112
119
  * Different argument types:
113
120
  * ```ts
114
121
  * {
115
122
  * name: { type: 'string' }, // --name value
116
- * verbose: { type: 'boolean' }, // --verbose or --no-verbose
123
+ * verbose: { type: 'boolean' }, // --verbose (--no-verbose needs negatable: true)
117
124
  * port: { type: 'number' }, // --port 3000
118
125
  * level: { type: 'enum', choices: ['debug', 'info'] },
119
126
  * file: { type: 'positional' }, // first positional arg
@@ -188,14 +195,32 @@ interface ArgSchema {
188
195
  /**
189
196
  * Marks the argument as required.
190
197
  *
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
198
+ * When `true`, the argument must be provided by the user. If it is missing, the error is an
199
+ * `ArgResolveError` with type 'required' and the code `err:arg:required-option`
200
+ * ({@link ArgsValidationErrorKeys}.requiredOption), or `err:arg:required-positional`
201
+ * ({@link ArgsValidationErrorKeys}.requiredPositional) for a positional argument. Its
202
+ * `values` has the `displayName` as in the message, such as `'--name'` for an option
203
+ * (`'--name' or '-n'` with the short name `n`) and `'file'` for a positional argument, and
204
+ * the `name`, which is the schema key.
205
+ * An option that is given without a value is reported as `err:arg:missing-value`
206
+ * ({@link ArgsValidationErrorKeys}.missingValue) instead, because the option itself was given.
207
+ * An explicit empty value, such as `--name=` or `-n ''`, is still reported as required, but the
208
+ * option counts as given: it is `true` in `explicit` and takes part in conflicts, as any other
209
+ * given option does.
210
+ *
211
+ * For single-value positional arguments, omitting `required` keeps the argument required for
212
+ * compatibility, unless it has a `default`, which makes it optional. A `multiple` positional
213
+ * argument is optional unless `required: true` is set. Set `required: false` to make a positional
214
+ * argument explicitly optional. Optional positional arguments leave enough input values for later
197
215
  * required positional arguments before consuming a value.
198
216
  *
217
+ * In the type of the values, such as {@link ArgValues}, a single-value positional argument whose
218
+ * `required` may be `false`, such as one of type `boolean`, is optional, as it may be missing,
219
+ * unless it has a `default`. An optional `required` of type `boolean`, as declared here, says
220
+ * nothing, and keeps it required. TypeScript widens a `required: true` to `boolean` in a schema
221
+ * written apart from the call, such as `{ type: 'positional' as const, required: true }`, which
222
+ * types the argument as optional: write such a schema `as const`.
223
+ *
199
224
  * @example
200
225
  * Required arguments:
201
226
  * ```ts
@@ -216,8 +241,9 @@ interface ArgSchema {
216
241
  /**
217
242
  * Allows the argument to accept multiple values.
218
243
  *
219
- * When `true`, the resolved value becomes an array.
220
- * For options: can be specified multiple times (--tag foo --tag bar)
244
+ * When `true`, the resolved value becomes an array. When the argument is not given and has no
245
+ * `default`, its value is `undefined`, not an empty array.
246
+ * For options: can be specified multiple times (--tags foo --tags bar)
221
247
  * For positional: collects remaining positional arguments after preserving values for
222
248
  * later required positional arguments.
223
249
  *
@@ -249,6 +275,12 @@ interface ArgSchema {
249
275
  *
250
276
  * Only applicable to `type: 'boolean'` arguments.
251
277
  *
278
+ * The negated name is always `no-` followed by the full option name. An option named
279
+ * `no-cache` is negated by `--no-no-cache`, and `--no-cache` sets it to `true`.
280
+ *
281
+ * The negated form does not take a value. `--no-flag=<value>` is reported as
282
+ * `err:arg:unexpected-value` ({@link ArgsValidationErrorKeys}.unexpectedValue).
283
+ *
252
284
  * @example
253
285
  * Negatable boolean:
254
286
  * ```ts
@@ -267,8 +299,17 @@ interface ArgSchema {
267
299
  /**
268
300
  * Array of allowed string values for enum-type arguments.
269
301
  *
270
- * Required when `type: 'enum'`. The argument value must be one of these choices,
271
- * otherwise an `ArgResolveError` with type 'type' will be thrown.
302
+ * Required when `type: 'enum'`, unless the argument has a `parse` function: if `choices` is
303
+ * missing or not an array, {@link resolveArgs} and `parse()` throw a `TypeError`, whether or not
304
+ * the argument is given. With a `parse` function and no `choices`, the value is passed to the
305
+ * function as for a `string` argument with a `parse` function.
306
+ *
307
+ * The argument value must be one of these choices, otherwise the error is an `ArgResolveError`
308
+ * with type 'type' and the code `err:arg:invalid-choice`
309
+ * ({@link ArgsValidationErrorKeys}.invalidChoice).
310
+ *
311
+ * The value is checked before `parse` is called, so a `parse` function receives only one of
312
+ * these choices and can change it, for example to upper case.
272
313
  *
273
314
  * Supports both mutable arrays and readonly arrays for type safety.
274
315
  *
@@ -292,18 +333,37 @@ interface ArgSchema {
292
333
  */
293
334
  choices?: string[] | readonly string[];
294
335
  /**
295
- * Default value used when the argument is not provided.
336
+ * Default value used when the argument is not provided. An option that is given without a value,
337
+ * or with a value that is rejected, also gets its default, along with the error.
296
338
  *
297
339
  * The type must match the argument's `type` property:
298
340
  * - `string` type: string default
299
341
  * - `boolean` type: boolean default
300
342
  * - `number` type: number default
301
- * - `enum` type: must be one of the `choices` values
343
+ * - `enum` type: one of the `choices` values, or a value that a `parse` of your own returns
302
344
  * - `positional`/`custom` type: string, boolean, or number default
303
345
  *
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.
346
+ * The default is used as is and never goes through `parse`, including when an option is given
347
+ * without a value. An explicit empty value, such as `--name=` or `-n ''`, is a value, not a
348
+ * missing one: a `string` option without `parse` gets `''` instead of the default, unless it is
349
+ * `required`. What `parse` returns is a value too, even `undefined` or `null`, and the default
350
+ * does not replace it.
351
+ *
352
+ * The value of a `multiple` argument is an array, so its default becomes the only element of the
353
+ * array: `default: 'latest'` gives `['latest']`.
354
+ *
355
+ * The default of an `enum` option with `choices` is checked when it would be used, that is, when
356
+ * no value from the command line is used: one that is not one of the choices is reported as an
357
+ * `ArgResolveError` with type 'type' and the code `err:arg:invalid-default`
358
+ * ({@link ArgsValidationErrorKeys}.invalidDefault), and is not used. With a `parse` function of
359
+ * your own, or a `map()` transform, the default is a value that the function returns, which need
360
+ * not be one of the choices, and it is not checked. `choice()` returns the value as is, so its
361
+ * default is checked.
362
+ *
363
+ * For positional arguments, `multiple` ones included, the default is used when no value is left
364
+ * for the argument: when the positional values run out, or when the remaining ones are preserved
365
+ * for later required positional arguments. With `required: true`, the default is not used, and
366
+ * the argument is reported as required instead.
307
367
  *
308
368
  * @example
309
369
  * Default values by type:
@@ -336,7 +396,8 @@ interface ArgSchema {
336
396
  * When `true`, a property like `maxCount` becomes available as `--max-count`.
337
397
  * This allows [CAC](https://github.com/cacjs/cac) user-friendly property names while maintaining CLI conventions.
338
398
  *
339
- * Can be overridden globally with `resolveArgs({ toKebab: true })`.
399
+ * The `toKebab` option of {@link resolveArgs} and `parse()` applies it to all arguments, as in
400
+ * `resolveArgs(args, tokens, { toKebab: true })`.
340
401
  *
341
402
  * Note: Only `true` is allowed (not `false`) to make intent explicit.
342
403
  *
@@ -360,8 +421,19 @@ interface ArgSchema {
360
421
  /**
361
422
  * Names of other options that conflict with this option.
362
423
  *
363
- * When this option is used together with any of the conflicting options,
364
- * an `ArgResolveError` with type 'conflict' will be thrown.
424
+ * When this option is used together with any of the conflicting options, the error is an
425
+ * `ArgResolveError` with type 'conflict' and the code `err:arg:conflict`
426
+ * ({@link ArgsValidationErrorKeys}.conflict). Its `values` has the `displayName` and `name` of
427
+ * the argument whose `conflicts` names the other one, and the `conflictDisplayName` and
428
+ * `conflictName` of the other one. `displayName` and `conflictDisplayName` show an option as
429
+ * it was written, such as `'-p'`, and `name` and `conflictName` are the schema keys. When both
430
+ * name each other, `name` is the one that comes first in the schema.
431
+ *
432
+ * A positional argument can be on either side, such as `[file]` and `--stdin`. It conflicts when
433
+ * it is given, and it is shown by its name, such as `'file'` (in kebab-case with `toKebab`), as
434
+ * in its other errors. The message starts with the kind of the argument given as `name`:
435
+ * `Positional argument 'file' conflicts with '--stdin'` or
436
+ * `Optional argument '--stdin' conflicts with 'file'`.
365
437
  *
366
438
  * Conflicts only need to be defined on one side - if option A defines a conflict
367
439
  * with option B, the conflict is automatically detected when both are used,
@@ -399,7 +471,7 @@ interface ArgSchema {
399
471
  * // No conflicts defined, but still cannot use with --summer
400
472
  * }
401
473
  * }
402
- * // Usage: --summer --autumn will throw error
474
+ * // Usage: --summer --autumn reports an error
403
475
  * // Error: "Optional argument '--summer' conflicts with '--autumn'"
404
476
  * ```
405
477
  *
@@ -451,6 +523,10 @@ interface ArgSchema {
451
523
  * Particularly useful for `type: 'custom'` arguments where the type
452
524
  * name would otherwise be unhelpful.
453
525
  *
526
+ * For a `custom` option that is given without a value, it is also the `expected` in the `values`
527
+ * of the `err:arg:missing-value` error ({@link ArgsValidationErrorKeys}.missingValue), which is
528
+ * `'custom'` without it.
529
+ *
454
530
  * @example
455
531
  * Metavar usage:
456
532
  * ```ts
@@ -467,13 +543,37 @@ interface ArgSchema {
467
543
  */
468
544
  metavar?: string;
469
545
  /**
470
- * Custom parsing function for `type: 'custom'` arguments.
546
+ * Custom parsing function, used in place of the parsing of the argument's `type`.
471
547
  *
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.
548
+ * Required when `type: 'custom'`: if it is missing or not a function, {@link resolveArgs} and
549
+ * `parse()` throw a `TypeError`, whether or not the argument is given. The function receives the
550
+ * raw string value and must return the parsed result. It should throw an Error (or subclass) if
551
+ * parsing fails.
474
552
  *
475
553
  * The function's return type becomes the resolved argument type.
476
554
  *
555
+ * `parse` is called synchronously, and what it returns becomes the value, even `undefined` or
556
+ * `null`, so throw to reject a value. An `async` function returns a promise, and the promise
557
+ * becomes the value as is: it is not awaited, and its rejection is not reported as an error.
558
+ * Await the value, or each of its elements with `multiple` (for example with `Promise.all()`),
559
+ * and handle the rejection yourself: a rejection that nothing handles is an unhandled rejection,
560
+ * which ends a Node.js process by default.
561
+ *
562
+ * A `boolean` option calls `parse` with `'true'`, or `'false'` for the negated form. Other
563
+ * options call it only with a value from the command line: when the option is given without a
564
+ * value, `parse` is not called and the missing value is reported as `err:arg:missing-value`
565
+ * ({@link ArgsValidationErrorKeys}.missingValue). When that error may suggest the argument after
566
+ * the option as its value, such as `--port=-5` for `--port -5`, a `parse` function of your own
567
+ * is not called to check it either: only the `parse` functions of `string()`, `number()`,
568
+ * `integer()`, `float()` and `choice()`, which have no side effects, are called for that.
569
+ * An explicit empty value, such as `--name=` or `-n=`, is passed as `''` unless
570
+ * `required: true` is set.
571
+ *
572
+ * An `enum` option with `choices` calls it only with one of them. Any other value, an explicit
573
+ * empty one included, is reported as `err:arg:invalid-choice`
574
+ * ({@link ArgsValidationErrorKeys}.invalidChoice), except that a required option reports an
575
+ * explicit empty value as required.
576
+ *
477
577
  * @param value - Raw string value from command line
478
578
  * @returns Parsed value of any type
479
579
  * @throws {Error} Error or subclass when value is invalid
@@ -519,62 +619,85 @@ interface Args {
519
619
  /**
520
620
  * An object that contains the values of the arguments.
521
621
  *
622
+ * The value of an argument whose schema is a union, such as
623
+ * `strict ? multiple(integer()) : string()` with the combinators, is typed as a value of any of its
624
+ * schemas: `number[] | string`. The argument is typed as present only when each schema of the
625
+ * union gives it a value, with a default, with `required: true` or as a required positional
626
+ * argument.
627
+ *
628
+ * When the type of one schema covers that of the other, as the type of `integer()` covers that of
629
+ * `multiple(integer())`, TypeScript types a `?:` expression of them as the covering schema alone:
630
+ * the value of `strict ? multiple(integer()) : integer()` is typed without the array, and
631
+ * `strict ? multiple(positional()) : positional()` as present, although it may be missing. Give
632
+ * each schema its own argument instead, or give the expression the type of both schemas with `as`,
633
+ * as in `(strict ? many : one) as typeof many | typeof one` for `const many = multiple(integer())`
634
+ * and `const one = integer()`.
635
+ *
522
636
  * @typeParam T - {@link Args | Arguments} which is an object that defines the command line arguments.
523
637
  */
524
- type ArgValues<T> = T extends Args ? ResolveArgValues<T, { [Arg in keyof T]: ExtractOptionValue<T[Arg]> }> : {
638
+ type ArgValues<T> = T extends Args ? ResolveArgValues<T, { [Arg in keyof T]: ExtractOptionValue<T[Arg]>; }> : {
525
639
  [option: string]: string | boolean | number | (string | boolean | number)[] | undefined;
526
640
  };
527
641
  /**
528
642
  * Extracts the value type from the argument schema.
643
+ * For a union of schemas, it is the union of the value types of its schemas.
529
644
  *
530
645
  * @typeParam A - {@link ArgSchema | Argument schema} which is an object that defines command line arguments.
531
646
  *
532
647
  * @internal
533
648
  */
534
- 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;
649
+ type ExtractOptionValue<A extends ArgSchema> = A extends ArgSchema ? ExtractSchemaValue<A> : never;
650
+ /**
651
+ * The value type of one schema, which {@link ExtractOptionValue} takes for each schema of a union.
652
+ */
653
+ 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;
535
654
  type ResolveOptionValue<A extends ArgSchema, T> = A['multiple'] extends true ? T[] : T;
536
655
  /**
537
656
  * Resolved argument values.
538
657
  *
658
+ * Each argument is mapped as optional, and the ones that are present, as {@link IsPresentArg}
659
+ * says, are mapped again as present. The optional mapping types a present argument as `unknown`:
660
+ * TypeScript does not reduce an intersection such as
661
+ * `(string | number[] | undefined) & (string | number[])`, of a value type that is a union with an
662
+ * object type. It maps all the keys without renaming them, which lets TypeScript relate the values
663
+ * of related type parameters, so that a conversion such as `values as ArgValues<A>` compiles.
664
+ *
539
665
  * @typeParam A - {@link Arguments | Args} which is an object that defines the command line arguments.
540
666
  * @typeParam V - Resolvable argument values.
541
667
  *
542
668
  * @internal
543
669
  */
544
- 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;
670
+ 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;
545
671
  /**
546
- * Filters the arguments based on their default values.
547
- *
548
- * @typeParam A - {@link Args | Arguments}, which is an object that defines the command line arguments.
549
- * @typeParam V - Resolvable argument values.
550
- * @typeParam K - Key of the {@link ArgSchema | argument schema} to filter by.
551
- *
552
- * @internal
672
+ * Whether an argument with the schema `S` has a value: with a default, with `required: true` or as
673
+ * a required positional argument. For a union of schemas, only when each schema of the union has
674
+ * one. A `default` or `required` typed as `any`, and a schema typed as `any`, count as giving a
675
+ * value, as {@link FilterArgs} does.
553
676
  */
554
- 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] };
677
+ type IsPresentArg<S extends ArgSchema> = S extends ArgSchema ? true extends (S['default'] extends {} ? true : S['required'] extends true ? true : false) ? true : IsRequiredPositionalArg<S> : never;
678
+ 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;
555
679
  /**
556
- * Filters positional arguments from the argument schema.
557
- *
558
- * @typeParam A - {@link Args | Arguments}, which is an object that defines the command line arguments.
559
- * @typeParam V - Resolvable argument values.
560
- *
561
- * @internal
562
- */
563
- 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] };
564
- 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;
565
- /**
566
- * An arguments for {@link resolveArgs | resolve arguments}.
680
+ * Whether the `required` of `A` may be `false`. An optional `required` of type `boolean`, as in
681
+ * {@link ArgSchema}, says nothing, and is read as missing, so that a positional argument with it is
682
+ * required. A `required` that `A` always has may be `false` when its type is `boolean` or
683
+ * `boolean | undefined`.
567
684
  */
568
-
685
+ type MayBeUnrequired<A extends ArgSchema> = false extends A['required'] ? [A] extends [{
686
+ required: unknown;
687
+ }] ? true : boolean | undefined extends A['required'] ? false : true : false;
569
688
  /**
570
689
  * Tracks which arguments were explicitly provided by the user.
571
690
  *
572
- * Each property indicates whether the corresponding argument was explicitly
573
- * provided (true) or is using a default value or not provided (false).
691
+ * Each property is `true` when the argument is given on the command line, and `false` when it is
692
+ * not, whether it has a default or not. An option is given when one of its forms is, such as
693
+ * `--port`, `-p` or `--no-color`, even if its value is missing or rejected: the error is reported,
694
+ * and if no value from the command line is used, its default, if any, fills in the value. A
695
+ * positional argument is given when a positional value is used for it, even if `parse` rejects
696
+ * the value: the error is reported, and its default is not used.
574
697
  *
575
698
  * @typeParam A - {@link Args | Arguments}, which is an object that defines the command line arguments.
576
699
  */
577
- type ArgExplicitlyProvided<A extends Args> = { [K in keyof A]: boolean };
700
+ type ArgExplicitlyProvided<A extends Args> = { [K in keyof A]: boolean; };
578
701
  //#endregion
579
702
  //#region ../gunshi/src/types.d.ts
580
703
  /**
@@ -721,7 +844,11 @@ interface CommandEnvironment<G extends GunshiParamsConstraint = DefaultGunshiPar
721
844
  */
722
845
  usageOptionValue: boolean;
723
846
  /**
724
- * Whether to display the command usage.
847
+ * Whether to keep usage, header, version, and validation-error text off the terminal
848
+ * (they are still returned as strings) and to silence {@linkcode CommandContext.log}.
849
+ *
850
+ * Output that must still appear — machine-readable results for an agent, warnings for the
851
+ * CLI author — should use `console.log` / `console.warn`, not `ctx.log`.
725
852
  *
726
853
  * @default false
727
854
  * @see {@linkcode CliOptions.usageSilent}
@@ -740,6 +867,26 @@ interface CommandEnvironment<G extends GunshiParamsConstraint = DefaultGunshiPar
740
867
  * @see {@linkcode CliOptions.subCommands}
741
868
  */
742
869
  subCommands: Map<string, Command<any> | LazyCommand<any>> | undefined;
870
+ /**
871
+ * The entry command of the CLI, marked with `entry: true`.
872
+ *
873
+ * It is available whether or not the CLI has sub-commands, while {@linkcode CommandEnvironment.subCommands}
874
+ * includes the entry command only when the sub-commands are given with {@linkcode CliOptions.subCommands}.
875
+ * It is not frozen, like the commands in {@linkcode CommandEnvironment.subCommands}.
876
+ */
877
+ entryCommand?: Command<any> | LazyCommand<any>;
878
+ /**
879
+ * The global options that are in effect for the command being executed.
880
+ *
881
+ * A plugin registers a global option with `addGlobalOption`, and gunshi merges it into the arguments
882
+ * of the command that runs. An argument that the command declares under the same name replaces it,
883
+ * and the option is then not in effect: the value under that name is the command's, and the plugin
884
+ * that registered it must not read it as its own.
885
+ *
886
+ * The schema is the one in effect, which may have given up its short name to an argument of the
887
+ * command that claims the same letter.
888
+ */
889
+ globalOptions?: ReadonlyMap<string, ArgSchema>;
743
890
  /**
744
891
  * Render function the command usage.
745
892
  */
@@ -1087,7 +1234,7 @@ type CommandExamplesFetcher<G extends GunshiParamsConstraint = DefaultGunshiPara
1087
1234
  */
1088
1235
  type CommandRunner<G extends GunshiParamsConstraint = DefaultGunshiParams> = (ctx: Readonly<CommandContext<G>>) => Awaitable<string | void>;
1089
1236
  //#endregion
1090
- //#region ../../node_modules/.pnpm/args-tokens@0.29.0/node_modules/args-tokens/lib/utils.d.ts
1237
+ //#region ../../node_modules/.pnpm/args-tokens@1.0.0-beta.1/node_modules/args-tokens/lib/utils.d.ts
1091
1238
  //#region src/utils.d.ts
1092
1239
  /**
1093
1240
  * Entry point of utils.
@@ -1113,12 +1260,18 @@ declare function kebabnize(str: string): string;
1113
1260
  * Check if the given command is a {@link LazyCommand}.
1114
1261
  *
1115
1262
  * @param cmd - A command to check
1116
- * @returns `true` if the command is a {@link LazyCommand}, otherwise `false
1263
+ * @returns `true` if the command is a {@link LazyCommand}, otherwise `false`
1264
+ *
1265
+ * A lazy command is identified by its `commandName` property. The property may be
1266
+ * `undefined` when the lazy command has no definition name.
1117
1267
  */
1118
1268
  declare function isLazyCommand<G extends GunshiParamsConstraint = DefaultGunshiParams>(cmd: unknown): cmd is LazyCommand<G>;
1119
1269
  /**
1120
1270
  * Resolve a lazy command to a {@link Command}.
1121
1271
  *
1272
+ * If the loader returns a command, the properties of the loaded command take precedence,
1273
+ * and the properties that it does not define fall back to the definition that is given to `lazy`.
1274
+ *
1122
1275
  * @param cmd - A {@link Commandable} or {@link LazyCommand} to resolve
1123
1276
  * @param name - Optional name of the command, if not provided, it will use the name from the command itself.
1124
1277
  * @param needRunResolving - Whether to run the resolving function of the lazy command.
@@ -1132,6 +1285,19 @@ declare function resolveLazyCommand<G extends GunshiParamsConstraint = DefaultGu
1132
1285
  * @returns A new object with the specified prototype
1133
1286
  */
1134
1287
  declare function create<T>(obj?: object | null): T;
1288
+ /**
1289
+ * Resolve the arguments of a command, the way gunshi parses and renders them.
1290
+ *
1291
+ * The global options belong to no command definition, so they are merged into the arguments of the
1292
+ * command that runs. An argument of the command shadows the global option of the same name, and it
1293
+ * shadows the same way by short name: a global option gives up its short name to an argument of the
1294
+ * command that claims the same letter, and keeps its long name.
1295
+ *
1296
+ * @param globalOptions - The global options that plugins registered with `addGlobalOption`
1297
+ * @param args - The arguments that the command declares
1298
+ * @returns The merged arguments
1299
+ */
1300
+ declare function resolveCommandArgs<A extends Args = Args>(globalOptions?: ReadonlyMap<string, ArgSchema>, args?: A): A;
1135
1301
  /**
1136
1302
  * Log a message to the console.
1137
1303
  *
@@ -1182,24 +1348,25 @@ type CommonArgType = {
1182
1348
  };
1183
1349
  declare const COMMON_ARGS: CommonArgType;
1184
1350
  declare const COMMAND_BUILTIN_RESOURCE_KEYS: readonly ["USAGE", "COMMAND", "SUBCOMMAND", "COMMANDS", "ARGUMENTS", "OPTIONS", "EXAMPLES", "FORMORE", "NEGATABLE", "DEFAULT", "CHOICES"];
1185
- declare const ARG_ERROR_RESOURCE_KEYS: readonly ["err:arg:required-option", "err:arg:required-positional", "err:arg:invalid-type", "err:arg:invalid-choice", "err:arg:custom-parse", "err:arg:unknown-option"];
1186
- declare const COMMAND_ERROR_RESOURCE_KEYS: readonly ["err:cmd:not-found"];
1351
+ declare const ARG_ERROR_RESOURCE_KEYS: readonly ["err:arg:required-option", "err:arg:required-positional", "err:arg:invalid-type", "err:arg:invalid-choice", "err:arg:custom-parse", "err:arg:unknown-option", "err:arg:unexpected-value", "err:arg:missing-value", "err:arg:conflict", "err:arg:invalid-default"];
1352
+ declare const ARG_ERROR_HINT_RESOURCE_KEYS: readonly ["err:arg:missing-value:hint"];
1353
+ declare const COMMAND_ERROR_RESOURCE_KEYS: readonly ["err:cmd:not-found", "err:cmd:ambiguous", "err:cmd:inconsistent-options", "err:cmd:lazy-schema-mismatch"];
1187
1354
  declare const SUGGESTION_ERROR_RESOURCE_KEYS: readonly ["err:suggestion:did-you-mean"];
1188
1355
  //#endregion
1189
1356
  //#region src/types.d.ts
1190
- type RemoveIndexSignature<T> = { [K in keyof T as string extends K ? never : number extends K ? never : K]: T[K] };
1357
+ type RemoveIndexSignature<T> = { [K in keyof T as string extends K ? never : number extends K ? never : K]: T[K]; };
1191
1358
  /**
1192
- * Make all properties in T deeply writeable (not readonly)
1359
+ * Make all properties in T deeply writable (not readonly)
1193
1360
  */
1194
- type DeepWriteable<T> = T extends ((...args: any) => any) ? T : T extends readonly (infer U)[] ? DeepWriteable<U>[] : T extends object ? { -readonly [P in keyof T]: DeepWriteable<T[P]> } : T;
1361
+ type DeepWriteable<T> = T extends ((...args: any) => any) ? T : T extends readonly (infer U)[] ? DeepWriteable<U>[] : T extends object ? { -readonly [P in keyof T]: DeepWriteable<T[P]>; } : T;
1195
1362
  /**
1196
1363
  * Remove index signature from object or record type.
1197
1364
  */
1198
- type RemovedIndex<T> = RemoveIndexSignature<{ [K in keyof T]: T[K] }>;
1365
+ type RemovedIndex<T> = RemoveIndexSignature<{ [K in keyof T]: T[K]; }>;
1199
1366
  /**
1200
1367
  * Resolve a key on {@link Args}.
1201
1368
  */
1202
- type KeyOfArgs<A extends Args> = keyof A | { [K in keyof A]: A[K]['type'] extends 'boolean' ? A[K]['negatable'] extends true ? `no-${Extract<K, string>}` : never : never }[keyof A];
1369
+ type KeyOfArgs<A extends Args> = keyof A | { [K in keyof A]: A[K]['type'] extends 'boolean' ? A[K]['negatable'] extends true ? `no-${Extract<K, string>}` : never : never; }[keyof A];
1203
1370
  /**
1204
1371
  * Generate a namespaced key.
1205
1372
  */
@@ -1216,6 +1383,10 @@ type CommandBuiltinResourceKeys = (typeof COMMAND_BUILTIN_RESOURCE_KEYS)[number]
1216
1383
  * Args validation error resource keys.
1217
1384
  */
1218
1385
  type ArgErrorResourceKeys = (typeof ARG_ERROR_RESOURCE_KEYS)[number];
1386
+ /**
1387
+ * Resource keys of the hints that follow an args validation error.
1388
+ */
1389
+ type ArgErrorHintResourceKeys = (typeof ARG_ERROR_HINT_RESOURCE_KEYS)[number];
1219
1390
  /**
1220
1391
  * Command validation error resource keys.
1221
1392
  */
@@ -1227,7 +1398,7 @@ type SuggestionErrorResourceKeys = (typeof SUGGESTION_ERROR_RESOURCE_KEYS)[numbe
1227
1398
  /**
1228
1399
  * Error resource keys.
1229
1400
  */
1230
- type ErrorResourceKeys = ArgErrorResourceKeys | CommandErrorResourceKeys | SuggestionErrorResourceKeys;
1401
+ type ErrorResourceKeys = ArgErrorResourceKeys | ArgErrorHintResourceKeys | CommandErrorResourceKeys | SuggestionErrorResourceKeys;
1231
1402
  /**
1232
1403
  * Built-in resource keys.
1233
1404
  */
@@ -1250,21 +1421,17 @@ type CommandArgKeys<A extends Args, C = {}, K extends string = GenerateNamespace
1250
1421
  /**
1251
1422
  * Resolve translation keys for command context.
1252
1423
  */
1253
- type ResolveTranslationKeys<A extends Args, C = {},
1254
- // for CommandContext
1255
- E extends Record<string, string> = {},
1256
- // for extended resources
1257
- R extends string = keyof RemovedIndex<E>, T extends string = (C extends {
1424
+ type ResolveTranslationKeys<A extends Args, C = {} // for CommandContext
1425
+ , E extends Record<string, string> = {} // for extended resources
1426
+ , R extends string = keyof RemovedIndex<E>, T extends string = C extends {
1258
1427
  name: infer N;
1259
- } ? N extends string ? GenerateNamespacedKey<R, N> : R : R | CommandBuiltinKeys), O = CommandArgKeys<A, C>> = ErrorResourceKeys | CommandBuiltinKeys | O | T;
1428
+ } ? N extends string ? GenerateNamespacedKey<R, N> : R : R | CommandBuiltinKeys, O = CommandArgKeys<A, C>> = ErrorResourceKeys | CommandBuiltinKeys | O | T;
1260
1429
  /**
1261
1430
  * Translation function interface
1262
1431
  */
1263
- interface Translation<A extends Args, C = {},
1264
- // for CommandContext
1265
- E extends Record<string, string> = {},
1266
- // for extended resources
1267
- K = ResolveTranslationKeys<A, C, E>> {
1432
+ interface Translation<A extends Args, C = {} // for CommandContext
1433
+ , E extends Record<string, string> = {} // for extended resources
1434
+ , K = ResolveTranslationKeys<A, C, E>> {
1268
1435
  (key: K, values?: Record<string, unknown>): string;
1269
1436
  }
1270
1437
  //#endregion
@@ -1276,9 +1443,8 @@ K = ResolveTranslationKeys<A, C, E>> {
1276
1443
  * @typeParam C - Additional context type for command localization.
1277
1444
  * @typeParam E - Extended resource keys type.
1278
1445
  */
1279
- interface Localization<A extends Args, C = {},
1280
- // for CommandContext
1281
- E extends Record<string, string> = {}> {
1446
+ interface Localization<A extends Args, C = {} // for CommandContext
1447
+ , E extends Record<string, string> = {}> {
1282
1448
  <K = ResolveTranslationKeys<A, C, E>>(key: K, values?: Record<string, unknown>): Promise<string>;
1283
1449
  }
1284
1450
  /**
@@ -1295,11 +1461,9 @@ E extends Record<string, string> = {}> {
1295
1461
  * @param translate - Translation function
1296
1462
  * @returns Localizable function
1297
1463
  */
1298
- declare function localizable<A extends Args, C = {},
1299
- // for CommandContext
1300
- E extends Record<string, string> = {},
1301
- // for extended resources
1302
- K = ResolveTranslationKeys<A, C, E>>(ctx: CommandContext, cmd: Command, translate?: Translation<A, C, E, K>): Localization<A, C, E>;
1464
+ declare function localizable<A extends Args, C = {} // for CommandContext
1465
+ , E extends Record<string, string> = {} // for extended resources
1466
+ , K = ResolveTranslationKeys<A, C, E>>(ctx: CommandContext, cmd: Command, translate?: Translation<A, C, E, K>): Localization<A, C, E>;
1303
1467
  /**
1304
1468
  * Format a resource message by replacing placeholder values.
1305
1469
  *
@@ -1309,7 +1473,7 @@ K = ResolveTranslationKeys<A, C, E>>(ctx: CommandContext, cmd: Command, translat
1309
1473
  */
1310
1474
  declare function formatResource(resource: string | undefined, values?: Record<string, unknown>): string | undefined;
1311
1475
  //#endregion
1312
- //#region ../resources/locales/en-US.d.ts
1476
+ //#region ../resources/locales/en-US.json.d.ts
1313
1477
  declare const _exports: {
1314
1478
  COMMAND: string;
1315
1479
  COMMANDS: string;
@@ -1330,7 +1494,15 @@ declare const _exports: {
1330
1494
  "err:arg:invalid-choice": string;
1331
1495
  "err:arg:custom-parse": string;
1332
1496
  "err:arg:unknown-option": string;
1497
+ "err:arg:unexpected-value": string;
1498
+ "err:arg:missing-value": string;
1499
+ "err:arg:missing-value:hint": string;
1500
+ "err:arg:conflict": string;
1501
+ "err:arg:invalid-default": string;
1333
1502
  "err:cmd:not-found": string;
1503
+ "err:cmd:ambiguous": string;
1504
+ "err:cmd:inconsistent-options": string;
1505
+ "err:cmd:lazy-schema-mismatch": string;
1334
1506
  "err:suggestion:did-you-mean": string;
1335
1507
  };
1336
1508
  //#endregion
@@ -1370,7 +1542,7 @@ declare function resolveArgKey<A extends Args = DefaultGunshiParams['args'], K e
1370
1542
  * @param name - The command name.
1371
1543
  * @returns Prefixed non-built-in key.
1372
1544
  */
1373
- declare function resolveKey<T extends Record<string, string> = {}, K extends string = (keyof T extends string ? keyof T : string)>(key: K, name?: string): string;
1545
+ declare function resolveKey<T extends Record<string, string> = {}, K extends string = keyof T extends string ? keyof T : string>(key: K, name?: string): string;
1374
1546
  /**
1375
1547
  * Resolve command examples.
1376
1548
  *
@@ -1399,12 +1571,25 @@ declare function namespacedId<K extends string>(id: K): GenerateNamespacedKey<K,
1399
1571
  * @returns A string representing the short and long option pair.
1400
1572
  */
1401
1573
  declare function makeShortLongOptionPair(schema: ArgSchema, name: string, toKebab?: boolean): string;
1402
- //#endregion
1403
- //#region src/index.d.ts
1404
1574
  /**
1405
- * @author kazuya kawaguchi (a.k.a. kazupon)
1406
- * @license MIT
1407
- */
1408
-
1575
+ * Resolve the name that an argument is parsed and rendered under.
1576
+ *
1577
+ * @param name - The key of the argument.
1578
+ * @param schema - The {@linkcode ArgSchema | argument schema}.
1579
+ * @param toKebab - Whether to convert the name to kebab-case.
1580
+ * @returns The name of the argument, kebab-cased when `toKebab` asks for it.
1581
+ */
1582
+ declare function resolveDisplayName(name: string, schema: ArgSchema, toKebab?: boolean): string;
1583
+ /**
1584
+ * Collect the names that the arguments are parsed and rendered under.
1585
+ *
1586
+ * A positional argument is left out: it is never spelled as an option, so it cannot take the name of
1587
+ * one. A `hidden` argument is counted, because it still owns the name that it parses.
1588
+ *
1589
+ * @param args - The {@linkcode Args | arguments} of a command, global options included.
1590
+ * @param toKebab - Whether the command converts its names to kebab-case.
1591
+ * @returns The set of names.
1592
+ */
1593
+ declare function resolveOptionNames(args: Args, toKebab?: boolean): Set<string>;
1409
1594
  //#endregion
1410
- export { ARG_ERROR_RESOURCE_KEYS, ARG_NEGATABLE_PREFIX, ARG_PREFIX, ARG_PREFIX_AND_KEY_SEPARATOR, ArgErrorResourceKeys, BUILD_IN_PREFIX_AND_KEY_SEPARATOR, BUILT_IN_KEY_SEPARATOR, BUILT_IN_PREFIX, BuiltinResource, BuiltinResourceKeys, COMMAND_BUILTIN_RESOURCE_KEYS, COMMAND_ERROR_RESOURCE_KEYS, COMMON_ARGS, CommandArgKeys, CommandBuiltinArgsKeys, CommandBuiltinKeys, CommandBuiltinResourceKeys, CommandErrorResourceKeys, DeepWriteable, _exports as DefaultResource, ERROR_PREFIX, ERROR_PREFIX_AND_KEY_SEPARATOR, ErrorResourceKeys, GenerateNamespacedKey, KeyOfArgs, Localization, PLUGIN_PREFIX, RemovedIndex, ResolveTranslationKeys, SUGGESTION_ERROR_RESOURCE_KEYS, SuggestionErrorResourceKeys, Translation, create, deepFreeze, formatResource, getCommandSubCommands, isLazyCommand, kebabnize, localizable, log, makeShortLongOptionPair, namespacedId, resolveArgKey, resolveBuiltInKey, resolveExamples, resolveKey, resolveLazyCommand };
1595
+ export { ARG_ERROR_HINT_RESOURCE_KEYS, ARG_ERROR_RESOURCE_KEYS, ARG_NEGATABLE_PREFIX, ARG_PREFIX, ARG_PREFIX_AND_KEY_SEPARATOR, type ArgErrorHintResourceKeys, type ArgErrorResourceKeys, BUILD_IN_PREFIX_AND_KEY_SEPARATOR, BUILT_IN_KEY_SEPARATOR, BUILT_IN_PREFIX, type BuiltinResource, type BuiltinResourceKeys, COMMAND_BUILTIN_RESOURCE_KEYS, COMMAND_ERROR_RESOURCE_KEYS, COMMON_ARGS, type CommandArgKeys, type CommandBuiltinArgsKeys, type CommandBuiltinKeys, type CommandBuiltinResourceKeys, type CommandErrorResourceKeys, type DeepWriteable, _exports as DefaultResource, ERROR_PREFIX, ERROR_PREFIX_AND_KEY_SEPARATOR, type ErrorResourceKeys, type GenerateNamespacedKey, type KeyOfArgs, Localization, PLUGIN_PREFIX, type RemovedIndex, type ResolveTranslationKeys, SUGGESTION_ERROR_RESOURCE_KEYS, type SuggestionErrorResourceKeys, type Translation, create, deepFreeze, formatResource, getCommandSubCommands, isLazyCommand, kebabnize, localizable, log, makeShortLongOptionPair, namespacedId, resolveArgKey, resolveBuiltInKey, resolveCommandArgs, resolveDisplayName, resolveExamples, resolveKey, resolveLazyCommand, resolveOptionNames };
package/lib/index.js CHANGED
@@ -1,4 +1,4 @@
1
- //#region ../../node_modules/.pnpm/args-tokens@0.29.0/node_modules/args-tokens/lib/utils.js
1
+ //#region ../../node_modules/.pnpm/args-tokens@1.0.0-beta.1/node_modules/args-tokens/lib/utils.js
2
2
  /**
3
3
  * Entry point of utils.
4
4
  *
@@ -29,14 +29,20 @@ function kebabnize(str) {
29
29
  * Check if the given command is a {@link LazyCommand}.
30
30
  *
31
31
  * @param cmd - A command to check
32
- * @returns `true` if the command is a {@link LazyCommand}, otherwise `false
32
+ * @returns `true` if the command is a {@link LazyCommand}, otherwise `false`
33
+ *
34
+ * A lazy command is identified by its `commandName` property. The property may be
35
+ * `undefined` when the lazy command has no definition name.
33
36
  */
34
37
  function isLazyCommand(cmd) {
35
- return typeof cmd === "function" && "commandName" in cmd && !!cmd.commandName;
38
+ return typeof cmd === "function" && "commandName" in cmd;
36
39
  }
37
40
  /**
38
41
  * Resolve a lazy command to a {@link Command}.
39
42
  *
43
+ * If the loader returns a command, the properties of the loaded command take precedence,
44
+ * and the properties that it does not define fall back to the definition that is given to `lazy`.
45
+ *
40
46
  * @param cmd - A {@link Commandable} or {@link LazyCommand} to resolve
41
47
  * @param name - Optional name of the command, if not provided, it will use the name from the command itself.
42
48
  * @param needRunResolving - Whether to run the resolving function of the lazy command.
@@ -52,6 +58,8 @@ async function resolveLazyCommand(cmd, name, needRunResolving = false) {
52
58
  examples: cmd.examples,
53
59
  internal: cmd.internal,
54
60
  entry: cmd.entry,
61
+ toKebab: cmd.toKebab,
62
+ rendering: cmd.rendering,
55
63
  subCommands: cmd.subCommands
56
64
  };
57
65
  if ("resource" in cmd && cmd.resource) baseCommand.resource = cmd.resource;
@@ -61,13 +69,20 @@ async function resolveLazyCommand(cmd, name, needRunResolving = false) {
61
69
  if (typeof loaded === "function") command.run = loaded;
62
70
  else if (typeof loaded === "object") {
63
71
  if (loaded.run == null) throw new TypeError(`'run' is required in command: ${cmd.name || name}`);
72
+ /**
73
+ * NOTE(kazupon): the loaded command wins, and the definition that is given to `lazy` is the fallback
74
+ * for what the loaded command does not define. A loader that returns `{ run }` keeps the whole definition,
75
+ * like a loader that returns the runner itself.
76
+ */
64
77
  command.run = loaded.run;
65
- command.name = loaded.name;
66
- command.description = loaded.description;
67
- command.args = loaded.args;
68
- command.examples = loaded.examples;
69
- command.internal = loaded.internal;
70
- command.entry = loaded.entry;
78
+ command.name = loaded.name ?? cmd.commandName;
79
+ command.description = loaded.description ?? cmd.description;
80
+ command.args = loaded.args ?? cmd.args;
81
+ command.examples = loaded.examples ?? cmd.examples;
82
+ command.internal = loaded.internal ?? cmd.internal;
83
+ command.entry = loaded.entry ?? cmd.entry;
84
+ command.toKebab = loaded.toKebab ?? cmd.toKebab;
85
+ command.rendering = loaded.rendering ?? cmd.rendering;
71
86
  command.subCommands = loaded.subCommands || cmd.subCommands;
72
87
  if ("resource" in loaded && loaded.resource) command.resource = loaded.resource;
73
88
  } else throw new TypeError(`Cannot resolve command: ${cmd.name || name}`);
@@ -86,6 +101,37 @@ function create(obj = null) {
86
101
  return Object.create(obj);
87
102
  }
88
103
  /**
104
+ * Resolve the arguments of a command, the way gunshi parses and renders them.
105
+ *
106
+ * The global options belong to no command definition, so they are merged into the arguments of the
107
+ * command that runs. An argument of the command shadows the global option of the same name, and it
108
+ * shadows the same way by short name: a global option gives up its short name to an argument of the
109
+ * command that claims the same letter, and keeps its long name.
110
+ *
111
+ * @param globalOptions - The global options that plugins registered with `addGlobalOption`
112
+ * @param args - The arguments that the command declares
113
+ * @returns The merged arguments
114
+ */
115
+ function resolveCommandArgs(globalOptions, args) {
116
+ return Object.assign(create(), resolveGlobalOptions(globalOptions, args), args);
117
+ }
118
+ function resolveGlobalOptions(globalOptions, args) {
119
+ if (!globalOptions) return;
120
+ const shortNames = /* @__PURE__ */ new Set();
121
+ for (const schema of Object.values(args || {})) if (schema.type !== "positional" && schema.short) shortNames.add(schema.short);
122
+ const resolved = create();
123
+ for (const [name, schema] of globalOptions)
124
+ /**
125
+ * NOTE(kazupon): a copy, because the schema is the one that the plugin registered, which every
126
+ * command of the CLI shares. Only this command gives up the short name.
127
+ */
128
+ resolved[name] = schema.short && shortNames.has(schema.short) ? {
129
+ ...schema,
130
+ short: void 0
131
+ } : schema;
132
+ return resolved;
133
+ }
134
+ /**
89
135
  * Log a message to the console.
90
136
  *
91
137
  * @param args - Arguments to log
@@ -173,9 +219,19 @@ const ARG_ERROR_RESOURCE_KEYS = [
173
219
  "err:arg:invalid-type",
174
220
  "err:arg:invalid-choice",
175
221
  "err:arg:custom-parse",
176
- "err:arg:unknown-option"
222
+ "err:arg:unknown-option",
223
+ "err:arg:unexpected-value",
224
+ "err:arg:missing-value",
225
+ "err:arg:conflict",
226
+ "err:arg:invalid-default"
227
+ ];
228
+ const ARG_ERROR_HINT_RESOURCE_KEYS = ["err:arg:missing-value:hint"];
229
+ const COMMAND_ERROR_RESOURCE_KEYS = [
230
+ "err:cmd:not-found",
231
+ "err:cmd:ambiguous",
232
+ "err:cmd:inconsistent-options",
233
+ "err:cmd:lazy-schema-mismatch"
177
234
  ];
178
- const COMMAND_ERROR_RESOURCE_KEYS = ["err:cmd:not-found"];
179
235
  const SUGGESTION_ERROR_RESOURCE_KEYS = ["err:suggestion:did-you-mean"];
180
236
  //#endregion
181
237
  //#region ../resources/locales/en-US.json
@@ -194,12 +250,20 @@ var en_US_default = {
194
250
  help: "Display this help message",
195
251
  version: "Display this version",
196
252
  "err:arg:required-option": "Optional argument {$displayName} is required",
197
- "err:arg:required-positional": "Positional argument {$name} is required",
253
+ "err:arg:required-positional": "Positional argument {$displayName} is required",
198
254
  "err:arg:invalid-type": "Invalid value for {$displayName}: expected {$expected}",
199
255
  "err:arg:invalid-choice": "Invalid value for {$displayName}: expected one of {$choices}",
200
256
  "err:arg:custom-parse": "Invalid value for {$displayName}: {$reason}",
201
257
  "err:arg:unknown-option": "Unknown option: {$rawName}",
258
+ "err:arg:unexpected-value": "Optional argument {$displayName} does not take a value",
259
+ "err:arg:missing-value": "Optional argument {$displayName} requires a value",
260
+ "err:arg:missing-value:hint": "(to pass '{$next}' as its value, write '{$suggestion}')",
261
+ "err:arg:conflict": "{$displayName} conflicts with {$conflictDisplayName}",
262
+ "err:arg:invalid-default": "Invalid default for {$displayName}: {$actual} is not one of {$choices}",
202
263
  "err:cmd:not-found": "Command not found: {$commandName}",
264
+ "err:cmd:ambiguous": "The command is ambiguous. Move options after the command name: {$candidatePaths}",
265
+ "err:cmd:inconsistent-options": "The options do not identify a consistent command. Move options after the command name.",
266
+ "err:cmd:lazy-schema-mismatch": "The lazy command definition does not match its loaded options. Declare leading options in the lazy definition or move options after the command name: {$commandPath}",
203
267
  "err:suggestion:did-you-mean": "Did you mean {$name}?"
204
268
  };
205
269
  //#endregion
@@ -282,10 +346,36 @@ function namespacedId(id) {
282
346
  * @returns A string representing the short and long option pair.
283
347
  */
284
348
  function makeShortLongOptionPair(schema, name, toKebab) {
285
- let key = `--${toKebab || schema.toKebab ? kebabnize(name) : name}`;
349
+ let key = `--${resolveDisplayName(name, schema, toKebab)}`;
286
350
  if (schema.short) key = `-${schema.short}, ${key}`;
287
351
  return key;
288
352
  }
353
+ /**
354
+ * Resolve the name that an argument is parsed and rendered under.
355
+ *
356
+ * @param name - The key of the argument.
357
+ * @param schema - The {@linkcode ArgSchema | argument schema}.
358
+ * @param toKebab - Whether to convert the name to kebab-case.
359
+ * @returns The name of the argument, kebab-cased when `toKebab` asks for it.
360
+ */
361
+ function resolveDisplayName(name, schema, toKebab) {
362
+ return toKebab || schema.toKebab ? kebabnize(name) : name;
363
+ }
364
+ /**
365
+ * Collect the names that the arguments are parsed and rendered under.
366
+ *
367
+ * A positional argument is left out: it is never spelled as an option, so it cannot take the name of
368
+ * one. A `hidden` argument is counted, because it still owns the name that it parses.
369
+ *
370
+ * @param args - The {@linkcode Args | arguments} of a command, global options included.
371
+ * @param toKebab - Whether the command converts its names to kebab-case.
372
+ * @returns The set of names.
373
+ */
374
+ function resolveOptionNames(args, toKebab) {
375
+ const names = /* @__PURE__ */ new Set();
376
+ for (const [name, schema] of Object.entries(args)) if (schema.type !== "positional") names.add(resolveDisplayName(name, schema, toKebab));
377
+ return names;
378
+ }
289
379
  //#endregion
290
380
  //#region src/localization.ts
291
381
  /**
@@ -313,15 +403,21 @@ function localizable(ctx, cmd, translate) {
313
403
  if (key.startsWith(ERROR_PREFIX_AND_KEY_SEPARATOR)) return resolveAndFormatResource(key, key, values);
314
404
  const namaspacedArgKey = resolveKey(ARG_PREFIX_AND_KEY_SEPARATOR, ctx.name);
315
405
  if (key.startsWith(namaspacedArgKey)) {
316
- let argKey = key.slice(namaspacedArgKey.length);
317
- let negatable = false;
406
+ const argKey = key.slice(namaspacedArgKey.length);
407
+ /**
408
+ * NOTE(kazupon): an argument describes itself, whatever it is called. `no-` is stripped only
409
+ * to reach the option that a negated form negates, and only when there is no argument under
410
+ * the name as written: `no-emoji` may be an argument of its own, and it then has nothing to do
411
+ * with `emoji`.
412
+ */
413
+ const ownSchema = ctx.args[argKey];
414
+ if (ownSchema) return ownSchema.description || "";
318
415
  if (argKey.startsWith("no-")) {
319
- argKey = argKey.slice(3);
320
- negatable = true;
416
+ const negatedKey = argKey.slice(3);
417
+ const schema = ctx.args[negatedKey];
418
+ if (schema && schema.type === "boolean" && schema.negatable) return `${en_US_default["NEGATABLE"]} ${makeShortLongOptionPair(schema, negatedKey, ctx.toKebab)}`;
321
419
  }
322
- const schema = ctx.args[argKey];
323
- if (!schema) return argKey;
324
- return negatable && schema.type === "boolean" && schema.negatable ? `${en_US_default["NEGATABLE"]} ${makeShortLongOptionPair(schema, argKey, ctx.toKebab)}` : schema.description || "";
420
+ return argKey;
325
421
  }
326
422
  if (key === resolveKey("description", ctx.name)) return "";
327
423
  else if (key === resolveKey("examples", ctx.name)) return await resolveExamples(ctx, cmd.examples);
@@ -351,4 +447,4 @@ function formatResource(resource, values = Object.create(null)) {
351
447
  * @license MIT
352
448
  */
353
449
  //#endregion
354
- export { ARG_ERROR_RESOURCE_KEYS, ARG_NEGATABLE_PREFIX, ARG_PREFIX, ARG_PREFIX_AND_KEY_SEPARATOR, BUILD_IN_PREFIX_AND_KEY_SEPARATOR, BUILT_IN_KEY_SEPARATOR, BUILT_IN_PREFIX, COMMAND_BUILTIN_RESOURCE_KEYS, COMMAND_ERROR_RESOURCE_KEYS, COMMON_ARGS, en_US_default as DefaultResource, ERROR_PREFIX, ERROR_PREFIX_AND_KEY_SEPARATOR, PLUGIN_PREFIX, SUGGESTION_ERROR_RESOURCE_KEYS, create, deepFreeze, formatResource, getCommandSubCommands, isLazyCommand, kebabnize, localizable, log, makeShortLongOptionPair, namespacedId, resolveArgKey, resolveBuiltInKey, resolveExamples, resolveKey, resolveLazyCommand };
450
+ export { ARG_ERROR_HINT_RESOURCE_KEYS, ARG_ERROR_RESOURCE_KEYS, ARG_NEGATABLE_PREFIX, ARG_PREFIX, ARG_PREFIX_AND_KEY_SEPARATOR, BUILD_IN_PREFIX_AND_KEY_SEPARATOR, BUILT_IN_KEY_SEPARATOR, BUILT_IN_PREFIX, COMMAND_BUILTIN_RESOURCE_KEYS, COMMAND_ERROR_RESOURCE_KEYS, COMMON_ARGS, en_US_default as DefaultResource, ERROR_PREFIX, ERROR_PREFIX_AND_KEY_SEPARATOR, PLUGIN_PREFIX, SUGGESTION_ERROR_RESOURCE_KEYS, create, deepFreeze, formatResource, getCommandSubCommands, isLazyCommand, kebabnize, localizable, log, makeShortLongOptionPair, namespacedId, resolveArgKey, resolveBuiltInKey, resolveCommandArgs, resolveDisplayName, resolveExamples, resolveKey, resolveLazyCommand, resolveOptionNames };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@gunshi/shared",
3
3
  "description": "shared utils for gunshi",
4
- "version": "0.37.3",
4
+ "version": "1.0.0-beta.1",
5
5
  "author": {
6
6
  "name": "kazuya kawaguchi",
7
7
  "email": "kawakazu80@gmail.com"
@@ -50,13 +50,13 @@
50
50
  }
51
51
  },
52
52
  "devDependencies": {
53
+ "@gunshi/resources": "1.0.0-beta.1",
53
54
  "deno": "^2.7.14",
55
+ "gunshi": "1.0.0-beta.1",
54
56
  "jsr": "^0.14.3",
55
57
  "jsr-exports-lint": "^0.4.2",
56
58
  "publint": "^0.3.20",
57
- "tsdown": "0.21.0",
58
- "gunshi": "0.37.3",
59
- "@gunshi/resources": "0.37.3"
59
+ "tsdown": "0.22.14"
60
60
  },
61
61
  "scripts": {
62
62
  "build": "tsdown",