β¨ a command line builder β¨
- What is this?
- Install
- Use
- API
Argument(info)Command(info)Command#action([action])Command#addArgument(argument)Command#addCommand(subcommand)Command#addOption(option)Command#alias([alias])Command#aliases([aliases])Command#ancestors()Command#argsCommand#argument(info[, data])Command#arguments([infos])Command#argvCommand#command(info[, data])Command#commands([infos])Command#copyInheritedSettings(parent)Command#createArgument(info[, data])Command#createCommand(info[, data])Command#createOption(info[, data])Command#defaultCommand#defaultCommandCommand#done([done])Command#emit(event)Command#emitOption(option, value, source[, flags])Command#example(info[, prefix])Command#examples([examples])Command#error(info)Command#exit([e])Command#exiter([exit])Command#findCommand(ref)Command#findOption(flag[, direction])Command#helpCommand([help])Command#helpOption([help])Command#helpUtility([util])Command#id([name])Command#loggerCommand#on<T>(event, listener[, options])Command#option(info[, data])Command#optionPriority([priority])Command#optionValue(key[, value][, source])Command#optionValueSource(key[, source])Command#options([infos])Command#opts<T>()Command#optsWithGlobals<T>()Command#parentCommand#parse([argv][, options])Command#parseAsync([argv][, options])Command#processCommand#snapshot()Command#summary([summary])Command#toString()Command#unknownCommand#unknowns([strategy])Command#usage([usage])Command#version([version])
CommandError(info)Help([options])Helpable([info])KronkError(info)KronkEvent(id)Option(info)OptionEvent<T>(option, value, source[, flag])Parseable([info])VersionOption(info)keidoptionValueSource
- Types
ActionArgumentDataArgumentInfoArgumentMetadataArgumentSyntaxMapArgumentSyntaxArgumentsDataArgvSourceMapArgvSourceAwaitableCommandDataCommandErrorInfoCommandErrorSnapshotCommandInfoCommandMetadataCommandNameCommandSnapshotDefaultInfoEmptyStringExampleInfoExamplesDataExitCodeExitProcessExitFlagsHelpCommandDataHelpOptionDataHelpTextOptionsHelpableInfoKronkErrorCauseKronkErrorIdKronkErrorInfoKronkErrorJsonKronkErrorMapKronkEventListenerKronkEventNameMapListOptionDataOptionEventListenerOptionEventNameMapOptionEventNameOptionInfoOptionMetadataOptionPriorityOptionValueSourceMapOptionValueSourceOptionValueSourcesOptionsDataParseArgParseOptionsParseUnknownResultParseableInfoParseableMetadataProcessEnvProcessRawOptionValueRawParseValueSubcommandInfoSubcommandsDataSubcommandsInfoUnknownStrategyUsageDataUsageInfoVersionDataVersionOptionInfoVersion
- Contribute
kronk is a utility for building command-line applications in node.js and bun.
This package is ESM only.
With yarn:
yarn add @flex-development/kronkSee Git - Protocols | Yarn Β for info regarding installing from Git.
With bun:
bun add @flex-development/kronk
See bun add for more details.
TODO: use
kronk exports a global program object convenient for quick programs.
This is used in the examples throughout this README for brevity.
import { program } from '@flex-development/kronk'For larger programs using kronk in multiple ways, including unit testing, a Command should be created.
import { Command } from '@flex-development/kronk'
const program: Command = new Command()Options are defined with the .option() and .options() methods,
which also serve as documentation for the options. Each option can have at most 2 flags, typically one long flag and one
short or shortish (e.g. -w, --ws) flag. Flags can be separated by commas (,), pipes (|), or spaces ( ).
An option and its option-argument can be separated by an equal sign (=) or spaces ( ).
A short option (i.e. -p) and its option-argument can also be combined.
serve --port 80
serve --port=80
serve -p 80
serve -p80
serve -p=80Options on the command line are not positional, and can be specified before or after command-arguments.
serve --port=80 ./server.mts
serve ./src/main.mts -p8080If a non-option (i.e. -13) looks like an option because it starts with a hyphen (-), a delimiter (--) can be used
to demarcate the command-argument from an option.
clamp -M3 -m-1 -- -13Parsed options can be accessed by calling .opts<T>() on a Command object, and are
passed to the command's action handler.
Multi-word options such as --template-engine are camelCased, becoming program.opts().templateEngine, or can be
configured to be converted using snake_case, becoming program.opts().template_engine.
There are additional, related routines for when .opts<T>() is not enough:
A command argument (class).
constructor(info: ArgumentInfo | string)constructor(info: string, data?: ArgumentData | null | undefined)
info(ArgumentInfo|string) β argument info or syntaxdata(ArgumentData) β additional argument info
string
The argument syntax id.
The normalized argument syntax string.
Get the argument as a human-readable string.
(string) String representation of this argument
A command (class).
constructor(info: CommandInfo | string)constructor(info: string, data?: CommandData | null | undefined)
info(CommandInfo|string) β command info or namedata(CommandData) β additional command info
Get or set the command action callback.
action(action: Action<any> | null | undefined): thisaction<Opts extends OptionValues = OptionValues, Args extends any[] = any[]>(): Action<Opts, Args>
Opts(OptionValues, optional) β parsed command optionsArgs(any[], optional) β parsed command arguments
action(Action<any>|null|undefined) β the callback to fire when the command is ran
(Action<Opts, Args> | this) The command action callback or this command
Add a prepared argument.
argument(Argument) β the argument instance to add
(never | this) this command
(KronkError) If the last registered argument is variadic
Add a prepared subcommand.
π Note: See
commandfor creating an attached subcommand that inherits settings from itsparent.
subcommand(Command) β the command instance to add
(never | this) this command
(KronkError) If subcommand does not have a valid name
or a subcommand with the same name or alias as subcommand already exists
Add a prepared option.
option(Option) β the option instance to add
(never | this) this command
(KronkError) If an option with the same long or short flag as option already exists
Get an alias for the command or add a command alias.
π Note: This method can be called more than once to add multiple aliases.
alias(alias: string): thisalias(): CommandName
alias(string) β an alias for the command
(CommandName | this) Command alias or this command
Get or add aliases for the command.
aliases(aliases: List<string> | string | null | undefined): thisaliases(): Set<string>
aliases(List<string>|string|null|undefined) β an alias, or list of aliases, for the command
(Set<string> | this) List of command aliases or this command
Get a list of ancestor commands.
The first command is the parent of this command, and the last is the greatest grandparent of this command.
(Command[]) List of ancestor commands
any[]
Parsed command-line arguments.
Define an argument for the command.
argument(info: ArgumentInfo | string): thisargument(info: string, data?: ArgumentData | null | undefined): this
info(ArgumentInfo|string) β argument info or syntaxdata(ArgumentData, optional) β additional argument info
(this) this command
Get a list of command arguments or batch define arguments for the command.
arguments(infos: List<ArgumentInfo | string> | string): thisarguments(): Argument[]
infos(List<ArgumentInfo | string>|string) β list of argument info and/or syntaxes, or a string containing argument syntaxes
(Argument[] | this) List of command arguments or this command
string[]
Raw command-line arguments.
Define a subcommand.
command(info: SubcommandInfo | string): Commandcommand(info: string, data?: CommandData | null | undefined): Command
info(SubcommandInfo|string) β subcommand info or namedata(CommandData) β additional subcommand info
(Command) Subcommand instance
Get a subcommand map or batch define subcommands for the command.
commands(infos: SubcommandsInfo): thiscommands(): Map<string, Command>
infos(SubcommandsInfo) β subcommands info
(Map<string, Command> | this) Subcommand map or this command
Copy settings that are useful to have in common across parent and its subcommands.
π Note: This method is used internally via
commandso subcommands can inherit parent settings.
parent(Command) β the parent command to copy settings from
(this) this command
Create a new unattached argument.
createArgument(info: ArgumentInfo | ArgumentSyntax): ArgumentcreateArgument(info: ArgumentSyntax, data?: ArgumentData | null | undefined): Argument
info(ArgumentInfo|ArgumentSyntax) β argument info or syntaxdata(ArgumentData) β additional argument info
(Argument) New argument instance
Create a new unattached command.
createCommand(info?: CommandInfo | string | null | undefined): CommandcreateCommand(info: string, data?: CommandData | null | undefined): Command
info(CommandInfo|string) β command info or namedata(CommandData) β additional command info
(Command) New command instance
Create a new unattached option.
createOption(info: Flags | OptionInfo): OptioncreateOption(info: VersionOptionInfo): VersionOptioncreateOption(info: Flags, data?: OptionData | null | undefined): Option
info(Flags|OptionInfo|VersionOptionInfo) β option info or flagsdata(OptionData) β additional option info
(Option | VersionOption) New option instance
boolean
Whether the command is the default subcommand of its parent.
Command | null | undefined
The default command.
Get or set the command done callback.
done(done: Action<any> | null | undefined): thisdone<Opts extends OptionValues = OptionValues, Args extends any[] = any[]>(): Action<Opts, Args>
Opts(OptionValues, optional) β parsed command options with globalsArgs(any[], optional) β parsed command arguments
done(Action<any>|null|undefined) β the callback to fire after the command is ran
(Action<Opts, Args> | this) The command done callback or this command
Emit an event.
event(KronkEvent) β the event to emit
(boolean) true if event has listeners, false otherwise
Emit a parsed option event.
option(Option) β the command option instancevalue(RawOptionValue) β the rawoptionvaluesource(OptionValueSource) β the source of the raw optionvalueflag?(Flags, optional) β the parsedoptionflag
(boolean) true if event has listeners, false otherwise
Display an error message and exit.
info(CommandErrorInfo|KronkError) β info about the error or the error to display
(never) Never, exits erroneously
Add an example for the command.
π Note: This method can be called more than once to add multiple examples.
example(info: ExampleInfo | string): thisexample(info: string, prefix?: string | null | undefined): this
info(ExampleInfo|string) β example info or textprefix(string|null|undefined) β the example text prefix
(this) this command
Get or add examples for the command.
examples(examples: ExamplesData | null | undefined): thisexamples(): ExampleInfo[]
examples(ExamplesData|null|undefined) β example info, example text, or a list of such
(ExampleInfo[] | this) List of examples or this command
Exit the process.
π Note: The exit code (
process.exitCode) is set, butprocess.exitis not called. To change this behavior, override the exit callback usingexiter.
exit(e: CommandError | KronkError): neverexit(e?: null | undefined): undefined
e(CommandError|KronkError|null|undefined) β the error to handle
(never | undefined) Nothing
(KronkError) If e is an unhandled error after calling the command exit callback
Get or set the exit callback.
exiter(exit: Exit | null | undefined): thisexiter(): Exit
exit(Exit|null|undefined) β the callback to fire on process exit
(Exit | this) Command exit callback or this command
Find a command with a name or alias matching ref.
ref(CommandName|List<CommandName>|undefined) β a command name, command alias, or list of such references
(Command | this | undefined) Command with a name or alias matching ref
Find an option with a flag matching flag.
Options known to this command and its (defaultCommand) are searched by
default. Set direction to 0 to only search for options known to the current command.
flag(string|null|undefined) β the option flag to matchdirection(0|null|undefined, optional) β the direction to search for options
(Option | undefined) Option with the long or short flag flag
Get or configure the help subcommand.
helpCommand(help: HelpCommandData | null | undefined): thishelpCommand<T extends Command = Command>(): T | null
T(Command) β help subcommand instance
help(HelpCommandData|null|undefined) β subcommand instance, subcommand info,falseto disable the help subcommand, or any other allowed value to use the default configuration
(T | this | null) Help subcommand or this command
Get or configure the help option.
helpOption(help: HelpOptionData | null | undefined): thishelpOption<T extends Option = Option>(): T | null
T(Option) β help option instance
help(HelpOptionData|null|undefined) β option flags, option instance, option info,falseto disable the help option, or any other allowed value to use the default configuration
(T | this | null) Help option or this command
Get or set the help text utility.
helpUtility(util: Help | null | undefined): thishelpUtility<T extends Help>(): T
T(Help) β help text utility instance
util(Help|null|undefined) β the help text utility
(T | this) Help text utility or this command
Get or set the name of the command.
id(name: CommandName | undefined): thisid(): CommandName
name(CommandName|undefined) β the name of the command
(CommandName | this) The name of this command or this command
Logger instance.
Register an event listener.
T(KronkEvent) β the event being listened for
event(T['id']) β the name of the event being listened forlistener(KronkEventListener<T>) β the event listeneroptions(OnOptions, optional) β event listening options
(undefined) Nothing
Define an option for the command.
option(info: Flags | OptionInfo): thisoption(info: Flags, data?: OptionData | null | undefined): this
info(Flags|OptionInfo) β option flags or infodata(OptionData, optional) β additional argument info
(this) this command
Get or set the strategy to use when merging global and local options.
optionPriority(priority: OptionPriority | null | undefined): thisoptionPriority(): OptionPriority
priority(OptionPriority|null|undefined) β the strategy to use when merging options
(OptionPriority | this) Option merge strategy or this command
Get or set an option value.
optionValue(key: Option['key'], value: unknown, source?: OptionValueSource | null | undefined): thisoptionValue<T>(key: Option['key']): T
T(any) β parsed option value type
key(Option['key']) β option keyvalue(unknown) β the parsed option value to storesource(OptionValueSource|null|undefined) β the source of the original option value
(T | this) Stored option value or this command
Get or set an option value source.
optionValueSource(key: Option['key'], source: OptionValueSource | null | undefined): thisoptionValueSource(key: Option['key']): OptionValueSource | null | undefined
key(Option['key']) β option keysource(OptionValueSource|null|undefined, optional) β the source of the option value
(OptionValueSource | this | null | undefined)
Option value source for key or this command
Get a list of command options or batch define options for the command.
options(infos: List<Flags | OptionInfo>): thisoptions(): Option[]
infos(List<Flags | OptionInfo>) β list of option flags and/or info
(Option[] | this) List of command options or this command
Get a record of local option values.
T(OptionValues) β local option values type
(T) Local option values
Get a record of global and local option values.
π Note: Local options overwrite global options by default. Prioritize global options (i.e.
cmd.optionPriority('global')) to change this behavior.
T(OptionValues) β merged option values type
(T) Merged option values
Command | null | undefined
The parent command.
Parse argv, setting options and invoking commands when defined.
The default expectation is that the arguments are from node and have the application as argv[0] and the script being
run in argv[1], with user parameters after that.
π Note: If the
actionhandler is async,parseAsyncshould be used instead.
argv(List<string>|null|undefined, optional) β list of command-line argumentsoptions(ParseOptions|null|undefined, optional) β options for parsingargv
(Command | this) The command that was run
Asynchronously parse argv, setting options and invoking commands when defined.
Otherwise the same as parse.
π Note: If the
actionhandler is async, this method should be used instead ofparse.
Information about the current process.
Get a snapshot of this command.
(CommandSnapshot) Command snapshot object
Get or set the command summary.
summary(summary: string | null | undefined): thissummary(): string | null
summary(string|null|undefined) β the command summary
(string | this | null) Summary of this command or this command
Get the command as a human-readable string.
(string) String representation of this argument
The strategy for handling unknown command-line arguments.
Get or set the strategy for handling unknown command-line arguments.
unknowns(strategy: UnknownStrategy | null | undefined): thisunknowns(): UnknownStrategy
strategy(UnknownStrategy|null|undefined) β the strategy for handling unknown command-line arguments
(UnknownStrategy | this)
Unknown command-line argument strategy or this command
Get or set the command usage description.
usage(usage: UsageData | null | undefined): thisusage(): UsageInfo
usage(UsageData|null|undefined) β command usage data
(UsageInfo | this) Command usage info or this command
Get or set the command version.
π Note: When setting the command version, this method auto-registers the version option with the flags
-v | --version. No cleanup is performed when this method is called with different flags (i.e.infoas a string orinfo.flags).
version(version: VersionData | null | undefined): thisversion<T extends string = string>(): T | null
T(string, optional) β command version type
version(VersionData|null|undefined) β command version, version option instance, or version option info
(T | this | null) Command version or this command
A command error (class).
info(CommandErrorInfo) β info about the error
Command | null
The command where the error originated.
Get a snapshot of the error.
(CommandErrorSnapshot) Error snapshot object
Help text utility (class).
options(HelpTextOptions|null|undefined) β options for formating help text
Generate help text for a command.
cmd(Command) β the command to generate help text for
(string) Formatted help text
A help text candidate (abstract class).
info(HelpableInfo) β candidate info
Get or set the candidate description.
The description can be long or short form text, or a URL pointing to more information about the candidate.
description(description: URL | string | null | undefined): thisdescription(): string
description(URL|string) β candidate description text or a URL pointing to more info
(string | this) Candidate description or this candidate
Helpable#hidden
boolean
Whether the candidate should not be displayed in help text.
Helpable#hide([hidden])
Remove the candidate from the help text.
hidden(boolean|null|undefined) β whether the candidate should be hidden in help text- default:
true
- default:
(this) this candidate
A command-line error (class).
Error
constructor(info: KronkErrorInfo | string)constructor(info: string, id?: EmptyString | KronkErrorId | null | undefined, code?: ExitCode | null | undefined)
info(KronkErrorInfo|string) β error info or human-readable description of the errorid(EmptyString|KronkErrorId) β unique id representing the errorcode(ExitCode) β suggested exit code to use withprocess.exit
string[]
Additional lines to be logged with the error.
KronkErrorCause | null | undefined
Info about the cause of the error.
number
The suggested exit code to use with process.exit.
Unique id representing the error.
Get the error as a JSON object.
(KronkErrorJson) JSON representation of this error
Get the error as a human-readable string.
(string) String representation of this error
An event (class).
id(KronkEventName) β the unique id representing the event
The unique id representing the event.
Get the event as a human-readable string.
(string) String representation of this event
A command option (class).
constructor(info: Flags | OptionInfo)constructor(info: Flags, data?: OptionData | null | undefined)
info(Flags|OptionInfo) β option flags or infodata(OptionData) β additional option info
boolean
Whether the option is a boolean option. Boolean options are options that do not take any option-arguments.
Get or set option names that conflict with the option.
conflicts(conflicts: List<string> | string | null | undefined): thisconflicts(): Set<string>
conflicts(List<string>|string|null|undefined) β an option name, or list of option names, that conflict with the option
(Set<string> | this) List of conflicting option names or this option
Get or set the environment variables to check for the value of the option.
env(env: List<string> | string | null | undefined): thisenv(): Set<string>
env(List<string>|string|null|undefined) β the name of the environment variable to check, or a list of names, in order of priority, to check
(string | this) Environment variable names or this option
The event name for the option.
The normalized option flags string.
string
The option id.
Get or set implied option values.
Implied option values are values that are set on other options
when this option is passed, but the implied option is not.
Lone keys (string implies) imply true, i.e. { [implies]: true }.
The option-argument parser will be called for implied values
that are strings and string arrays.
implies(implies: OptionValues | string | null | undefined): thisimplies<T extends OptionValues>(): T
T(OptionValues) β implied option values
implies(OptionValues|string|null|undefined) β the key of an implied option, or a map where each key is an implied option key and each value is the value to use when the option is set but the implied option is not
(T | this) Map of implied option values or this option
string
The option id in a format that can be used an object property key.
string | null
The long flag for the option.
If null, the short flag will be a non-empty string.
Specify if the option is mandatory.
Mandatory options must have a value after parsing, which usually means the option must be specified on the command line.
π Note: This method is a no-op if mandatory option syntax was used when defining option flags (i.e.
new Option('--token <!>')).
mandatory(boolean|null|undefined, optional) β whether the option must have a value after parsing
(this) this option
boolean
Whether the option must have a value after parsing.
boolean
Whether a value is optional when the option is specified.
Get or set the preset to use when the option is specified without an argument.
The option-argument parser will be called.
preset(preset: string | null | undefined): thispreset<T extends string>(): T | null
T(string) β option-argument preset
preset(string|null|undefined) β the option-argument preset
(T | this | null) The option-argument preset or this option
string | null
The short flag for the option.
If null, the long flag will be a non-empty string.
Get the option as a human-readable string.
(string) String representation of this option
A parsed option event (class).
π Note: For options where the
sourceis'implied', thevaluemay not be a raw option value.
constructor(option: T, value: RawOptionValue, source: OptionValueSource, flag?: Flags | null | undefined)constructor(option: T, value: unknown, source: optionValueSource.implied, flag?: Flags | null | undefined)
T(Option, optional) β Parsed command option
option(T) β the command option instancevalue(RawOptionValue) β theoptionvaluesource(OptionValueSource) β the source of the optionvalueflag(Flags, optional) β the parsedoptionflag
Flags | null | undefined
The parsed command option flag.
The option event name.
T
The command option instance.
The source of the raw option value.
The raw option value.
A parse candidate (abstract class).
Parse candidates are the parseable components of commands (e.g. arguments and options).
info(ParseableInfo) β candidate info
Get or set candidate choices.
choices(choices: List<string> | null | undefined): thischoices<T extends string>(): Set<T>
T(string) β candidate choice
choices(List<string>|null|undefined) β list of allowed candidate choices
(Set<T> | this) List of candidate choices or this candidate
Get or set the default value configuration.
default(info: DefaultInfo | null | undefined): thisdefault<T>(): DefaultInfo<T> | undefined
T(any) β default value
info(DefaultInfo) β default value info
(DefaultInfo<T> | this | undefined)
Default value info or this candidate
string
The unique id for the candidate (abstract).
Get or set the handler used to parse candidate-arguments.
parser(parser: ParseArg<any, any> | null | undefined): thisparser<T, Value extends RawParseValue = RawParseValue>(): ParseArg<T, Value>
T(any) β parse resultValue(RawParseValue, optional) β the argument or arguments to parse
parser(ParseArg<any, any>|null|undefined) β the candidate-argument parser
(ParseArg<T, Value> | this) The candidate-argument parser or this candidate
boolean
Whether the candidate is required.
Required arguments must have a value after parsing. Required options must have a value supplied when the option is specified.
Get the candidate as a human-readable string (abstract).
(string) String representation of this candidate
boolean
Whether the candidate can be specified multiple times.
A command version option (class).
info(Version|VersionOptionInfo) β command version or option info
string
The version of the command.
Default error ids (const enum).
const enum keid {
argument_after_variadic = 'kronk/argument-after-variadic',
conflicting_option = 'kronk/conflicting-option',
duplicate_option = 'kronk/duplicate-option',
duplicate_subcommand = 'kronk/duplicate-subcommand',
error = 'kronk/error',
excess_arguments = 'kronk/excess-arguments',
invalid_argument = 'kronk/invalid-argument',
invalid_argument_syntax = 'kronk/invalid-argument-syntax',
invalid_flags = 'kronk/invalid-flags',
invalid_subcommand_name = 'kronk/invalid-subcommand-name',
missing_argument = 'kronk/missing-argument',
missing_mandatory_option = 'kronk/missing-mandatory-option',
no_flags = 'kronk/no-flags',
unknown_implied_option = 'kronk/unknown-implied-option',
unknown_option = 'kronk/unknown-option'
}Default option value sources (const enum).
const enum optionValueSource {
cli = 'cli',
config = 'config',
default = 'default',
env = 'env',
implied = 'implied'
}This package is fully typed with TypeScript.
The callback to fire when a command is executed (TypeScript type).
type Action<
Opts extends OptionValues = OptionValues,
Args extends any[] = any[]
> = (
this: Command,
opts: Opts,
...args: Args
) => Awaitable<null | undefined | void>Opts(OptionValues, optional) β command optionsArgs(any[], optional) β command arguments
this(Command) β the command or subcommand being executedoptions(Opts) β parsed command options...args(Args) β parsed command arguments
(Awaitable<null | undefined | void>) Nothing
Data transfer object for command-arguments (TypeScript interface).
Data used to create command-arguments (TypeScript interface).
syntax(ArgumentSyntax|string) β argument syntax
Command-argument metadata (TypeScript interface).
id(string) β argument syntax idrequired(boolean) β whether required syntax was used when defining the argumentvariadic(boolean) β whether variadic syntax was used when defining the argument
Registry of strings used to define command and option arguments (TypeScript interface).
interface ArgumentSyntaxMap {/* see code */}When developing extensions that use additional syntaxes, augment ArgumentSyntaxMap to register custom syntaxes:
declare module '@flex-development/kronk' {
interface ArgumentSyntaxMap {
requiredMaybe: `<${string}?>`
}
}Union of registered syntaxes used to define command and option arguments (TypeScript type).
To register custom syntaxes, augment ArgumentSyntaxMap.
They will be added to this union automatically.
type ArgumentSyntax = ArgumentSyntaxMap[keyof ArgumentSyntaxMap]Union of types used to create command arguments (TypeScript type).
type ArgumentsData =
| ArgumentInfo
| List<ArgumentInfo | ArgumentSyntax>
| stringRegistry of command-line argument sources (TypeScript interface).
interface ArgvSourceMap {/* see code */}When developing extensions that use additional sources, augment ArgvSourceMap to register custom sources:
declare module '@flex-development/kronk' {
interface ArgvSourceMap {
electron: 'electron'
}
}Union of registered command-line argument sources (TypeScript type).
To register custom sources, augment ArgvSourceMap.
They will be added to this union automatically.
type ArgvSource = ArgvSourceMap[keyof ArgvSourceMap]Create a union of T and T as a promise (TypeScript type).
T(any, optional)- the value
type Awaitable<T = unknown> = Promise<T> | TData transfer object for commands (TypeScript interface).
action?(Action<any>, optional) β callback to fire when the command is executedaliases?(List<string>|string, optional) β aliases for the commandarguments?(List<string>, optional) β arguments for the commanddefault?(boolean, optional) β whether this is the default commanddone?(Action<any>, optional) β callback to fire after the commandactionis executedexit?(Exit, optional) β callback to fire when the process is exitedhelpCommand?(HelpCommandData, optional) β customize the help subcommand, or disable it (false)π Note: to configure the help subcommand for
helpCommand, aCommandinstance must be used.helpCommand.helpCommandis set tofalsewhenhelpCommandis not aCommand.- default:
{ description: 'show help', name: 'help' }
- default:
helpOption?(HelpOptionData, optional) β customize the help option, or disable it (false)- default:
{ description: 'show help', flags: '-h | --help' }
- default:
helpUtility?(Help, optional) β the help text utility to use when generating help text- default:
new Help()
- default:
optionPriority?(OptionPriority, optional) β the strategy to use when merging global and local options- default:
'local'
- default:
options?(OptionsData, optional) β options for the commandparent?(Command, optional) β the parent commandsubcommands?(SubcommandsData, optional) β subcommands for the commandsummary?(string, optional) β a summary of the commandunknown?(UnknownStrategy, optional) β the strategy to use for handling unknown command-line arguments- default:
false
- default:
usage?(UsageData, optional) β an object describing how the command is used- default:
{ arguments: null, options: '[options]', subcommand: '[command]' }
- default:
version?(VersionData, optional) β command version configuration
Data used to create command errors (TypeScript interface).
command?(Command, optional) β the command where the error originatedid(KronkErrorId) β unique id representing the error
Command error overview (TypeScript interface).
command(CommandSnapshot|null) β an overview of the failed command
Data used to create commands (TypeScript interface).
name?(CommandName, optional) β the name of the command
Command metadata (TypeScript interface).
aliases(Set<string>) β list of command aliasesarguments(Argument[]) β list of command argumentsexamples(ExampleInfo[]) β list of command exampleshelpCommand(Command|null|undefined) β the help subcommandhelpOption(Option|null|undefined) β the help optionhelpUtility(Help) β the help text utility to use when generating help textoptions(Map<string, Option>) β map, where each key is a long or short flag and each value is the command option instance registered for that flagparent?(null|undefined) β the parent commandsubcommands(Map<string, Command>) β map, where each key is the name of a subcommand each value is a subcommandversion(VersionOption|null|undefined) β the version option
The name of a command (TypeScript type).
Parent commands do not need to have a name, but all subcommands must have a name. Valid command names are non-empty strings.
type CommandName = string | nullObject representing a command overview (TypeScript interface).
ancestors(CommandName[]) β list of ancestor command namesargs(string[]) β list of parsed command argumentsargv(string[]) β list of raw command argumentsname(CommandName) β the name of the commandoptionValueSources(OptionValueSources) β record, where each key is an option key and each value is the source of the parsed option valueopts(OptionValues) β parsed command optionsoptsWithGlobals(OptionValues) β parsed command options (with globals)
Data used to configure the default value of a command argument or option (TypeScript interface).
T(any, optional) β default value type
description?(URL | string, optional) β description of the default valuevalue?(T, optional) β the default value- default:
undefined
- default:
An empty string (TypeScript type).
type EmptyString = ''Command example info (TypeScript interface).
prefix?(string, optional) β the example text prefixtext(string) β the example text
Union of types used to configure command examples (TypeScript type).
type ExamplesData = ExampleInfo | List<ExampleInfo | string> | stringUnion of exit status code types (TypeScript type).
type ExitCode = number | stringTerminate the process synchronously with an exit status of code (TypeScript type).
If code is omitted, exit uses either the 'success' code 0
or the value of process.exitCode if it has been set.
type ExitProcess = (code?: ExitCode | null | undefined) => undefinedcode?(ExitCode, optional) β exit status code
(undefined) Nothing
The callback to fire when the process is exited (TypeScript type).
type Exit = (
this: Command,
e?: CommandError | KronkError | null | undefined
) => undefinedthis(Command) β the current command or subcommand being executede?(CommandError|KronkError, optional) β the error to handle (if any)
(undefined) Nothing
A string comprised of option flags (TypeScript type).
The flags string can contain at most 2 flags, typically one long flag and one short or shortish (e.g. --ws) flag.
Flags are separated by commas (,), pipes (|), or spaces.
A short flag is a hyphen β specifically HYPHEN-MINUS U+002D β followed by one case-insensitive alphanumeric
character.
The letters themselves have conventional meanings and are worth following, if possible.
A long flag starts with two hyphens followed by one or more case-insensitive alphanumeric characters. Using two hyphens
prevents long flags from being confused for grouped short options.
Hyphens and full stops (FULL STOP U+002E) can be used to separate words, as well as camelCase format.
Option-arguments are marked as required using empty angle brackets (<>) or by wrapping an argument id in angle
brackets: <id>.
Optional arguments use empty square brackets ([]) or have their id wrapped in square brackets: [id].
Variadic arguments are specified with an ellipsis wrapped in brackets (e.g. <...>, [...]) or by appending the
ellipsis to the end of the argument id (<value...>, [value...]). Option-arguments can also be marked as mandatory by
appending an exclamation mark to the end of the argument id: (<!>, <id!>, <value!...>).
type Flags = stringUnion of types used to configure the help subcommand (TypeScript type).
The help subcommand can be customized with
a Command instance, subcommand info object, or a subcommand name.
It can also be disabled (false).
type HelpCommandData = Command | SubcommandInfo | string | falseUnion of types used to configure the help option (TypeScript type).
The command help option can be customized with
an Option instance, flags, or an info object.
It can also be disabled (false).
type HelpOptionData = Flags | Option | OptionInfo | falseOptions for formating help text (TypeScript interface).
columns?(number, optional) β the maximum number of columns to output- default:
80
- default:
Data used to create help text candidates (TypeScript interface).
description?(URL | string, optional) β a description of the candidate. the description can be long or short form text, or a URL pointing to more information about the candidatehidden?(boolean, optional) β whether the candidate should not be displayed in help text
Info about the cause of an error (TypeScript interface).
π Note:
Symbol.hasInstanceandSymbol.unscopablesare used to identify arrays and functions.
interface KronkErrorCause {
[Symbol.hasInstance]?: never
[Symbol.unscopables]?: never
[key: string]: any
}Union of registered error ids (TypeScript type).
To register custom error ids, augment KronkErrorMap.
They will be added to this union automatically.
type KronkErrorId = `kronk/${keyof KronkErrorMap}`Data used to create errors (TypeScript interface).
additional?(string | string[], optional) β additional lines to be logged with the errorcause?(KronkErrorCause, optional) β info about the cause of the errorcode?(ExitCode, optional) β the suggested exit code to use withprocess.exit- default:
1
- default:
id?(EmptyString|KronkErrorId, optional) β the unique id representing the error- default:
'kronk/error'
- default:
reason(string) β a human-readable description of the error
JSON representation of an error (TypeScript interface).
additional(string[]) β additional lines to be logged with the errorcause?(KronkErrorCause, optional) β info about the cause of the errorcode(number) β the suggested exit code to use withprocess.exitid(KronkErrorId) β the unique id representing the errormessage(string) β the human-readable description of the errorstack?(string, optional) β stack trace
Registry of errors (TypeScript interface).
Each key is the suffix of an error id and each value is a KronkError.
interface KronkErrorMap {/* see code */}When developing extensions that use additional errors, augment KronkErrorMap to register custom errors:
declare module '@flex-development/kronk' {
interface KronkErrorMap {
'action-error': CustomCommandError
'parse-error': CustomKronkError
}
}Handle an event (TypeScript type).
type KronkEventListener<T extends KronkEvent = KronkEvent> = (
event: T
) => undefinedT(KronkEvent, optional) β the emitted event
event(T) β the emitted event
(undefined) Nothing
Registry of event names (TypeScript interface).
interface KronkEventNameMap extends OptionEventNameMap {/* see code */}When developing extensions that use additional events, augment KronkEventNameMap to register custom event names:
declare module '@flex-development/kronk' {
interface KronkEventNameMap {
custom: 'command:custom'
}
}Union of registered event names (TypeScript type).
To register custom event names, augment KronkEventNameMap.
They will be added to this union automatically.
type KronkEventName = KronkEventNameMap[keyof KronkEventNameMap]A list (TypeScript type).
T(any, optional) β list item type
type List<T = unknown> = ReadonlySet<T> | readonly T[]Data transfer object for command options (TypeScript interface).
conflicts?(List<string>|string, optional) β an option name, or list of option names, that conflict with the option.
an error will be displayed if conflicting options are found during parsingenv?(List<string>|string, optional) β the name of the environment variable to check for option value, or a list of names, in order of priority, to checkimplies?(OptionValues|string, optional) β the key of an implied option, or a map where each key is an implied option key and each value is the value to use when the option is set but the implied option is not.
lone keys imply (stringimplies)true, i.e.{ [implies]: true }.
the option-argumentparserwill be called for implied values that are strings and string arraysmandatory?(boolean, optional) β whether the option is mandatory. mandatory options must have a value after parsing, which usually means the option must be specified on the command line- default:
false
- default:
preset?(string, optional) β for boolean and optional options, the preset to use when the option is specified without an option-argument.π note: the option-argument
parserwill be called.snakecase?(boolean, optional) β whether to usesnake_caseformat when converting the option id to an object property key
Handle a parsed command option event (TypeScript type).
type OptionEventListener<T extends Option = Option> = (
event: OptionEvent<T>
) => undefinedT(Option, optional) β the parsed command option
event(OptionEvent<T>) β the emitted parsed option event
(undefined) Nothing
Registry of option event names (TypeScript interface).
interface OptionEventNameMap {/* see code */}When developing extensions that use additional events, augment OptionEventNameMap to register custom event names:
declare module '@flex-development/kronk' {
interface OptionEventNameMap {
custom: `option.${string}`
}
}Union of registered option event names (TypeScript type).
To register custom event names, augment OptionEventNameMap.
They will be added to this union automatically.
type OptionEventName = OptionEventNameMap[keyof OptionEventNameMap]Data used to create command options (TypeScript interface).
flags(Flags) β option flags
Command option metadata (TypeScript interface).
long(string|null|undefined) β long flagoptional(boolean) β whether a value is optional when the option is specifiedrequired(boolean) β whether a value must be supplied when the option is specifiedshort(string|null|undefined) β short (or shortish, e.g.--ws) flagπ note: if
nullorundefined, thelongflag will be a non-empty stringvariadic(boolean) β whether the option can be specified multiple times
Union of strategies used when merging global and local options (TypeScript type).
global: global options overwrite local optionslocal: local options overwrite global options
type OptionPriority = 'global' | 'local'Registry of option value sources (TypeScript interface).
interface OptionValueSourceMap {/* see code */}When developing extensions that use additional sources, augment OptionValueSourceMap to register custom sources:
declare module '@flex-development/kronk' {
interface OptionValueSourceMap {
builder: 'builder'
}
}Union of registered option value sources (TypeScript type).
To register custom sources, augment OptionValueSourceMap.
They will be added to this union automatically.
type OptionValueSource = OptionValueSourceMap[keyof OptionValueSourceMap]Record, where each key is an option key (Option.key)
and each value is an OptionValueSource (TypeScript type).
type OptionValueSources = {
[x: Option['key']]: OptionValueSource | null | undefined
}Record, where each key is an option key (Option.key)
and each value is a parsed option value (TypeScript type).
T(any, optional) β parsed option value type
type OptionValues<T = any> = { [x: Option['key']]: T }Union of types used to create command options (TypeScript type).
type OptionsData =
| Flags
| List<Flags | OptionInfo>
| OptionInfoParse a command or option argument value (TypeScript type).
type ParseArg<T = any, Value extends RawParseValue = RawParseValue> = (
this: void,
value: Value,
previous: T | undefined
) => TT(any, optional) β parse resultValue(RawParseValue, optional) β the argument or arguments to parse
this(Command) β the current command or subcommand being executedvalue(Value) β the raw argument or arguments to parseprevious(T|undefined) β the default argument value
(T) Parse result
Options for parsing command-line arguments (TypeScript interface).
from?(ArgvSource, optional) β the source of the command line arguments
The result of parsing unknown arguments (TypeScript interface).
operands(string[]) β list of arguments that are operands (not options or values)unknown(string[]) β list containing the first unknown option and any remaining unknown arguments
Data used to create parse candidates (TypeScript interface).
choices?(List<string>, optional) β list of option choicesdefault?(DefaultInfo, optional) β default value configurationπ note: the option-argument
parserwill not be called.parser?(ParseArg<any, string> | ParseArg<any, string[]>, optional) β handler used to parse arguments. the handler receives two parameters, the raw, unparsed argument (or arguments for variadic candidates), and the default value for the argument. it should return the new value for the argument
Parse candidate metadata (TypeScript interface).
required?(boolean, optional) β whether required syntax was used when defining the candidatevariadic?(boolean, optional) β whether variadic syntax was used when defining the candidate.
Information about the current user environment (TypeScript interface).
interface ProcessEnv {
[key: string]: string | undefined
}Information about the current process (TypeScript interface).
argv(string[]) β list of command-line arguments passed when the process was launchedenv(ProcessEnv) β object containing information about the user environmentexit(ExitProcess) β terminate the process synchronously with an exit status ofcodeexitCode?(ExitCode, optional) β the exit code to use when the process exits gracefully, or is exited viaexitwithout specifying a codestderr(WriteStream) β the writeable stream for standard error outputstdout(WriteStream) β the writeable stream for standard output
Union of raw option value types (TypeScript type).
type RawOptionValue = boolean | string | string[] | nullThe argument or arguments passed to an argument parser (TypeScript type).
type RawParseValue = string | readonly string[]Data used to create subcommands (TypeScript interface).
name(string) β the name of the subcommand
Union of types used to create subcommands (TypeScript type).
type SubcommandsData = SubcommandInfo | SubcommandsInfoRecord, where each key is the name of a subcommand and each value is an info object.
type SubcommandsInfo = { [subcommand: string]: CommandInfo }Union of values used to alter handling of unknown command-line arguments (TypeScript type).
'arguments': allow unknown command-arguments only'options': allow unknown options onlyfalse: disallow unknown command-arguments and optionstrue: allow unknown command-arguments and options
type UnknownStrategy = 'arguments' | 'options' | booleanAn object describing command usage (TypeScript interface).
arguments?(string, optional) β command arguments descriptorπ note: displayed in auto-generated help text only when a command has at least one visible argument
- default: generated using visible command arguments
options?(string, optional) β command options descriptorπ note: displayed in auto-generated help text only when a command has at least one visible option
subcommand?(string, optional) β subcommands descriptorπ note: displayed in auto-generated help text only when a command has at least one visible subcommand
- default:
'[command]'
- default:
Command usage info (TypeScript interface).
options(string) β command options descriptorπ note: displayed in auto-generated help text only when a command has at least one visible option
subcommand(string) β subcommands descriptorπ note: displayed in auto-generated help text only when a command has at least one visible subcommand
Union of types used to configure the version of a Command (TypeScript type).
type VersionData = Version | VersionOption | VersionOptionInfoData used to create command version options (i.e. -v | --version) (TypeScript interface).
flags?(Flags, optional) β option flags- default:
'-v | --version'
- default:
version(Version) β the command version
Union of command version types (TypeScript type).
type Version = import('semver').SemVer | stringSee CONTRIBUTING.md.
This project has a code of conduct. By interacting with this repository, organization, or community you agree to abide by its terms.
