Skip to content

FlagBuilder ​

Immutable flag schema builder.

The type parameter C is a phantom that tracks the value type and presence through the fluent chain. Each modifier returns a new builder — the original is never mutated.

Signatures ​

ts
class FlagBuilder<C extends FlagConfig> {}

Members ​

Constructors ​

constructor ​

Create a flag builder from a pre-built schema descriptor.

ts
constructor(schema: FlagSchema);

Methods ​

complete ​

Suggest flag values from a static list or compute them at completion time. Static suggestions are embedded in the shell script and do not constrain validation.

The callback runs without the command action, middleware, prompts, or config discovery. Return complete values; DreamCLI filters by prefix. Candidates containing control characters are omitted.

ts
complete(candidates: CompletionHandler | readonly string[]): FlagBuilder<WithoutElementEligibility<C>>;

default ​

Provide a default value. The flag becomes "always present" — handlers will never see undefined.

The generic constraint V extends C['valueType'] ensures the default matches the flag's declared type.

ts
default<V extends C["valueType"]>(value: V, options?: DefaultValueOptions): FlagBuilder<WithPresence<C, "defaulted">>;

required ​

Mark the flag as required. If not resolved from any source the framework will emit a ValidationError before the action handler runs.

ts
required(): FlagBuilder<WithPresence<C, "required">>;

sensitive ​

Mark this input's values as sensitive.

Sensitive defaults are omitted from definition and input JSON Schemas and from automatic help text. A custom default description remains safe to show.

ts
sensitive(value?: boolean): FlagBuilder<WithoutElementEligibility<C>>;

alias ​

Add a short or long alias (e.g. 'f' for --force, 'verbose' as an alternative long name).

ts
alias(name: string, options?: { hidden?: boolean; }): FlagBuilder<WithoutElementEligibility<C>>;

env ​

Bind to an environment variable (resolved in v0.2+).

The env value is read after CLI and stdin, and before config, the prompt, and the default: CLI → stdin → env → config → prompt → default.

Under a CLI-wide namespace (CLIBuilder.envPrefix()) the name is relative: .env('TOKEN') in cli('foo').envPrefix() reads FOO_TOKEN. Pass { absolute: true } to read the name exactly as written.

Bind to an indexed family of environment variables, read as one env source.

The count variable owns indices 0..count-1; {index} in each template expands to the zero-based index. An unset count means the env source supplied nothing, so resolution continues to config, the prompt, and the default. A set count claims the flag: 0 resolves an empty list, and a malformed count or a missing member is an error, never a fallback.

A value family reads a list of strings, so it suits flag.array() (each entry decoded by the element) and flag.custom() (handed the whole list). A fields family reads a list of records, one variable per field, so it suits flag.array(flag.custom(...)) and flag.custom().

Under a CLI-wide namespace the count and every template are relative, the same as a single name; { absolute: true } reads them as written.

Bind to an environment variable derived from this input's registered name (api-token and apiToken → API_TOKEN), relative to the CLI namespace unless { absolute: true }.

ts
env(varName: string, options?: EnvOptions): FlagBuilder<WithoutElementEligibility<C>>;
env(binding: IndexedEnvBinding, options?: EnvOptions): FlagBuilder<WithoutElementEligibility<C>>;
env(options?: EnvOptions): FlagBuilder<WithoutElementEligibility<C>>;

stdin ​

Let this flag read its value from piped stdin.

An explicit --<name> - is CLI-sourced with bytes from stdin and keeps CLI precedence. An absent flag takes the stdin fallback stage, which sits between CLI and env, so a flag set in the environment still reads stdin and stdin wins. The whole buffer becomes the value, byte for byte for a string flag; every other kind drops the single line terminator a pipe appends before decoding, and { trim: true } drops it for a string flag too.

A collection reads the buffer as elements instead: --tag - splices what stdin decodes into the position the - occupies, so --tag before --tag - --tag after over 'a\nb\n' resolves to ['before', 'a', 'b', 'after']. .split({ stdin }) sets the decoding. Each - stands for the whole source, so --tag - --tag - splices the buffer twice. A - typed beside other occurrences with nothing piped fails with MISSING_STDIN; occurrences of nothing but - fall through to the later sources.

A stdin-enabled flag cannot receive a literal - as its value, since the token names the source.

Available on every flag kind except count. One command may declare a single exclusive stdin consumer; pass { consume: 'broadcast' } on every input that should share the buffer.

ts
stdin(this: FlagBuilder<C & { flagKind: StdinCapableFlagKind; }>, options?: StdinOptions): FlagBuilder<WithoutElementEligibility<C>>;

config ​

Bind to a dotted config path (resolved in v0.2+).

The config value is read after CLI, stdin, and env, and before the prompt and the default: CLI → stdin → env → config → prompt → default.

ts
config(path: string): FlagBuilder<WithoutElementEligibility<C>>;

describe ​

Human-readable description shown in help output.

ts
describe(description: HelpDescription): FlagBuilder<WithoutElementEligibility<C>>;

group ​

Place this flag in a named options section in command help.

ts
group(name: string): FlagBuilder<WithoutElementEligibility<C>>;

advanced ​

Show this flag in full text help and any help topic for its group.

ts
advanced(): FlagBuilder<WithoutElementEligibility<C>>;

prompt ​

Attach interactive prompt configuration for v0.3+ resolution.

When a flag value is not resolved from CLI, stdin, env, or config, the prompt engine uses this config to interactively ask the user. In non-interactive contexts (CI, piped stdin) prompts are skipped and resolution falls through to default or required validation.

ts
prompt(config: AllowedPromptConfig<C>): FlagBuilder<WithoutElementEligibility<C>>;

deprecated ​

Mark this flag as deprecated.

When used, a warning is emitted to stderr. Help text shows [deprecated] or [deprecated: <reason>].

Does not change the flag's type-level config — it's metadata only.

ts
deprecated(message?: string): FlagBuilder<WithoutElementEligibility<C>>;

propagate ​

Mark this flag as propagated to subcommands.

Propagated flags are automatically available to all descendant commands in a nested command tree. A child command that defines a flag with the same name shadows the propagated parent flag.

Does not change the flag's type-level config — it's metadata only.

ts
propagate(): FlagBuilder<WithoutElementEligibility<C>>;

int ​

Require an integer value. Composes with other numeric constraints.

ts
int(this: FlagBuilder<C & { flagKind: "number"; }>, value?: boolean): FlagBuilder<C>;

min ​

Set an inclusive lower bound. Composes with other numeric constraints; a later call overrides an earlier min (including one from the options object).

ts
min(this: FlagBuilder<C & { flagKind: "number"; }>, value: number): FlagBuilder<C>;

max ​

Set an inclusive upper bound. Composes with other numeric constraints; a later call overrides an earlier max.

ts
max(this: FlagBuilder<C & { flagKind: "number"; }>, value: number): FlagBuilder<C>;

finite ​

Require (or, with false, allow) a finite value. Finiteness is enforced by default, so this is mainly used as .finite(false) to re-allow Infinity / -Infinity.

ts
finite(this: FlagBuilder<C & { flagKind: "number"; }>, allow?: boolean): FlagBuilder<C>;

nonEmpty ​

Reject empty strings. Composes with other string constraints.

ts
nonEmpty(this: FlagBuilder<C & { flagKind: "string"; }>, value?: boolean): FlagBuilder<C>;

minLength ​

Set an inclusive minimum length (UTF-16 code units). Composes with other string constraints; a later call overrides an earlier minLength.

ts
minLength(this: FlagBuilder<C & { flagKind: "string"; }>, value: number): FlagBuilder<C>;

maxLength ​

Set an inclusive maximum length (UTF-16 code units). Composes with other string constraints; a later call overrides an earlier maxLength.

ts
maxLength(this: FlagBuilder<C & { flagKind: "string"; }>, value: number): FlagBuilder<C>;

pattern ​

Require the value to match a regular expression. Anchor with ^/$ for full-string matching. Composes with other string constraints.

ts
pattern(this: FlagBuilder<C & { flagKind: "string"; }>, value: RegExp): FlagBuilder<C>;

separator ​

Split each CLI occurrence on a separator before element coercion, so --tag a,b --tag c resolves to ['a', 'b', 'c']. Elements are coerced (and rejected) individually with the element schema's own error format.

The separator is the CLI policy alone. Env values split on ',' and the stdin buffer on line terminators unless .split() says otherwise.

ts
separator(this: FlagBuilder<C & { flagKind: "array" | "keyValue"; }>, value: string): FlagBuilder<C>;

split ​

Set how each source decodes into elements.

CLI tokens accept 'whole' and a delimiter; env values also accept 'json'; the stdin buffer accepts every format, including 'lines'. The strings 'whole', 'lines', and 'json' name their format, and every other string is the delimiter to split on. A source left out keeps what it already had, or its default: whole CLI tokens (or the .separator() delimiter), comma-delimited env values, line-delimited stdin. A config value is a native array or object, and a config string decodes under the env policy. For stdin, 'whole' passes the complete buffer to a string element, including its final line terminator.

ts
split(this: FlagBuilder<C & { flagKind: "array" | "keyValue"; }>, options: SplitOptions): FlagBuilder<C>;

duplicateKeys ​

Set how a repeated key combines.

Applies to repeated CLI occurrences, delimited env pairs, and spliced stdin reads in the same occurrence order. JSON decoding does not preserve repeated object member names, so it cannot reliably expose them here.

ts
duplicateKeys(this: FlagBuilder<C & { flagKind: "keyValue"; }>, policy: DuplicateKeys): FlagBuilder<C>;

standard ​

Validate the resolved value with a Standard Schema v1 validator.

On a scalar builder the validator sees each value; on a collection builder it sees the completed array or record, after every element passed its own validator. flag.array(flag.string().standard(s)) validates elements, flag.array(flag.string()).standard(s) validates the array.

ts
standard(schema: StandardSchemaV1): FlagBuilder<C>;

unique ​

Deduplicate the resolved array, preserving first-seen order. Applied after all sources resolve, using SameValueZero semantics (like Set).

ts
unique(this: FlagBuilder<C & { flagKind: "array"; }>, value?: boolean): FlagBuilder<C>;

negatable ​

Accept a negated spelling (--no-<name>) that sets the flag to false.

Both spellings are ONE logical flag: the last CLI occurrence wins across them, and they share the duplicate policy. The negated spelling is presence-only — --no-<name>=true is rejected. Help renders the flag as --[no-]<name> (or lists a custom alias); env/config/prompt/default resolution is unaffected.

ts
negatable(this: FlagBuilder<C & { flagKind: "boolean"; }>, options?: { alias?: string; hidden?: boolean; }): FlagBuilder<WithoutElementEligibility<C>>;

duplicates ​

Set how repeated CLI occurrences of this flag combine.

Counted per logical flag — aliases and the negated spelling all count toward the same flag. CLI tokens only: env/config/prompt/default resolution keeps its precedence semantics. Not available on array, count, or keyValue flags, which inherently accumulate.

ts
duplicates(this: FlagBuilder<C & { flagKind: "boolean" | "string" | "number" | "enum" | "custom"; }>, policy: DuplicatePolicy): FlagBuilder<WithoutElementEligibility<C>>;

Examples ​

ts
const port = flag.number().default(8080);
type Port = InferFlag<typeof port>; // number

const region = flag.enum(['us', 'eu', 'ap']);
type Region = InferFlag<typeof region>; // 'us' | 'eu' | 'ap' | undefined

See Also ​

Released under the MIT License.