@optique/core 1.1.0-dev.2069 → 1.1.0-dev.2077

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.
@@ -162,7 +162,7 @@ function _${programName} () {
162
162
 
163
163
  # Pre-expand file candidates. When the glob base came from the
164
164
  # program's pattern and contains wildcard characters (* or ?),
165
- # use it as-is via compgen -G (safe no command substitution).
165
+ # use it as-is via compgen -G (safe—no command substitution).
166
166
  # Otherwise append * to treat it as a prefix.
167
167
  # Note: [ is NOT treated as a glob indicator because it commonly
168
168
  # appears in literal filenames like [draft] or foo[1].txt.
@@ -375,7 +375,7 @@ function _${programName.replace(/[^a-zA-Z0-9]/g, "_")} () {
375
375
  [[ "\$__compare_pattern" == */* ]] && __compare_pattern="\${__compare_pattern%/*}/" || __compare_pattern=""
376
376
  fi
377
377
  if [[ ( -n "\$__compare_pattern" || -n "\$__norm_prefix" ) && \${#__norm_prefix} -ge \${#__compare_pattern} && "\${__norm_prefix[1,\${#__compare_pattern}]}" == "\$__compare_pattern" && "\$PREFIX" != "\$pattern" ]]; then
378
- # User typed an equivalent or extended form keep PREFIX
378
+ # User typed an equivalent or extended form—keep PREFIX
379
379
  true
380
380
  else
381
381
  PREFIX="\$pattern"
@@ -536,7 +536,7 @@ ${escapedArgs ? ` set -l output (${programName} ${escapedArgs} $prev $current
536
536
  end
537
537
  end
538
538
 
539
- # Expand tilde prefix for globbing fish does not expand ~
539
+ # Expand tilde prefix for globbing—fish does not expand ~
540
540
  # inside variable substitutions, so replace it with $HOME
541
541
  if string match -q '~/*' -- "$glob_base"
542
542
  set __tilde_prefix "~"
@@ -1186,7 +1186,7 @@ ${escapedArgs ? ` \$completionArgs += @(${escapedArgs})
1186
1186
  \$prefix = \$prefix + '/'
1187
1187
  }
1188
1188
 
1189
- # Build the glob path when the prefix contains wildcard
1189
+ # Build the glob path—when the prefix contains wildcard
1190
1190
  # characters, use it as-is; otherwise append *
1191
1191
  \$globPath = if (\$prefix -match '[\*\?]') { \$prefix } else { "\${prefix}*" }
1192
1192
 
@@ -162,7 +162,7 @@ function _${programName} () {
162
162
 
163
163
  # Pre-expand file candidates. When the glob base came from the
164
164
  # program's pattern and contains wildcard characters (* or ?),
165
- # use it as-is via compgen -G (safe no command substitution).
165
+ # use it as-is via compgen -G (safe—no command substitution).
166
166
  # Otherwise append * to treat it as a prefix.
167
167
  # Note: [ is NOT treated as a glob indicator because it commonly
168
168
  # appears in literal filenames like [draft] or foo[1].txt.
@@ -375,7 +375,7 @@ function _${programName.replace(/[^a-zA-Z0-9]/g, "_")} () {
375
375
  [[ "\$__compare_pattern" == */* ]] && __compare_pattern="\${__compare_pattern%/*}/" || __compare_pattern=""
376
376
  fi
377
377
  if [[ ( -n "\$__compare_pattern" || -n "\$__norm_prefix" ) && \${#__norm_prefix} -ge \${#__compare_pattern} && "\${__norm_prefix[1,\${#__compare_pattern}]}" == "\$__compare_pattern" && "\$PREFIX" != "\$pattern" ]]; then
378
- # User typed an equivalent or extended form keep PREFIX
378
+ # User typed an equivalent or extended form—keep PREFIX
379
379
  true
380
380
  else
381
381
  PREFIX="\$pattern"
@@ -536,7 +536,7 @@ ${escapedArgs ? ` set -l output (${programName} ${escapedArgs} $prev $current
536
536
  end
537
537
  end
538
538
 
539
- # Expand tilde prefix for globbing fish does not expand ~
539
+ # Expand tilde prefix for globbing—fish does not expand ~
540
540
  # inside variable substitutions, so replace it with $HOME
541
541
  if string match -q '~/*' -- "$glob_base"
542
542
  set __tilde_prefix "~"
@@ -1186,7 +1186,7 @@ ${escapedArgs ? ` \$completionArgs += @(${escapedArgs})
1186
1186
  \$prefix = \$prefix + '/'
1187
1187
  }
1188
1188
 
1189
- # Build the glob path when the prefix contains wildcard
1189
+ # Build the glob path—when the prefix contains wildcard
1190
1190
  # characters, use it as-is; otherwise append *
1191
1191
  \$globPath = if (\$prefix -match '[\*\?]') { \$prefix } else { "\${prefix}*" }
1192
1192
 
@@ -1597,7 +1597,7 @@ function filterExcludedFieldParsers(pairs, excludedFields) {
1597
1597
  /**
1598
1598
  * Pre-completes dependency source fields and registers their values in
1599
1599
  * the given registry. Unlike `completeDependencySourceDefaults()` (used
1600
- * by suggest), this function handles all four Phase 1 cases including
1600
+ * by suggest), this function handles all four Phase 1 cases—including
1601
1601
  * PendingDependencySourceState in arrays and wrappedDependencySourceMarker.
1602
1602
  *
1603
1603
  * The original state is NOT modified; only the registry is populated.
@@ -1597,7 +1597,7 @@ function filterExcludedFieldParsers(pairs, excludedFields) {
1597
1597
  /**
1598
1598
  * Pre-completes dependency source fields and registers their values in
1599
1599
  * the given registry. Unlike `completeDependencySourceDefaults()` (used
1600
- * by suggest), this function handles all four Phase 1 cases including
1600
+ * by suggest), this function handles all four Phase 1 cases—including
1601
1601
  * PendingDependencySourceState in arrays and wrappedDependencySourceMarker.
1602
1602
  *
1603
1603
  * The original state is NOT modified; only the registry is populated.
@@ -20,13 +20,13 @@ interface DependencySourceCapability {
20
20
  * The `state` argument is the current parser state for the source-owning
21
21
  * parser. Each wrapper composes this method to handle its own state shape:
22
22
  * - plain source: reads from `DependencySourceState`
23
- * - `optional()` / `withDefault()`: unwraps `[innerState]` first
23
+ * - `optional()`/`withDefault()`: unwraps `[innerState]` first
24
24
  * - `map()`: reads the pre-transform value from inner state
25
25
  *
26
26
  * Returns the `ValueParserResult` (which may be successful with any
27
27
  * value including `undefined`, or failed), a promise that resolves to the
28
28
  * same shape when extraction needs async work, or `undefined` if the state
29
- * does not contain a source result at all (unpopulated / wrong shape).
29
+ * does not contain a source result at all (unpopulated/wrong shape).
30
30
  * Callers and wrapper authors must handle both direct and promise-wrapped
31
31
  * results when composing `extractSourceValue`.
32
32
  */
@@ -20,13 +20,13 @@ interface DependencySourceCapability {
20
20
  * The `state` argument is the current parser state for the source-owning
21
21
  * parser. Each wrapper composes this method to handle its own state shape:
22
22
  * - plain source: reads from `DependencySourceState`
23
- * - `optional()` / `withDefault()`: unwraps `[innerState]` first
23
+ * - `optional()`/`withDefault()`: unwraps `[innerState]` first
24
24
  * - `map()`: reads the pre-transform value from inner state
25
25
  *
26
26
  * Returns the `ValueParserResult` (which may be successful with any
27
27
  * value including `undefined`, or failed), a promise that resolves to the
28
28
  * same shape when extraction needs async work, or `undefined` if the state
29
- * does not contain a source result at all (unpopulated / wrong shape).
29
+ * does not contain a source result at all (unpopulated/wrong shape).
30
30
  * Callers and wrapper authors must handle both direct and promise-wrapped
31
31
  * results when composing `extractSourceValue`.
32
32
  */
package/dist/index.cjs CHANGED
@@ -72,6 +72,7 @@ exports.isNonEmptyString = require_nonempty.isNonEmptyString;
72
72
  exports.isSuggestionHidden = require_usage.isSuggestionHidden;
73
73
  exports.isUsageHidden = require_usage.isUsageHidden;
74
74
  exports.isValueParser = require_valueparser.isValueParser;
75
+ exports.json = require_valueparser.json;
75
76
  exports.lineBreak = require_message.lineBreak;
76
77
  exports.link = require_message.link;
77
78
  exports.locale = require_valueparser.locale;
package/dist/index.d.cts CHANGED
@@ -3,7 +3,7 @@ import { NonEmptyString, ensureNonEmptyString, isNonEmptyString } from "./nonemp
3
3
  import { Message, MessageFormatOptions, MessageTerm, ValueSetOptions, commandLine, envVar, formatMessage, lineBreak, link, message, metavar, optionName, optionNames, text, value, valueSet, values } from "./message.cjs";
4
4
  import { HiddenVisibility, OptionName, Usage, UsageFormatOptions, UsageTerm, UsageTermFormatOptions, cloneUsage, cloneUsageTerm, extractArgumentMetavars, extractCommandNames, extractLiteralValues, extractOptionNames, formatUsage, formatUsageTerm, isDocHidden, isSuggestionHidden, isUsageHidden, mergeHidden, normalizeUsage } from "./usage.cjs";
5
5
  import { DocEntry, DocFragment, DocFragments, DocPage, DocPageFormatOptions, DocSection, ShowChoicesOptions, ShowDefaultOptions, cloneDocEntry, deduplicateDocEntries, deduplicateDocFragments, formatDocPage, isDocEntryHidden } from "./doc.cjs";
6
- import { ChoiceOptions, ChoiceOptionsBase, ChoiceOptionsNumber, ChoiceOptionsString, CidrOptions, CidrValue, Color, ColorFormat, ColorOptions, DeferredMap, DomainOptions, EmailOptions, FileSizeOptions, FileSizeOptionsBigInt, FileSizeOptionsNumber, FileSizeUnit, FloatOptions, HostnameOptions, IntegerOptionsBigInt, IntegerOptionsNumber, IpOptions, Ipv4Options, Ipv6Options, LocaleOptions, MacAddressOptions, PortOptionsBigInt, PortOptionsNumber, PortRangeOptionsBigInt, PortRangeOptionsNumber, PortRangeValueBigInt, PortRangeValueNumber, SemVer, SemVerOptionsObject, SemVerOptionsString, SemVerString, SocketAddressOptions, SocketAddressValue, StringOptions, UrlOptions, Uuid, UuidOptions, ValueParser, ValueParserResult, checkBooleanOption, checkEnumOption, choice, cidr, color, domain, email, fileSize, float, hostname, integer, ip, ipv4, ipv6, isValueParser, locale, macAddress, port, portRange, semVer, socketAddress, string, url, uuid } from "./valueparser.cjs";
6
+ import { ChoiceOptions, ChoiceOptionsBase, ChoiceOptionsNumber, ChoiceOptionsString, CidrOptions, CidrValue, Color, ColorFormat, ColorOptions, DeferredMap, DomainOptions, EmailOptions, FileSizeOptions, FileSizeOptionsBigInt, FileSizeOptionsNumber, FileSizeUnit, FloatOptions, HostnameOptions, IntegerOptionsBigInt, IntegerOptionsNumber, IpOptions, Ipv4Options, Ipv6Options, Json, JsonOptions, LocaleOptions, MacAddressOptions, PortOptionsBigInt, PortOptionsNumber, PortRangeOptionsBigInt, PortRangeOptionsNumber, PortRangeValueBigInt, PortRangeValueNumber, SemVer, SemVerOptionsObject, SemVerOptionsString, SemVerString, SocketAddressOptions, SocketAddressValue, StringOptions, UrlOptions, Uuid, UuidOptions, ValueParser, ValueParserResult, checkBooleanOption, checkEnumOption, choice, cidr, color, domain, email, fileSize, float, hostname, integer, ip, ipv4, ipv6, isValueParser, json, locale, macAddress, port, portRange, semVer, socketAddress, string, url, uuid } from "./valueparser.cjs";
7
7
  import { CombineModes, DocState, ExecutionContext, ExecutionPhase, InferMode, InferValue, Mode, ModeIterable, ModeValue, ParseFrame, Parser, ParserContext, ParserResult, Result, Suggestion, createParserContext, getDocPage, getDocPageAsync, getDocPageSync, parse, parseAsync, parseSync, suggest, suggestAsync, suggestSync } from "./internal/parser.cjs";
8
8
  import { ShellCompletion, bash, fish, nu, pwsh, zsh } from "./completion.cjs";
9
9
  import { ConditionalErrorOptions, ConditionalOptions, DuplicateOptionError, GroupOptions, LongestMatchErrorOptions, LongestMatchOptions, MergeOptions, NoMatchContext, ObjectErrorOptions, ObjectOptions, OrErrorOptions, OrOptions, TupleOptions, concat, conditional, group, longestMatch, merge, object, or, tuple } from "./constructs.cjs";
@@ -12,4 +12,4 @@ import { AnyDependencySource, CombineMode, CombinedDependencyMode, DependencyMod
12
12
  import { CommandSubConfig, ContextOptionsParam, ExtractRequiredOptions, OptionSubConfig, RunOptions, RunParserError, RunWithOptions, SubstituteParserValue, runParser, runParserAsync, runParserSync, runWith, runWithAsync, runWithSync } from "./facade.cjs";
13
13
  import { MultipleErrorOptions, MultipleOptions, WithDefaultError, WithDefaultOptions, map, multiple, nonEmpty, optional, withDefault } from "./modifiers.cjs";
14
14
  import { ArgumentErrorOptions, ArgumentOptions, CommandErrorOptions, CommandOptions, FlagErrorOptions, FlagOptions, NegatableFlagErrorOptions, NegatableFlagNameList, NegatableFlagNames, NegatableFlagOptions, NegatableFlagState, OptionErrorOptions, OptionOptions, OptionState, PassThroughFormat, PassThroughOptions, argument, command, constant, fail, flag, negatableFlag, option, passThrough } from "./primitives.cjs";
15
- export { type Annotations, AnyDependencySource, ArgumentErrorOptions, ArgumentOptions, ChoiceOptions, ChoiceOptionsBase, ChoiceOptionsNumber, ChoiceOptionsString, CidrOptions, CidrValue, Color, ColorFormat, ColorOptions, CombineMode, CombineModes, CombinedDependencyMode, CommandErrorOptions, CommandOptions, CommandSubConfig, ConditionalErrorOptions, ConditionalOptions, ContextOptionsParam, DeferredMap, DependencyMode, DependencySource, DependencyValue, DependencyValues, DeriveAsyncOptions, DeriveFromAsyncOptions, DeriveFromOptions, DeriveFromSyncOptions, DeriveOptions, DeriveSyncOptions, DerivedValueParser, DocEntry, DocFragment, DocFragments, DocPage, DocPageFormatOptions, DocSection, DocState, DomainOptions, DuplicateOptionError, EmailOptions, ExecutionContext, ExecutionPhase, ExtractRequiredOptions, FileSizeOptions, FileSizeOptionsBigInt, FileSizeOptionsNumber, FileSizeUnit, FlagErrorOptions, FlagOptions, FloatOptions, GroupOptions, HiddenVisibility, HostnameOptions, InferMode, InferValue, IntegerOptionsBigInt, IntegerOptionsNumber, IpOptions, Ipv4Options, Ipv6Options, LocaleOptions, LongestMatchErrorOptions, LongestMatchOptions, MacAddressOptions, MergeOptions, type Message, type MessageFormatOptions, type MessageTerm, Mode, ModeIterable, ModeValue, MultipleErrorOptions, MultipleOptions, NegatableFlagErrorOptions, NegatableFlagNameList, NegatableFlagNames, NegatableFlagOptions, NegatableFlagState, NoMatchContext, NonEmptyString, ObjectErrorOptions, ObjectOptions, OptionErrorOptions, OptionName, OptionOptions, OptionState, OptionSubConfig, OrErrorOptions, OrOptions, ParseFrame, type ParseOptions, Parser, ParserContext, ParserResult, ParserValuePlaceholder, PassThroughFormat, PassThroughOptions, PortOptionsBigInt, PortOptionsNumber, PortRangeOptionsBigInt, PortRangeOptionsNumber, PortRangeValueBigInt, PortRangeValueNumber, Result, RunOptions, RunParserError, RunWithOptions, SemVer, SemVerOptionsObject, SemVerOptionsString, SemVerString, ShellCompletion, ShowChoicesOptions, ShowDefaultOptions, SocketAddressOptions, SocketAddressValue, SourceContext, SourceContextRequest, StringOptions, SubstituteParserValue, Suggestion, TupleOptions, UrlOptions, Usage, UsageFormatOptions, UsageTerm, UsageTermFormatOptions, Uuid, UuidOptions, ValueParser, ValueParserResult, type ValueSetOptions, WithDefaultError, WithDefaultOptions, argument, bash, checkBooleanOption, checkEnumOption, choice, cidr, cloneDocEntry, cloneUsage, cloneUsageTerm, color, command, commandLine, concat, conditional, constant, createParserContext, deduplicateDocEntries, deduplicateDocFragments, dependency, deriveFrom, deriveFromAsync, deriveFromSync, domain, email, ensureNonEmptyString, envVar, extractArgumentMetavars, extractCommandNames, extractLiteralValues, extractOptionNames, fail, fileSize, fish, flag, float, formatDocPage, formatMessage, formatUsage, formatUsageTerm, getAnnotations, getDocPage, getDocPageAsync, getDocPageSync, group, hostname, integer, ip, ipv4, ipv6, isDependencySource, isDerivedValueParser, isDocEntryHidden, isDocHidden, isNonEmptyString, isSuggestionHidden, isUsageHidden, isValueParser, lineBreak, link, locale, longestMatch, macAddress, map, merge, mergeHidden, message, metavar, multiple, negatableFlag, nonEmpty, normalizeUsage, nu, object, option, optionName, optionNames, optional, or, parse, parseAsync, parseSync, passThrough, port, portRange, pwsh, runParser, runParserAsync, runParserSync, runWith, runWithAsync, runWithSync, semVer, socketAddress, string, suggest, suggestAsync, suggestSync, text, tuple, url, uuid, value, valueSet, values, withDefault, zsh };
15
+ export { type Annotations, AnyDependencySource, ArgumentErrorOptions, ArgumentOptions, ChoiceOptions, ChoiceOptionsBase, ChoiceOptionsNumber, ChoiceOptionsString, CidrOptions, CidrValue, Color, ColorFormat, ColorOptions, CombineMode, CombineModes, CombinedDependencyMode, CommandErrorOptions, CommandOptions, CommandSubConfig, ConditionalErrorOptions, ConditionalOptions, ContextOptionsParam, DeferredMap, DependencyMode, DependencySource, DependencyValue, DependencyValues, DeriveAsyncOptions, DeriveFromAsyncOptions, DeriveFromOptions, DeriveFromSyncOptions, DeriveOptions, DeriveSyncOptions, DerivedValueParser, DocEntry, DocFragment, DocFragments, DocPage, DocPageFormatOptions, DocSection, DocState, DomainOptions, DuplicateOptionError, EmailOptions, ExecutionContext, ExecutionPhase, ExtractRequiredOptions, FileSizeOptions, FileSizeOptionsBigInt, FileSizeOptionsNumber, FileSizeUnit, FlagErrorOptions, FlagOptions, FloatOptions, GroupOptions, HiddenVisibility, HostnameOptions, InferMode, InferValue, IntegerOptionsBigInt, IntegerOptionsNumber, IpOptions, Ipv4Options, Ipv6Options, Json, JsonOptions, LocaleOptions, LongestMatchErrorOptions, LongestMatchOptions, MacAddressOptions, MergeOptions, type Message, type MessageFormatOptions, type MessageTerm, Mode, ModeIterable, ModeValue, MultipleErrorOptions, MultipleOptions, NegatableFlagErrorOptions, NegatableFlagNameList, NegatableFlagNames, NegatableFlagOptions, NegatableFlagState, NoMatchContext, NonEmptyString, ObjectErrorOptions, ObjectOptions, OptionErrorOptions, OptionName, OptionOptions, OptionState, OptionSubConfig, OrErrorOptions, OrOptions, ParseFrame, type ParseOptions, Parser, ParserContext, ParserResult, ParserValuePlaceholder, PassThroughFormat, PassThroughOptions, PortOptionsBigInt, PortOptionsNumber, PortRangeOptionsBigInt, PortRangeOptionsNumber, PortRangeValueBigInt, PortRangeValueNumber, Result, RunOptions, RunParserError, RunWithOptions, SemVer, SemVerOptionsObject, SemVerOptionsString, SemVerString, ShellCompletion, ShowChoicesOptions, ShowDefaultOptions, SocketAddressOptions, SocketAddressValue, SourceContext, SourceContextRequest, StringOptions, SubstituteParserValue, Suggestion, TupleOptions, UrlOptions, Usage, UsageFormatOptions, UsageTerm, UsageTermFormatOptions, Uuid, UuidOptions, ValueParser, ValueParserResult, type ValueSetOptions, WithDefaultError, WithDefaultOptions, argument, bash, checkBooleanOption, checkEnumOption, choice, cidr, cloneDocEntry, cloneUsage, cloneUsageTerm, color, command, commandLine, concat, conditional, constant, createParserContext, deduplicateDocEntries, deduplicateDocFragments, dependency, deriveFrom, deriveFromAsync, deriveFromSync, domain, email, ensureNonEmptyString, envVar, extractArgumentMetavars, extractCommandNames, extractLiteralValues, extractOptionNames, fail, fileSize, fish, flag, float, formatDocPage, formatMessage, formatUsage, formatUsageTerm, getAnnotations, getDocPage, getDocPageAsync, getDocPageSync, group, hostname, integer, ip, ipv4, ipv6, isDependencySource, isDerivedValueParser, isDocEntryHidden, isDocHidden, isNonEmptyString, isSuggestionHidden, isUsageHidden, isValueParser, json, lineBreak, link, locale, longestMatch, macAddress, map, merge, mergeHidden, message, metavar, multiple, negatableFlag, nonEmpty, normalizeUsage, nu, object, option, optionName, optionNames, optional, or, parse, parseAsync, parseSync, passThrough, port, portRange, pwsh, runParser, runParserAsync, runParserSync, runWith, runWithAsync, runWithSync, semVer, socketAddress, string, suggest, suggestAsync, suggestSync, text, tuple, url, uuid, value, valueSet, values, withDefault, zsh };
package/dist/index.d.ts CHANGED
@@ -3,7 +3,7 @@ import { NonEmptyString, ensureNonEmptyString, isNonEmptyString } from "./nonemp
3
3
  import { Message, MessageFormatOptions, MessageTerm, ValueSetOptions, commandLine, envVar, formatMessage, lineBreak, link, message, metavar, optionName, optionNames, text, value, valueSet, values } from "./message.js";
4
4
  import { HiddenVisibility, OptionName, Usage, UsageFormatOptions, UsageTerm, UsageTermFormatOptions, cloneUsage, cloneUsageTerm, extractArgumentMetavars, extractCommandNames, extractLiteralValues, extractOptionNames, formatUsage, formatUsageTerm, isDocHidden, isSuggestionHidden, isUsageHidden, mergeHidden, normalizeUsage } from "./usage.js";
5
5
  import { DocEntry, DocFragment, DocFragments, DocPage, DocPageFormatOptions, DocSection, ShowChoicesOptions, ShowDefaultOptions, cloneDocEntry, deduplicateDocEntries, deduplicateDocFragments, formatDocPage, isDocEntryHidden } from "./doc.js";
6
- import { ChoiceOptions, ChoiceOptionsBase, ChoiceOptionsNumber, ChoiceOptionsString, CidrOptions, CidrValue, Color, ColorFormat, ColorOptions, DeferredMap, DomainOptions, EmailOptions, FileSizeOptions, FileSizeOptionsBigInt, FileSizeOptionsNumber, FileSizeUnit, FloatOptions, HostnameOptions, IntegerOptionsBigInt, IntegerOptionsNumber, IpOptions, Ipv4Options, Ipv6Options, LocaleOptions, MacAddressOptions, PortOptionsBigInt, PortOptionsNumber, PortRangeOptionsBigInt, PortRangeOptionsNumber, PortRangeValueBigInt, PortRangeValueNumber, SemVer, SemVerOptionsObject, SemVerOptionsString, SemVerString, SocketAddressOptions, SocketAddressValue, StringOptions, UrlOptions, Uuid, UuidOptions, ValueParser, ValueParserResult, checkBooleanOption, checkEnumOption, choice, cidr, color, domain, email, fileSize, float, hostname, integer, ip, ipv4, ipv6, isValueParser, locale, macAddress, port, portRange, semVer, socketAddress, string, url, uuid } from "./valueparser.js";
6
+ import { ChoiceOptions, ChoiceOptionsBase, ChoiceOptionsNumber, ChoiceOptionsString, CidrOptions, CidrValue, Color, ColorFormat, ColorOptions, DeferredMap, DomainOptions, EmailOptions, FileSizeOptions, FileSizeOptionsBigInt, FileSizeOptionsNumber, FileSizeUnit, FloatOptions, HostnameOptions, IntegerOptionsBigInt, IntegerOptionsNumber, IpOptions, Ipv4Options, Ipv6Options, Json, JsonOptions, LocaleOptions, MacAddressOptions, PortOptionsBigInt, PortOptionsNumber, PortRangeOptionsBigInt, PortRangeOptionsNumber, PortRangeValueBigInt, PortRangeValueNumber, SemVer, SemVerOptionsObject, SemVerOptionsString, SemVerString, SocketAddressOptions, SocketAddressValue, StringOptions, UrlOptions, Uuid, UuidOptions, ValueParser, ValueParserResult, checkBooleanOption, checkEnumOption, choice, cidr, color, domain, email, fileSize, float, hostname, integer, ip, ipv4, ipv6, isValueParser, json, locale, macAddress, port, portRange, semVer, socketAddress, string, url, uuid } from "./valueparser.js";
7
7
  import { CombineModes, DocState, ExecutionContext, ExecutionPhase, InferMode, InferValue, Mode, ModeIterable, ModeValue, ParseFrame, Parser, ParserContext, ParserResult, Result, Suggestion, createParserContext, getDocPage, getDocPageAsync, getDocPageSync, parse, parseAsync, parseSync, suggest, suggestAsync, suggestSync } from "./internal/parser.js";
8
8
  import { ShellCompletion, bash, fish, nu, pwsh, zsh } from "./completion.js";
9
9
  import { ConditionalErrorOptions, ConditionalOptions, DuplicateOptionError, GroupOptions, LongestMatchErrorOptions, LongestMatchOptions, MergeOptions, NoMatchContext, ObjectErrorOptions, ObjectOptions, OrErrorOptions, OrOptions, TupleOptions, concat, conditional, group, longestMatch, merge, object, or, tuple } from "./constructs.js";
@@ -12,4 +12,4 @@ import { AnyDependencySource, CombineMode, CombinedDependencyMode, DependencyMod
12
12
  import { CommandSubConfig, ContextOptionsParam, ExtractRequiredOptions, OptionSubConfig, RunOptions, RunParserError, RunWithOptions, SubstituteParserValue, runParser, runParserAsync, runParserSync, runWith, runWithAsync, runWithSync } from "./facade.js";
13
13
  import { MultipleErrorOptions, MultipleOptions, WithDefaultError, WithDefaultOptions, map, multiple, nonEmpty, optional, withDefault } from "./modifiers.js";
14
14
  import { ArgumentErrorOptions, ArgumentOptions, CommandErrorOptions, CommandOptions, FlagErrorOptions, FlagOptions, NegatableFlagErrorOptions, NegatableFlagNameList, NegatableFlagNames, NegatableFlagOptions, NegatableFlagState, OptionErrorOptions, OptionOptions, OptionState, PassThroughFormat, PassThroughOptions, argument, command, constant, fail, flag, negatableFlag, option, passThrough } from "./primitives.js";
15
- export { type Annotations, AnyDependencySource, ArgumentErrorOptions, ArgumentOptions, ChoiceOptions, ChoiceOptionsBase, ChoiceOptionsNumber, ChoiceOptionsString, CidrOptions, CidrValue, Color, ColorFormat, ColorOptions, CombineMode, CombineModes, CombinedDependencyMode, CommandErrorOptions, CommandOptions, CommandSubConfig, ConditionalErrorOptions, ConditionalOptions, ContextOptionsParam, DeferredMap, DependencyMode, DependencySource, DependencyValue, DependencyValues, DeriveAsyncOptions, DeriveFromAsyncOptions, DeriveFromOptions, DeriveFromSyncOptions, DeriveOptions, DeriveSyncOptions, DerivedValueParser, DocEntry, DocFragment, DocFragments, DocPage, DocPageFormatOptions, DocSection, DocState, DomainOptions, DuplicateOptionError, EmailOptions, ExecutionContext, ExecutionPhase, ExtractRequiredOptions, FileSizeOptions, FileSizeOptionsBigInt, FileSizeOptionsNumber, FileSizeUnit, FlagErrorOptions, FlagOptions, FloatOptions, GroupOptions, HiddenVisibility, HostnameOptions, InferMode, InferValue, IntegerOptionsBigInt, IntegerOptionsNumber, IpOptions, Ipv4Options, Ipv6Options, LocaleOptions, LongestMatchErrorOptions, LongestMatchOptions, MacAddressOptions, MergeOptions, type Message, type MessageFormatOptions, type MessageTerm, Mode, ModeIterable, ModeValue, MultipleErrorOptions, MultipleOptions, NegatableFlagErrorOptions, NegatableFlagNameList, NegatableFlagNames, NegatableFlagOptions, NegatableFlagState, NoMatchContext, NonEmptyString, ObjectErrorOptions, ObjectOptions, OptionErrorOptions, OptionName, OptionOptions, OptionState, OptionSubConfig, OrErrorOptions, OrOptions, ParseFrame, type ParseOptions, Parser, ParserContext, ParserResult, ParserValuePlaceholder, PassThroughFormat, PassThroughOptions, PortOptionsBigInt, PortOptionsNumber, PortRangeOptionsBigInt, PortRangeOptionsNumber, PortRangeValueBigInt, PortRangeValueNumber, Result, RunOptions, RunParserError, RunWithOptions, SemVer, SemVerOptionsObject, SemVerOptionsString, SemVerString, ShellCompletion, ShowChoicesOptions, ShowDefaultOptions, SocketAddressOptions, SocketAddressValue, SourceContext, SourceContextRequest, StringOptions, SubstituteParserValue, Suggestion, TupleOptions, UrlOptions, Usage, UsageFormatOptions, UsageTerm, UsageTermFormatOptions, Uuid, UuidOptions, ValueParser, ValueParserResult, type ValueSetOptions, WithDefaultError, WithDefaultOptions, argument, bash, checkBooleanOption, checkEnumOption, choice, cidr, cloneDocEntry, cloneUsage, cloneUsageTerm, color, command, commandLine, concat, conditional, constant, createParserContext, deduplicateDocEntries, deduplicateDocFragments, dependency, deriveFrom, deriveFromAsync, deriveFromSync, domain, email, ensureNonEmptyString, envVar, extractArgumentMetavars, extractCommandNames, extractLiteralValues, extractOptionNames, fail, fileSize, fish, flag, float, formatDocPage, formatMessage, formatUsage, formatUsageTerm, getAnnotations, getDocPage, getDocPageAsync, getDocPageSync, group, hostname, integer, ip, ipv4, ipv6, isDependencySource, isDerivedValueParser, isDocEntryHidden, isDocHidden, isNonEmptyString, isSuggestionHidden, isUsageHidden, isValueParser, lineBreak, link, locale, longestMatch, macAddress, map, merge, mergeHidden, message, metavar, multiple, negatableFlag, nonEmpty, normalizeUsage, nu, object, option, optionName, optionNames, optional, or, parse, parseAsync, parseSync, passThrough, port, portRange, pwsh, runParser, runParserAsync, runParserSync, runWith, runWithAsync, runWithSync, semVer, socketAddress, string, suggest, suggestAsync, suggestSync, text, tuple, url, uuid, value, valueSet, values, withDefault, zsh };
15
+ export { type Annotations, AnyDependencySource, ArgumentErrorOptions, ArgumentOptions, ChoiceOptions, ChoiceOptionsBase, ChoiceOptionsNumber, ChoiceOptionsString, CidrOptions, CidrValue, Color, ColorFormat, ColorOptions, CombineMode, CombineModes, CombinedDependencyMode, CommandErrorOptions, CommandOptions, CommandSubConfig, ConditionalErrorOptions, ConditionalOptions, ContextOptionsParam, DeferredMap, DependencyMode, DependencySource, DependencyValue, DependencyValues, DeriveAsyncOptions, DeriveFromAsyncOptions, DeriveFromOptions, DeriveFromSyncOptions, DeriveOptions, DeriveSyncOptions, DerivedValueParser, DocEntry, DocFragment, DocFragments, DocPage, DocPageFormatOptions, DocSection, DocState, DomainOptions, DuplicateOptionError, EmailOptions, ExecutionContext, ExecutionPhase, ExtractRequiredOptions, FileSizeOptions, FileSizeOptionsBigInt, FileSizeOptionsNumber, FileSizeUnit, FlagErrorOptions, FlagOptions, FloatOptions, GroupOptions, HiddenVisibility, HostnameOptions, InferMode, InferValue, IntegerOptionsBigInt, IntegerOptionsNumber, IpOptions, Ipv4Options, Ipv6Options, Json, JsonOptions, LocaleOptions, LongestMatchErrorOptions, LongestMatchOptions, MacAddressOptions, MergeOptions, type Message, type MessageFormatOptions, type MessageTerm, Mode, ModeIterable, ModeValue, MultipleErrorOptions, MultipleOptions, NegatableFlagErrorOptions, NegatableFlagNameList, NegatableFlagNames, NegatableFlagOptions, NegatableFlagState, NoMatchContext, NonEmptyString, ObjectErrorOptions, ObjectOptions, OptionErrorOptions, OptionName, OptionOptions, OptionState, OptionSubConfig, OrErrorOptions, OrOptions, ParseFrame, type ParseOptions, Parser, ParserContext, ParserResult, ParserValuePlaceholder, PassThroughFormat, PassThroughOptions, PortOptionsBigInt, PortOptionsNumber, PortRangeOptionsBigInt, PortRangeOptionsNumber, PortRangeValueBigInt, PortRangeValueNumber, Result, RunOptions, RunParserError, RunWithOptions, SemVer, SemVerOptionsObject, SemVerOptionsString, SemVerString, ShellCompletion, ShowChoicesOptions, ShowDefaultOptions, SocketAddressOptions, SocketAddressValue, SourceContext, SourceContextRequest, StringOptions, SubstituteParserValue, Suggestion, TupleOptions, UrlOptions, Usage, UsageFormatOptions, UsageTerm, UsageTermFormatOptions, Uuid, UuidOptions, ValueParser, ValueParserResult, type ValueSetOptions, WithDefaultError, WithDefaultOptions, argument, bash, checkBooleanOption, checkEnumOption, choice, cidr, cloneDocEntry, cloneUsage, cloneUsageTerm, color, command, commandLine, concat, conditional, constant, createParserContext, deduplicateDocEntries, deduplicateDocFragments, dependency, deriveFrom, deriveFromAsync, deriveFromSync, domain, email, ensureNonEmptyString, envVar, extractArgumentMetavars, extractCommandNames, extractLiteralValues, extractOptionNames, fail, fileSize, fish, flag, float, formatDocPage, formatMessage, formatUsage, formatUsageTerm, getAnnotations, getDocPage, getDocPageAsync, getDocPageSync, group, hostname, integer, ip, ipv4, ipv6, isDependencySource, isDerivedValueParser, isDocEntryHidden, isDocHidden, isNonEmptyString, isSuggestionHidden, isUsageHidden, isValueParser, json, lineBreak, link, locale, longestMatch, macAddress, map, merge, mergeHidden, message, metavar, multiple, negatableFlag, nonEmpty, normalizeUsage, nu, object, option, optionName, optionNames, optional, or, parse, parseAsync, parseSync, passThrough, port, portRange, pwsh, runParser, runParserAsync, runParserSync, runWith, runWithAsync, runWithSync, semVer, socketAddress, string, suggest, suggestAsync, suggestSync, text, tuple, url, uuid, value, valueSet, values, withDefault, zsh };
package/dist/index.js CHANGED
@@ -8,8 +8,8 @@ import { createParserContext, getDocPage, getDocPageAsync, getDocPageSync, parse
8
8
  import { DuplicateOptionError, concat, conditional, group, longestMatch, merge, object, or, tuple } from "./constructs.js";
9
9
  import { WithDefaultError, map, multiple, nonEmpty, optional, withDefault } from "./modifiers.js";
10
10
  import { ensureNonEmptyString, isNonEmptyString } from "./nonempty.js";
11
- import { checkBooleanOption, checkEnumOption, choice, cidr, color, domain, email, fileSize, float, hostname, integer, ip, ipv4, ipv6, isValueParser, locale, macAddress, port, portRange, semVer, socketAddress, string, url, uuid } from "./valueparser.js";
11
+ import { checkBooleanOption, checkEnumOption, choice, cidr, color, domain, email, fileSize, float, hostname, integer, ip, ipv4, ipv6, isValueParser, json, locale, macAddress, port, portRange, semVer, socketAddress, string, url, uuid } from "./valueparser.js";
12
12
  import { argument, command, constant, fail, flag, negatableFlag, option, passThrough } from "./primitives.js";
13
13
  import { RunParserError, runParser, runParserAsync, runParserSync, runWith, runWithAsync, runWithSync } from "./facade.js";
14
14
 
15
- export { DuplicateOptionError, RunParserError, WithDefaultError, argument, bash, checkBooleanOption, checkEnumOption, choice, cidr, cloneDocEntry, cloneUsage, cloneUsageTerm, color, command, commandLine, concat, conditional, constant, createParserContext, deduplicateDocEntries, deduplicateDocFragments, dependency, deriveFrom, deriveFromAsync, deriveFromSync, domain, email, ensureNonEmptyString, envVar, extractArgumentMetavars, extractCommandNames, extractLiteralValues, extractOptionNames, fail, fileSize, fish, flag, float, formatDocPage, formatMessage, formatUsage, formatUsageTerm, getAnnotations, getDocPage, getDocPageAsync, getDocPageSync, group, hostname, integer, ip, ipv4, ipv6, isDependencySource, isDerivedValueParser, isDocEntryHidden, isDocHidden, isNonEmptyString, isSuggestionHidden, isUsageHidden, isValueParser, lineBreak, link, locale, longestMatch, macAddress, map, merge, mergeHidden, message, metavar, multiple, negatableFlag, nonEmpty, normalizeUsage, nu, object, option, optionName, optionNames, optional, or, parse, parseAsync, parseSync, passThrough, port, portRange, pwsh, runParser, runParserAsync, runParserSync, runWith, runWithAsync, runWithSync, semVer, socketAddress, string, suggest, suggestAsync, suggestSync, text, tuple, url, uuid, value, valueSet, values, withDefault, zsh };
15
+ export { DuplicateOptionError, RunParserError, WithDefaultError, argument, bash, checkBooleanOption, checkEnumOption, choice, cidr, cloneDocEntry, cloneUsage, cloneUsageTerm, color, command, commandLine, concat, conditional, constant, createParserContext, deduplicateDocEntries, deduplicateDocFragments, dependency, deriveFrom, deriveFromAsync, deriveFromSync, domain, email, ensureNonEmptyString, envVar, extractArgumentMetavars, extractCommandNames, extractLiteralValues, extractOptionNames, fail, fileSize, fish, flag, float, formatDocPage, formatMessage, formatUsage, formatUsageTerm, getAnnotations, getDocPage, getDocPageAsync, getDocPageSync, group, hostname, integer, ip, ipv4, ipv6, isDependencySource, isDerivedValueParser, isDocEntryHidden, isDocHidden, isNonEmptyString, isSuggestionHidden, isUsageHidden, isValueParser, json, lineBreak, link, locale, longestMatch, macAddress, map, merge, mergeHidden, message, metavar, multiple, negatableFlag, nonEmpty, normalizeUsage, nu, object, option, optionName, optionNames, optional, or, parse, parseAsync, parseSync, passThrough, port, portRange, pwsh, runParser, runParserAsync, runParserSync, runWith, runWithAsync, runWithSync, semVer, socketAddress, string, suggest, suggestAsync, suggestSync, text, tuple, url, uuid, value, valueSet, values, withDefault, zsh };
@@ -112,7 +112,7 @@ interface Parser<M extends Mode = "sync", TValue = unknown, TState = unknown> {
112
112
  *
113
113
  * Each built-in combinator computes this from its structural semantics.
114
114
  * Custom parser implementations must include every fixed token that
115
- * the parser accepts at `argv[0]` — command names, option names, and
115
+ * the parser accepts at `argv[0]`—command names, option names, and
116
116
  * literal values alike. For example, a parser whose usage declares
117
117
  * `{ type: "literal", value: "serve" }` should include `"serve"` in
118
118
  * this set. Parsers that accept *any* token (like `argument()`) should
@@ -265,8 +265,8 @@ interface Parser<M extends Mode = "sync", TValue = unknown, TState = unknown> {
265
265
  * parser (e.g., regex patterns, numeric bounds, `choice()` values).
266
266
  *
267
267
  * Wrappers like `bindEnv()` and `bindConfig()` call this on fallback
268
- * values environment variables parsed by a looser env parser,
269
- * configured defaults, and values loaded from config files so that
268
+ * values—environment variables parsed by a looser env parser,
269
+ * configured defaults, and values loaded from config files—so that
270
270
  * those values obey the same validation semantics as CLI input.
271
271
  * Without it, parser constraints can be silently bypassed through
272
272
  * fallback paths.
@@ -292,7 +292,7 @@ interface Parser<M extends Mode = "sync", TValue = unknown, TState = unknown> {
292
292
  * current dependency value, and custom value parsers whose `format()`
293
293
  * intentionally throws for unsupported inputs. Values that
294
294
  * `format()` successfully serializes to a string are always re-parsed,
295
- * and any resulting parse failure is propagated they represent the
295
+ * and any resulting parse failure is propagated—they represent the
296
296
  * bug class this method exists to surface.
297
297
  *
298
298
  * @param value The candidate value to validate.
@@ -413,7 +413,7 @@ interface ExecutionContext {
413
413
  * `preCompleteAndRegisterDependencies` results directly to children
414
414
  * in Phase 3. Children read it in their own Phase 1 to avoid
415
415
  * re-evaluating non-idempotent default thunks, but never write to
416
- * it this prevents sibling completions from leaking into each
416
+ * it—this prevents sibling completions from leaking into each
417
417
  * other.
418
418
  *
419
419
  * Field-name keying naturally handles parser reuse across different
@@ -112,7 +112,7 @@ interface Parser<M extends Mode = "sync", TValue = unknown, TState = unknown> {
112
112
  *
113
113
  * Each built-in combinator computes this from its structural semantics.
114
114
  * Custom parser implementations must include every fixed token that
115
- * the parser accepts at `argv[0]` — command names, option names, and
115
+ * the parser accepts at `argv[0]`—command names, option names, and
116
116
  * literal values alike. For example, a parser whose usage declares
117
117
  * `{ type: "literal", value: "serve" }` should include `"serve"` in
118
118
  * this set. Parsers that accept *any* token (like `argument()`) should
@@ -265,8 +265,8 @@ interface Parser<M extends Mode = "sync", TValue = unknown, TState = unknown> {
265
265
  * parser (e.g., regex patterns, numeric bounds, `choice()` values).
266
266
  *
267
267
  * Wrappers like `bindEnv()` and `bindConfig()` call this on fallback
268
- * values environment variables parsed by a looser env parser,
269
- * configured defaults, and values loaded from config files so that
268
+ * values—environment variables parsed by a looser env parser,
269
+ * configured defaults, and values loaded from config files—so that
270
270
  * those values obey the same validation semantics as CLI input.
271
271
  * Without it, parser constraints can be silently bypassed through
272
272
  * fallback paths.
@@ -292,7 +292,7 @@ interface Parser<M extends Mode = "sync", TValue = unknown, TState = unknown> {
292
292
  * current dependency value, and custom value parsers whose `format()`
293
293
  * intentionally throws for unsupported inputs. Values that
294
294
  * `format()` successfully serializes to a string are always re-parsed,
295
- * and any resulting parse failure is propagated they represent the
295
+ * and any resulting parse failure is propagated—they represent the
296
296
  * bug class this method exists to surface.
297
297
  *
298
298
  * @param value The candidate value to validate.
@@ -413,7 +413,7 @@ interface ExecutionContext {
413
413
  * `preCompleteAndRegisterDependencies` results directly to children
414
414
  * in Phase 3. Children read it in their own Phase 1 to avoid
415
415
  * re-evaluating non-idempotent default thunks, but never write to
416
- * it this prevents sibling completions from leaking into each
416
+ * it—this prevents sibling completions from leaking into each
417
417
  * other.
418
418
  *
419
419
  * Field-name keying naturally handles parser reuse across different
@@ -142,14 +142,14 @@ function extractOptionalLikePhase2Seed(parser, state, exec) {
142
142
  }
143
143
  /**
144
144
  * Computes the inner state to pass through to the wrapped parser inside
145
- * {@link optional} / {@link withDefault}. When the outer state is an
145
+ * {@link optional}/{@link withDefault}. When the outer state is an
146
146
  * array, the inner state is `state[0]`. Otherwise, including the
147
147
  * common case where `optional()` sits at top level and the outer state
148
- * is either `undefined` or an annotation wrapper from `parseOptionalLike`
149
- * / `parse({ annotations })`, we use the wrapped parser's
148
+ * is either `undefined` or an annotation wrapper from `parseOptionalLike`/
149
+ * `parse({ annotations })`, we use the wrapped parser's
150
150
  * `initialState`, propagating annotations from the outer state so that
151
- * source-binding wrappers under `optional()` / `withDefault()` (e.g.,
152
- * `bindEnv()` / `bindConfig()`) can resolve their fallbacks.
151
+ * source-binding wrappers under `optional()`/`withDefault()` (e.g.,
152
+ * `bindEnv()`/`bindConfig()`) can resolve their fallbacks.
153
153
  *
154
154
  * @internal
155
155
  */
@@ -677,7 +677,7 @@ function withDefault(parser, defaultValue, options) {
677
677
  *
678
678
  * Because the `deferred` flag is propagated conservatively, mapped scalar
679
679
  * results are treated as missing (`undefined`) during phase-two context
680
- * collection even when `transform` only used non-deferred fields.
680
+ * collection—even when `transform` only used non-deferred fields.
681
681
  * For example, `map(object({ apiKey: prompt(...), mode: option(...) }),
682
682
  * v => v.mode)` makes phase-two contexts see `undefined` instead of the
683
683
  * real `mode` value. This is the intentional trade-off: the alternative
@@ -138,7 +138,7 @@ declare function withDefault<M extends Mode, TValue, TState, const TDefault = TV
138
138
  *
139
139
  * Because the `deferred` flag is propagated conservatively, mapped scalar
140
140
  * results are treated as missing (`undefined`) during phase-two context
141
- * collection even when `transform` only used non-deferred fields.
141
+ * collection—even when `transform` only used non-deferred fields.
142
142
  * For example, `map(object({ apiKey: prompt(...), mode: option(...) }),
143
143
  * v => v.mode)` makes phase-two contexts see `undefined` instead of the
144
144
  * real `mode` value. This is the intentional trade-off: the alternative
@@ -138,7 +138,7 @@ declare function withDefault<M extends Mode, TValue, TState, const TDefault = TV
138
138
  *
139
139
  * Because the `deferred` flag is propagated conservatively, mapped scalar
140
140
  * results are treated as missing (`undefined`) during phase-two context
141
- * collection even when `transform` only used non-deferred fields.
141
+ * collection—even when `transform` only used non-deferred fields.
142
142
  * For example, `map(object({ apiKey: prompt(...), mode: option(...) }),
143
143
  * v => v.mode)` makes phase-two contexts see `undefined` instead of the
144
144
  * real `mode` value. This is the intentional trade-off: the alternative
package/dist/modifiers.js CHANGED
@@ -142,14 +142,14 @@ function extractOptionalLikePhase2Seed(parser, state, exec) {
142
142
  }
143
143
  /**
144
144
  * Computes the inner state to pass through to the wrapped parser inside
145
- * {@link optional} / {@link withDefault}. When the outer state is an
145
+ * {@link optional}/{@link withDefault}. When the outer state is an
146
146
  * array, the inner state is `state[0]`. Otherwise, including the
147
147
  * common case where `optional()` sits at top level and the outer state
148
- * is either `undefined` or an annotation wrapper from `parseOptionalLike`
149
- * / `parse({ annotations })`, we use the wrapped parser's
148
+ * is either `undefined` or an annotation wrapper from `parseOptionalLike`/
149
+ * `parse({ annotations })`, we use the wrapped parser's
150
150
  * `initialState`, propagating annotations from the outer state so that
151
- * source-binding wrappers under `optional()` / `withDefault()` (e.g.,
152
- * `bindEnv()` / `bindConfig()`) can resolve their fallbacks.
151
+ * source-binding wrappers under `optional()`/`withDefault()` (e.g.,
152
+ * `bindEnv()`/`bindConfig()`) can resolve their fallbacks.
153
153
  *
154
154
  * @internal
155
155
  */
@@ -677,7 +677,7 @@ function withDefault(parser, defaultValue, options) {
677
677
  *
678
678
  * Because the `deferred` flag is propagated conservatively, mapped scalar
679
679
  * results are treated as missing (`undefined`) during phase-two context
680
- * collection even when `transform` only used non-deferred fields.
680
+ * collection—even when `transform` only used non-deferred fields.
681
681
  * For example, `map(object({ apiKey: prompt(...), mode: option(...) }),
682
682
  * v => v.mode)` makes phase-two contexts see `undefined` instead of the
683
683
  * real `mode` value. This is the intentional trade-off: the alternative
@@ -55,7 +55,7 @@ function collectLeadingCandidates(terms, optionNames, commandNames) {
55
55
  *
56
56
  * This is the command-only projection of {@link collectLeadingCandidates}
57
57
  * and is used to generate accurate "Did you mean?" suggestions in
58
- * `command()` error messages suggestions are scoped to commands actually
58
+ * `command()` error messages—suggestions are scoped to commands actually
59
59
  * reachable at the current parse position rather than all commands anywhere
60
60
  * in the usage tree.
61
61
  *
@@ -55,7 +55,7 @@ function collectLeadingCandidates(terms, optionNames, commandNames) {
55
55
  *
56
56
  * This is the command-only projection of {@link collectLeadingCandidates}
57
57
  * and is used to generate accurate "Did you mean?" suggestions in
58
- * `command()` error messages suggestions are scoped to commands actually
58
+ * `command()` error messages—suggestions are scoped to commands actually
59
59
  * reachable at the current parse position rather than all commands anywhere
60
60
  * in the usage tree.
61
61
  *
@@ -5235,6 +5235,140 @@ function semVer(options = {}) {
5235
5235
  }
5236
5236
  };
5237
5237
  }
5238
+ /**
5239
+ * Creates a {@link ValueParser} for parsing JSON-encoded strings from the
5240
+ * command line.
5241
+ *
5242
+ * The parser accepts any well-formed JSON string by default. Use the
5243
+ * `rootType` option to restrict which JSON root type is accepted and to
5244
+ * narrow the TypeScript return type accordingly.
5245
+ *
5246
+ * @example
5247
+ * ```typescript
5248
+ * // Accept any JSON value
5249
+ * const anyJson = json();
5250
+ *
5251
+ * // Accept only JSON objects (return type narrowed)
5252
+ * const objJson = json({ rootType: "object" });
5253
+ * ```
5254
+ *
5255
+ * @param options Optional configuration for the parser.
5256
+ * @returns A {@link ValueParser} that converts JSON-encoded strings to the
5257
+ * appropriate JavaScript type.
5258
+ * @throws {TypeError} If `options.metavar` is provided but is an empty string.
5259
+ * @throws {TypeError} If `options.rootType` is provided but is not one of the
5260
+ * six allowed values.
5261
+ * @throws {TypeError} If `options.placeholder` or any value nested within
5262
+ * it is a non-finite number (`Infinity`, `-Infinity`, or `NaN`).
5263
+ * @throws {TypeError} If `options.placeholder` is provided with a `rootType`
5264
+ * but its JSON type does not match the `rootType`.
5265
+ * @throws {TypeError} If the returned parser's `format()` method is called
5266
+ * with a value that contains a non-finite number anywhere in its structure.
5267
+ * @since 1.1.0
5268
+ */
5269
+ function json(options) {
5270
+ const metavar = options?.metavar ?? "JSON";
5271
+ require_nonempty.ensureNonEmptyString(metavar);
5272
+ checkEnumOption(options, "rootType", [
5273
+ "string",
5274
+ "number",
5275
+ "boolean",
5276
+ "null",
5277
+ "object",
5278
+ "array"
5279
+ ]);
5280
+ const rootType = options?.rootType;
5281
+ const invalidJsonError = options?.errors?.invalidJson;
5282
+ const invalidRootTypeError = options?.errors?.invalidRootType;
5283
+ if (options?.placeholder !== void 0) {
5284
+ const p = options.placeholder;
5285
+ const nonFinitePlaceholder = findNonFiniteNumber(p);
5286
+ if (nonFinitePlaceholder !== void 0) throw new TypeError(`Expected placeholder to contain only finite numbers, but found ${String(nonFinitePlaceholder)}.`);
5287
+ if (rootType != null && jsonTypeOf(p) !== rootType) throw new TypeError(`Expected placeholder to be a JSON ${rootType}, but got ${jsonTypeOf(p)}.`);
5288
+ }
5289
+ const defaultPlaceholder = rootType === "string" ? "" : rootType === "number" ? 0 : rootType === "boolean" ? false : rootType === "object" ? {} : rootType === "array" ? [] : null;
5290
+ const placeholder = options?.placeholder ?? defaultPlaceholder;
5291
+ return {
5292
+ mode: "sync",
5293
+ metavar,
5294
+ placeholder,
5295
+ parse(input) {
5296
+ let value;
5297
+ try {
5298
+ value = JSON.parse(input);
5299
+ } catch (e) {
5300
+ const err = e instanceof Error ? e : new Error(String(e));
5301
+ const error = invalidJsonError instanceof Function ? invalidJsonError(input) : invalidJsonError ?? [require_message.text(`Not a valid JSON: ${err.message}`)];
5302
+ return {
5303
+ success: false,
5304
+ error
5305
+ };
5306
+ }
5307
+ const nonFinite = findNonFiniteNumber(value);
5308
+ if (nonFinite !== void 0) {
5309
+ const error = invalidJsonError instanceof Function ? invalidJsonError(input) : invalidJsonError ?? [require_message.text(`Not a valid JSON: number out of range.`)];
5310
+ return {
5311
+ success: false,
5312
+ error
5313
+ };
5314
+ }
5315
+ if (rootType != null) {
5316
+ const actual = jsonTypeOf(value);
5317
+ if (actual !== rootType) {
5318
+ const error = invalidRootTypeError instanceof Function ? invalidRootTypeError(value, rootType) : invalidRootTypeError ?? [require_message.text(`Expected JSON ${rootType}, but got ${actual}.`)];
5319
+ return {
5320
+ success: false,
5321
+ error
5322
+ };
5323
+ }
5324
+ }
5325
+ return {
5326
+ success: true,
5327
+ value
5328
+ };
5329
+ },
5330
+ format(value) {
5331
+ const nonFinite = findNonFiniteNumber(value);
5332
+ if (nonFinite !== void 0) throw new TypeError(`Expected a finite JSON number, but got ${String(nonFinite)}.`);
5333
+ return JSON.stringify(value);
5334
+ }
5335
+ };
5336
+ }
5337
+ function jsonTypeOf(value) {
5338
+ if (value === null) return "null";
5339
+ if (Array.isArray(value)) return "array";
5340
+ return typeof value;
5341
+ }
5342
+ /**
5343
+ * Finds the first non-finite number (`NaN`, `Infinity`, or `-Infinity`)
5344
+ * anywhere in a JSON structure.
5345
+ *
5346
+ * Uses an explicit stack rather than recursion to avoid call-stack overflows
5347
+ * on deeply nested inputs. Tracks visited objects to handle circular
5348
+ * references without looping forever.
5349
+ *
5350
+ * @returns The first non-finite number found, or `undefined` if all numbers
5351
+ * in the structure are finite.
5352
+ */
5353
+ function findNonFiniteNumber(root) {
5354
+ const stack = [root];
5355
+ const seen = /* @__PURE__ */ new Set();
5356
+ while (stack.length > 0) {
5357
+ const value = stack.pop();
5358
+ if (typeof value === "number") {
5359
+ if (!Number.isFinite(value)) return value;
5360
+ } else if (Array.isArray(value)) {
5361
+ if (seen.has(value)) continue;
5362
+ seen.add(value);
5363
+ for (const item of value) stack.push(item);
5364
+ } else if (value !== null && typeof value === "object") {
5365
+ if (seen.has(value)) continue;
5366
+ seen.add(value);
5367
+ for (const item of Object.values(value)) stack.push(item);
5368
+ }
5369
+ }
5370
+ return void 0;
5371
+ }
5238
5372
 
5239
5373
  //#endregion
5240
5374
  exports.checkBooleanOption = checkBooleanOption;
@@ -5254,6 +5388,7 @@ exports.ipv4 = ipv4;
5254
5388
  exports.ipv6 = ipv6;
5255
5389
  exports.isNonEmptyString = require_nonempty.isNonEmptyString;
5256
5390
  exports.isValueParser = isValueParser;
5391
+ exports.json = json;
5257
5392
  exports.locale = locale;
5258
5393
  exports.macAddress = macAddress;
5259
5394
  exports.port = port;
@@ -161,7 +161,7 @@ type ValueParserResult<T> = {
161
161
  * A recursive map that tracks which fields in a parsed object hold deferred
162
162
  * placeholder values. Each entry maps a property key to either `null`
163
163
  * (the field is fully deferred and should be replaced with `undefined`)
164
- * or another `DeferredMap` (the field is partially deferred recurse into
164
+ * or another `DeferredMap` (the field is partially deferred—recurse into
165
165
  * its sub-fields).
166
166
  *
167
167
  * @since 1.0.0
@@ -2559,5 +2559,157 @@ declare function semVer(options?: SemVerOptionsString): ValueParser<"sync", SemV
2559
2559
  * @since 1.1.0
2560
2560
  */
2561
2561
  declare function semVer(options: SemVerOptionsObject): ValueParser<"sync", SemVer>;
2562
+ /**
2563
+ * Any JSON-serializable value.
2564
+ *
2565
+ * This type is a TypeScript approximation of JSON data values. Note that
2566
+ * certain JavaScript distinctions are not preserved through serialization:
2567
+ * for example, `-0` serializes as `"0"`, so a round-trip through
2568
+ * `format()` and `parse()` may return `0` instead.
2569
+ *
2570
+ * @since 1.1.0
2571
+ */
2572
+ type Json = string | number | boolean | null | {
2573
+ readonly [property: string]: Json;
2574
+ } | readonly Json[];
2575
+ /**
2576
+ * Options for creating a {@link json} value parser.
2577
+ *
2578
+ * @since 1.1.0
2579
+ */
2580
+ interface JsonOptions {
2581
+ /**
2582
+ * The metavariable name for this parser. This is used in help messages to
2583
+ * indicate what kind of value this parser expects. Usually a single
2584
+ * word in uppercase, like `DATA` or `CONFIG`.
2585
+ * @default `"JSON"`
2586
+ */
2587
+ readonly metavar?: NonEmptyString;
2588
+ /**
2589
+ * A custom placeholder value used during deferred prompt resolution.
2590
+ * @default Depends on `rootType`: `null` when unset, `""` for `"string"`,
2591
+ * `0` for `"number"`, `false` for `"boolean"`, `null` for `"null"`,
2592
+ * `{}` for `"object"`, `[]` for `"array"`.
2593
+ * @since 1.1.0
2594
+ */
2595
+ readonly placeholder?: Json;
2596
+ /**
2597
+ * Restricts the expected JSON root type. When set, the parser rejects
2598
+ * JSON values whose root type does not match and narrows the TypeScript
2599
+ * return type accordingly.
2600
+ *
2601
+ * @since 1.1.0
2602
+ */
2603
+ readonly rootType?: "string" | "number" | "boolean" | "null" | "object" | "array";
2604
+ /**
2605
+ * Custom error messages for JSON parsing failures.
2606
+ *
2607
+ * @since 1.1.0
2608
+ */
2609
+ readonly errors?: {
2610
+ /**
2611
+ * Custom error message when the input is not valid JSON.
2612
+ * Can be a static message or a function that receives the raw input.
2613
+ * @since 1.1.0
2614
+ */
2615
+ readonly invalidJson?: Message | ((input: string) => Message);
2616
+ /**
2617
+ * Custom error message when the parsed JSON value does not match the
2618
+ * expected `rootType`. Can be a static message or a function that
2619
+ * receives the parsed value and the expected root type name.
2620
+ * @since 1.1.0
2621
+ */
2622
+ readonly invalidRootType?: Message | ((value: Json, expected: string) => Message);
2623
+ };
2624
+ }
2625
+ /**
2626
+ * Creates a {@link ValueParser} that parses JSON-encoded strings and returns
2627
+ * a `string`.
2628
+ *
2629
+ * @param options Configuration options including `rootType: "string"`.
2630
+ * @returns A parser whose successful value is typed as `string`.
2631
+ * @since 1.1.0
2632
+ */
2633
+ declare function json(options: JsonOptions & {
2634
+ readonly rootType: "string";
2635
+ readonly placeholder?: string;
2636
+ }): ValueParser<"sync", string>;
2637
+ /**
2638
+ * Creates a {@link ValueParser} that parses JSON-encoded strings and returns
2639
+ * a `number`.
2640
+ *
2641
+ * @param options Configuration options including `rootType: "number"`.
2642
+ * @returns A parser whose successful value is typed as `number`.
2643
+ * @since 1.1.0
2644
+ */
2645
+ declare function json(options: JsonOptions & {
2646
+ readonly rootType: "number";
2647
+ readonly placeholder?: number;
2648
+ }): ValueParser<"sync", number>;
2649
+ /**
2650
+ * Creates a {@link ValueParser} that parses JSON-encoded strings and returns
2651
+ * a `boolean`.
2652
+ *
2653
+ * @param options Configuration options including `rootType: "boolean"`.
2654
+ * @returns A parser whose successful value is typed as `boolean`.
2655
+ * @since 1.1.0
2656
+ */
2657
+ declare function json(options: JsonOptions & {
2658
+ readonly rootType: "boolean";
2659
+ readonly placeholder?: boolean;
2660
+ }): ValueParser<"sync", boolean>;
2661
+ /**
2662
+ * Creates a {@link ValueParser} that parses JSON-encoded strings and returns
2663
+ * `null`.
2664
+ *
2665
+ * @param options Configuration options including `rootType: "null"`.
2666
+ * @returns A parser whose successful value is typed as `null`.
2667
+ * @since 1.1.0
2668
+ */
2669
+ declare function json(options: JsonOptions & {
2670
+ readonly rootType: "null";
2671
+ readonly placeholder?: null;
2672
+ }): ValueParser<"sync", null>;
2673
+ /**
2674
+ * Creates a {@link ValueParser} that parses JSON-encoded strings and returns
2675
+ * a plain JSON object.
2676
+ *
2677
+ * @param options Configuration options including `rootType: "object"`.
2678
+ * @returns A parser whose successful value is typed as
2679
+ * `{ readonly [property: string]: Json }`.
2680
+ * @since 1.1.0
2681
+ */
2682
+ declare function json(options: JsonOptions & {
2683
+ readonly rootType: "object";
2684
+ readonly placeholder?: {
2685
+ readonly [property: string]: Json;
2686
+ };
2687
+ }): ValueParser<"sync", {
2688
+ readonly [property: string]: Json;
2689
+ }>;
2690
+ /**
2691
+ * Creates a {@link ValueParser} that parses JSON-encoded strings and returns
2692
+ * a JSON array.
2693
+ *
2694
+ * @param options Configuration options including `rootType: "array"`.
2695
+ * @returns A parser whose successful value is typed as `readonly Json[]`.
2696
+ * @since 1.1.0
2697
+ */
2698
+ declare function json(options: JsonOptions & {
2699
+ readonly rootType: "array";
2700
+ readonly placeholder?: readonly Json[];
2701
+ }): ValueParser<"sync", readonly Json[]>;
2702
+ /**
2703
+ * Creates a {@link ValueParser} that parses JSON-encoded strings into any
2704
+ * {@link Json} value (object, array, string, number, boolean, or null).
2705
+ *
2706
+ * Also accepts a pre-typed `JsonOptions` variable when the `rootType` is not
2707
+ * known at compile time; the return type is the widened {@link Json} union.
2708
+ *
2709
+ * @param options Optional configuration for the parser.
2710
+ * @returns A parser whose successful value is typed as {@link Json}.
2711
+ * @since 1.1.0
2712
+ */
2713
+ declare function json(options?: JsonOptions): ValueParser<"sync", Json>;
2562
2714
  //#endregion
2563
- export { ChoiceOptions, ChoiceOptionsBase, ChoiceOptionsNumber, ChoiceOptionsString, CidrOptions, CidrValue, Color, ColorFormat, ColorOptions, DeferredMap, DomainOptions, EmailOptions, FileSizeOptions, FileSizeOptionsBigInt, FileSizeOptionsNumber, FileSizeUnit, FloatOptions, HostnameOptions, IntegerOptionsBigInt, IntegerOptionsNumber, IpOptions, Ipv4Options, Ipv6Options, LocaleOptions, MacAddressOptions, type Mode, type ModeIterable, type ModeValue, type NonEmptyString, PortOptionsBigInt, PortOptionsNumber, PortRangeOptionsBigInt, PortRangeOptionsNumber, PortRangeValueBigInt, PortRangeValueNumber, SemVer, SemVerOptionsObject, SemVerOptionsString, SemVerString, SocketAddressOptions, SocketAddressValue, StringOptions, UrlOptions, Uuid, UuidOptions, ValueParser, ValueParserResult, checkBooleanOption, checkEnumOption, choice, cidr, color, domain, email, ensureNonEmptyString, fileSize, float, hostname, integer, ip, ipv4, ipv6, isNonEmptyString, isValueParser, locale, macAddress, port, portRange, semVer, socketAddress, string, url, uuid };
2715
+ export { ChoiceOptions, ChoiceOptionsBase, ChoiceOptionsNumber, ChoiceOptionsString, CidrOptions, CidrValue, Color, ColorFormat, ColorOptions, DeferredMap, DomainOptions, EmailOptions, FileSizeOptions, FileSizeOptionsBigInt, FileSizeOptionsNumber, FileSizeUnit, FloatOptions, HostnameOptions, IntegerOptionsBigInt, IntegerOptionsNumber, IpOptions, Ipv4Options, Ipv6Options, Json, JsonOptions, LocaleOptions, MacAddressOptions, type Mode, type ModeIterable, type ModeValue, type NonEmptyString, PortOptionsBigInt, PortOptionsNumber, PortRangeOptionsBigInt, PortRangeOptionsNumber, PortRangeValueBigInt, PortRangeValueNumber, SemVer, SemVerOptionsObject, SemVerOptionsString, SemVerString, SocketAddressOptions, SocketAddressValue, StringOptions, UrlOptions, Uuid, UuidOptions, ValueParser, ValueParserResult, checkBooleanOption, checkEnumOption, choice, cidr, color, domain, email, ensureNonEmptyString, fileSize, float, hostname, integer, ip, ipv4, ipv6, isNonEmptyString, isValueParser, json, locale, macAddress, port, portRange, semVer, socketAddress, string, url, uuid };
@@ -161,7 +161,7 @@ type ValueParserResult<T> = {
161
161
  * A recursive map that tracks which fields in a parsed object hold deferred
162
162
  * placeholder values. Each entry maps a property key to either `null`
163
163
  * (the field is fully deferred and should be replaced with `undefined`)
164
- * or another `DeferredMap` (the field is partially deferred recurse into
164
+ * or another `DeferredMap` (the field is partially deferred—recurse into
165
165
  * its sub-fields).
166
166
  *
167
167
  * @since 1.0.0
@@ -2559,5 +2559,157 @@ declare function semVer(options?: SemVerOptionsString): ValueParser<"sync", SemV
2559
2559
  * @since 1.1.0
2560
2560
  */
2561
2561
  declare function semVer(options: SemVerOptionsObject): ValueParser<"sync", SemVer>;
2562
+ /**
2563
+ * Any JSON-serializable value.
2564
+ *
2565
+ * This type is a TypeScript approximation of JSON data values. Note that
2566
+ * certain JavaScript distinctions are not preserved through serialization:
2567
+ * for example, `-0` serializes as `"0"`, so a round-trip through
2568
+ * `format()` and `parse()` may return `0` instead.
2569
+ *
2570
+ * @since 1.1.0
2571
+ */
2572
+ type Json = string | number | boolean | null | {
2573
+ readonly [property: string]: Json;
2574
+ } | readonly Json[];
2575
+ /**
2576
+ * Options for creating a {@link json} value parser.
2577
+ *
2578
+ * @since 1.1.0
2579
+ */
2580
+ interface JsonOptions {
2581
+ /**
2582
+ * The metavariable name for this parser. This is used in help messages to
2583
+ * indicate what kind of value this parser expects. Usually a single
2584
+ * word in uppercase, like `DATA` or `CONFIG`.
2585
+ * @default `"JSON"`
2586
+ */
2587
+ readonly metavar?: NonEmptyString;
2588
+ /**
2589
+ * A custom placeholder value used during deferred prompt resolution.
2590
+ * @default Depends on `rootType`: `null` when unset, `""` for `"string"`,
2591
+ * `0` for `"number"`, `false` for `"boolean"`, `null` for `"null"`,
2592
+ * `{}` for `"object"`, `[]` for `"array"`.
2593
+ * @since 1.1.0
2594
+ */
2595
+ readonly placeholder?: Json;
2596
+ /**
2597
+ * Restricts the expected JSON root type. When set, the parser rejects
2598
+ * JSON values whose root type does not match and narrows the TypeScript
2599
+ * return type accordingly.
2600
+ *
2601
+ * @since 1.1.0
2602
+ */
2603
+ readonly rootType?: "string" | "number" | "boolean" | "null" | "object" | "array";
2604
+ /**
2605
+ * Custom error messages for JSON parsing failures.
2606
+ *
2607
+ * @since 1.1.0
2608
+ */
2609
+ readonly errors?: {
2610
+ /**
2611
+ * Custom error message when the input is not valid JSON.
2612
+ * Can be a static message or a function that receives the raw input.
2613
+ * @since 1.1.0
2614
+ */
2615
+ readonly invalidJson?: Message | ((input: string) => Message);
2616
+ /**
2617
+ * Custom error message when the parsed JSON value does not match the
2618
+ * expected `rootType`. Can be a static message or a function that
2619
+ * receives the parsed value and the expected root type name.
2620
+ * @since 1.1.0
2621
+ */
2622
+ readonly invalidRootType?: Message | ((value: Json, expected: string) => Message);
2623
+ };
2624
+ }
2625
+ /**
2626
+ * Creates a {@link ValueParser} that parses JSON-encoded strings and returns
2627
+ * a `string`.
2628
+ *
2629
+ * @param options Configuration options including `rootType: "string"`.
2630
+ * @returns A parser whose successful value is typed as `string`.
2631
+ * @since 1.1.0
2632
+ */
2633
+ declare function json(options: JsonOptions & {
2634
+ readonly rootType: "string";
2635
+ readonly placeholder?: string;
2636
+ }): ValueParser<"sync", string>;
2637
+ /**
2638
+ * Creates a {@link ValueParser} that parses JSON-encoded strings and returns
2639
+ * a `number`.
2640
+ *
2641
+ * @param options Configuration options including `rootType: "number"`.
2642
+ * @returns A parser whose successful value is typed as `number`.
2643
+ * @since 1.1.0
2644
+ */
2645
+ declare function json(options: JsonOptions & {
2646
+ readonly rootType: "number";
2647
+ readonly placeholder?: number;
2648
+ }): ValueParser<"sync", number>;
2649
+ /**
2650
+ * Creates a {@link ValueParser} that parses JSON-encoded strings and returns
2651
+ * a `boolean`.
2652
+ *
2653
+ * @param options Configuration options including `rootType: "boolean"`.
2654
+ * @returns A parser whose successful value is typed as `boolean`.
2655
+ * @since 1.1.0
2656
+ */
2657
+ declare function json(options: JsonOptions & {
2658
+ readonly rootType: "boolean";
2659
+ readonly placeholder?: boolean;
2660
+ }): ValueParser<"sync", boolean>;
2661
+ /**
2662
+ * Creates a {@link ValueParser} that parses JSON-encoded strings and returns
2663
+ * `null`.
2664
+ *
2665
+ * @param options Configuration options including `rootType: "null"`.
2666
+ * @returns A parser whose successful value is typed as `null`.
2667
+ * @since 1.1.0
2668
+ */
2669
+ declare function json(options: JsonOptions & {
2670
+ readonly rootType: "null";
2671
+ readonly placeholder?: null;
2672
+ }): ValueParser<"sync", null>;
2673
+ /**
2674
+ * Creates a {@link ValueParser} that parses JSON-encoded strings and returns
2675
+ * a plain JSON object.
2676
+ *
2677
+ * @param options Configuration options including `rootType: "object"`.
2678
+ * @returns A parser whose successful value is typed as
2679
+ * `{ readonly [property: string]: Json }`.
2680
+ * @since 1.1.0
2681
+ */
2682
+ declare function json(options: JsonOptions & {
2683
+ readonly rootType: "object";
2684
+ readonly placeholder?: {
2685
+ readonly [property: string]: Json;
2686
+ };
2687
+ }): ValueParser<"sync", {
2688
+ readonly [property: string]: Json;
2689
+ }>;
2690
+ /**
2691
+ * Creates a {@link ValueParser} that parses JSON-encoded strings and returns
2692
+ * a JSON array.
2693
+ *
2694
+ * @param options Configuration options including `rootType: "array"`.
2695
+ * @returns A parser whose successful value is typed as `readonly Json[]`.
2696
+ * @since 1.1.0
2697
+ */
2698
+ declare function json(options: JsonOptions & {
2699
+ readonly rootType: "array";
2700
+ readonly placeholder?: readonly Json[];
2701
+ }): ValueParser<"sync", readonly Json[]>;
2702
+ /**
2703
+ * Creates a {@link ValueParser} that parses JSON-encoded strings into any
2704
+ * {@link Json} value (object, array, string, number, boolean, or null).
2705
+ *
2706
+ * Also accepts a pre-typed `JsonOptions` variable when the `rootType` is not
2707
+ * known at compile time; the return type is the widened {@link Json} union.
2708
+ *
2709
+ * @param options Optional configuration for the parser.
2710
+ * @returns A parser whose successful value is typed as {@link Json}.
2711
+ * @since 1.1.0
2712
+ */
2713
+ declare function json(options?: JsonOptions): ValueParser<"sync", Json>;
2562
2714
  //#endregion
2563
- export { ChoiceOptions, ChoiceOptionsBase, ChoiceOptionsNumber, ChoiceOptionsString, CidrOptions, CidrValue, Color, ColorFormat, ColorOptions, DeferredMap, DomainOptions, EmailOptions, FileSizeOptions, FileSizeOptionsBigInt, FileSizeOptionsNumber, FileSizeUnit, FloatOptions, HostnameOptions, IntegerOptionsBigInt, IntegerOptionsNumber, IpOptions, Ipv4Options, Ipv6Options, LocaleOptions, MacAddressOptions, type Mode, type ModeIterable, type ModeValue, type NonEmptyString, PortOptionsBigInt, PortOptionsNumber, PortRangeOptionsBigInt, PortRangeOptionsNumber, PortRangeValueBigInt, PortRangeValueNumber, SemVer, SemVerOptionsObject, SemVerOptionsString, SemVerString, SocketAddressOptions, SocketAddressValue, StringOptions, UrlOptions, Uuid, UuidOptions, ValueParser, ValueParserResult, checkBooleanOption, checkEnumOption, choice, cidr, color, domain, email, ensureNonEmptyString, fileSize, float, hostname, integer, ip, ipv4, ipv6, isNonEmptyString, isValueParser, locale, macAddress, port, portRange, semVer, socketAddress, string, url, uuid };
2715
+ export { ChoiceOptions, ChoiceOptionsBase, ChoiceOptionsNumber, ChoiceOptionsString, CidrOptions, CidrValue, Color, ColorFormat, ColorOptions, DeferredMap, DomainOptions, EmailOptions, FileSizeOptions, FileSizeOptionsBigInt, FileSizeOptionsNumber, FileSizeUnit, FloatOptions, HostnameOptions, IntegerOptionsBigInt, IntegerOptionsNumber, IpOptions, Ipv4Options, Ipv6Options, Json, JsonOptions, LocaleOptions, MacAddressOptions, type Mode, type ModeIterable, type ModeValue, type NonEmptyString, PortOptionsBigInt, PortOptionsNumber, PortRangeOptionsBigInt, PortRangeOptionsNumber, PortRangeValueBigInt, PortRangeValueNumber, SemVer, SemVerOptionsObject, SemVerOptionsString, SemVerString, SocketAddressOptions, SocketAddressValue, StringOptions, UrlOptions, Uuid, UuidOptions, ValueParser, ValueParserResult, checkBooleanOption, checkEnumOption, choice, cidr, color, domain, email, ensureNonEmptyString, fileSize, float, hostname, integer, ip, ipv4, ipv6, isNonEmptyString, isValueParser, json, locale, macAddress, port, portRange, semVer, socketAddress, string, url, uuid };
@@ -5235,6 +5235,140 @@ function semVer(options = {}) {
5235
5235
  }
5236
5236
  };
5237
5237
  }
5238
+ /**
5239
+ * Creates a {@link ValueParser} for parsing JSON-encoded strings from the
5240
+ * command line.
5241
+ *
5242
+ * The parser accepts any well-formed JSON string by default. Use the
5243
+ * `rootType` option to restrict which JSON root type is accepted and to
5244
+ * narrow the TypeScript return type accordingly.
5245
+ *
5246
+ * @example
5247
+ * ```typescript
5248
+ * // Accept any JSON value
5249
+ * const anyJson = json();
5250
+ *
5251
+ * // Accept only JSON objects (return type narrowed)
5252
+ * const objJson = json({ rootType: "object" });
5253
+ * ```
5254
+ *
5255
+ * @param options Optional configuration for the parser.
5256
+ * @returns A {@link ValueParser} that converts JSON-encoded strings to the
5257
+ * appropriate JavaScript type.
5258
+ * @throws {TypeError} If `options.metavar` is provided but is an empty string.
5259
+ * @throws {TypeError} If `options.rootType` is provided but is not one of the
5260
+ * six allowed values.
5261
+ * @throws {TypeError} If `options.placeholder` or any value nested within
5262
+ * it is a non-finite number (`Infinity`, `-Infinity`, or `NaN`).
5263
+ * @throws {TypeError} If `options.placeholder` is provided with a `rootType`
5264
+ * but its JSON type does not match the `rootType`.
5265
+ * @throws {TypeError} If the returned parser's `format()` method is called
5266
+ * with a value that contains a non-finite number anywhere in its structure.
5267
+ * @since 1.1.0
5268
+ */
5269
+ function json(options) {
5270
+ const metavar = options?.metavar ?? "JSON";
5271
+ ensureNonEmptyString(metavar);
5272
+ checkEnumOption(options, "rootType", [
5273
+ "string",
5274
+ "number",
5275
+ "boolean",
5276
+ "null",
5277
+ "object",
5278
+ "array"
5279
+ ]);
5280
+ const rootType = options?.rootType;
5281
+ const invalidJsonError = options?.errors?.invalidJson;
5282
+ const invalidRootTypeError = options?.errors?.invalidRootType;
5283
+ if (options?.placeholder !== void 0) {
5284
+ const p = options.placeholder;
5285
+ const nonFinitePlaceholder = findNonFiniteNumber(p);
5286
+ if (nonFinitePlaceholder !== void 0) throw new TypeError(`Expected placeholder to contain only finite numbers, but found ${String(nonFinitePlaceholder)}.`);
5287
+ if (rootType != null && jsonTypeOf(p) !== rootType) throw new TypeError(`Expected placeholder to be a JSON ${rootType}, but got ${jsonTypeOf(p)}.`);
5288
+ }
5289
+ const defaultPlaceholder = rootType === "string" ? "" : rootType === "number" ? 0 : rootType === "boolean" ? false : rootType === "object" ? {} : rootType === "array" ? [] : null;
5290
+ const placeholder = options?.placeholder ?? defaultPlaceholder;
5291
+ return {
5292
+ mode: "sync",
5293
+ metavar,
5294
+ placeholder,
5295
+ parse(input) {
5296
+ let value;
5297
+ try {
5298
+ value = JSON.parse(input);
5299
+ } catch (e) {
5300
+ const err = e instanceof Error ? e : new Error(String(e));
5301
+ const error = invalidJsonError instanceof Function ? invalidJsonError(input) : invalidJsonError ?? [text(`Not a valid JSON: ${err.message}`)];
5302
+ return {
5303
+ success: false,
5304
+ error
5305
+ };
5306
+ }
5307
+ const nonFinite = findNonFiniteNumber(value);
5308
+ if (nonFinite !== void 0) {
5309
+ const error = invalidJsonError instanceof Function ? invalidJsonError(input) : invalidJsonError ?? [text(`Not a valid JSON: number out of range.`)];
5310
+ return {
5311
+ success: false,
5312
+ error
5313
+ };
5314
+ }
5315
+ if (rootType != null) {
5316
+ const actual = jsonTypeOf(value);
5317
+ if (actual !== rootType) {
5318
+ const error = invalidRootTypeError instanceof Function ? invalidRootTypeError(value, rootType) : invalidRootTypeError ?? [text(`Expected JSON ${rootType}, but got ${actual}.`)];
5319
+ return {
5320
+ success: false,
5321
+ error
5322
+ };
5323
+ }
5324
+ }
5325
+ return {
5326
+ success: true,
5327
+ value
5328
+ };
5329
+ },
5330
+ format(value) {
5331
+ const nonFinite = findNonFiniteNumber(value);
5332
+ if (nonFinite !== void 0) throw new TypeError(`Expected a finite JSON number, but got ${String(nonFinite)}.`);
5333
+ return JSON.stringify(value);
5334
+ }
5335
+ };
5336
+ }
5337
+ function jsonTypeOf(value) {
5338
+ if (value === null) return "null";
5339
+ if (Array.isArray(value)) return "array";
5340
+ return typeof value;
5341
+ }
5342
+ /**
5343
+ * Finds the first non-finite number (`NaN`, `Infinity`, or `-Infinity`)
5344
+ * anywhere in a JSON structure.
5345
+ *
5346
+ * Uses an explicit stack rather than recursion to avoid call-stack overflows
5347
+ * on deeply nested inputs. Tracks visited objects to handle circular
5348
+ * references without looping forever.
5349
+ *
5350
+ * @returns The first non-finite number found, or `undefined` if all numbers
5351
+ * in the structure are finite.
5352
+ */
5353
+ function findNonFiniteNumber(root) {
5354
+ const stack = [root];
5355
+ const seen = /* @__PURE__ */ new Set();
5356
+ while (stack.length > 0) {
5357
+ const value = stack.pop();
5358
+ if (typeof value === "number") {
5359
+ if (!Number.isFinite(value)) return value;
5360
+ } else if (Array.isArray(value)) {
5361
+ if (seen.has(value)) continue;
5362
+ seen.add(value);
5363
+ for (const item of value) stack.push(item);
5364
+ } else if (value !== null && typeof value === "object") {
5365
+ if (seen.has(value)) continue;
5366
+ seen.add(value);
5367
+ for (const item of Object.values(value)) stack.push(item);
5368
+ }
5369
+ }
5370
+ return void 0;
5371
+ }
5238
5372
 
5239
5373
  //#endregion
5240
- export { checkBooleanOption, checkEnumOption, choice, cidr, color, domain, email, ensureNonEmptyString, fileSize, float, hostname, integer, ip, ipv4, ipv6, isNonEmptyString, isValueParser, locale, macAddress, port, portRange, semVer, socketAddress, string, url, uuid };
5374
+ export { checkBooleanOption, checkEnumOption, choice, cidr, color, domain, email, ensureNonEmptyString, fileSize, float, hostname, integer, ip, ipv4, ipv6, isNonEmptyString, isValueParser, json, locale, macAddress, port, portRange, semVer, socketAddress, string, url, uuid };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@optique/core",
3
- "version": "1.1.0-dev.2069",
3
+ "version": "1.1.0-dev.2077",
4
4
  "description": "Type-safe combinatorial command-line interface parser",
5
5
  "keywords": [
6
6
  "CLI",