Interactive command-line prompt system providing text input, confirmation, selection, and multi-selection prompts with comprehensive cancellation handling and type-safe return values.
Main prompt interface supporting multiple prompt types with configurable options and type-safe return values.
/**
* Display interactive prompt to user
* @param message - Prompt message to display
* @param opts - Prompt configuration options
* @returns Promise resolving to user input with inferred type
*/
async function prompt<T extends PromptOptions = TextPromptOptions>(
message: string,
opts?: PromptOptions
): Promise<inferPromptReturnType<T> | inferPromptCancelReturnType<T>>;Usage Examples:
import { consola } from "consola";
// Basic text input
const name = await consola.prompt("What's your name?");
// Returns: string
// Confirmation prompt
const confirmed = await consola.prompt("Continue?", { type: "confirm" });
// Returns: boolean
// Selection prompt
const choice = await consola.prompt("Choose option:", {
type: "select",
options: ["Option A", "Option B", "Option C"]
});
// Returns: "Option A" | "Option B" | "Option C"Integrated prompt method available on all Consola instances.
interface ConsolaInstance {
/**
* Display interactive prompt using instance configuration
* @param message - Prompt message to display
* @param opts - Prompt configuration options
* @returns Promise resolving to user input
*/
prompt<T extends PromptOptions>(
message: string,
opts?: T
): Promise<inferPromptReturnType<T>>;
}Usage Examples:
import { consola } from "consola";
// Instance method usage
const email = await consola.prompt("Enter email:", {
type: "text",
placeholder: "user@example.com"
});
// Tagged logger prompts
const dbLogger = consola.withTag("database");
const dbName = await dbLogger.prompt("Database name:");
// Prompt includes logger context/formattingSimple text input prompts with default values, placeholders, and initial text.
interface TextPromptOptions extends PromptCommonOptions {
/** Prompt type specification */
type?: "text";
/** Default value if user provides no input */
default?: string;
/** Placeholder text displayed in prompt */
placeholder?: string;
/** Initial text value in input field */
initial?: string;
}Usage Examples:
// Basic text prompt
const username = await consola.prompt("Username:");
// Text prompt with default
const port = await consola.prompt("Port number:", {
type: "text",
default: "3000"
});
// Text prompt with placeholder and initial value
const apiUrl = await consola.prompt("API URL:", {
type: "text",
placeholder: "https://api.example.com",
initial: "https://"
});Yes/no confirmation prompts with configurable default values.
interface ConfirmPromptOptions extends PromptCommonOptions {
/** Prompt type specification */
type: "confirm";
/** Initial/default confirmation value */
initial?: boolean;
}Usage Examples:
// Basic confirmation
const shouldContinue = await consola.prompt("Continue with deployment?", {
type: "confirm"
});
// Confirmation with default true
const createBackup = await consola.prompt("Create backup first?", {
type: "confirm",
initial: true
});
// Confirmation with custom cancel handling
const deleteFiles = await consola.prompt("Delete all files?", {
type: "confirm",
cancel: "reject" // Throw error on cancel
});Single-choice selection from a list of options with string or object format.
interface SelectPromptOptions extends PromptCommonOptions {
/** Prompt type specification */
type: "select";
/** Initial selected value */
initial?: string;
/** Available options for selection */
options: (string | SelectOption)[];
}
interface SelectOption {
/** Display label for the option */
label: string;
/** Value returned when selected */
value: string;
/** Optional hint/description text */
hint?: string;
}Usage Examples:
// Simple string options
const environment = await consola.prompt("Select environment:", {
type: "select",
options: ["development", "staging", "production"]
});
// Object-based options with labels and hints
const deployment = await consola.prompt("Deployment strategy:", {
type: "select",
options: [
{
label: "Blue-Green",
value: "blue-green",
hint: "Zero-downtime deployment"
},
{
label: "Rolling Update",
value: "rolling",
hint: "Gradual instance replacement"
},
{
label: "Recreate",
value: "recreate",
hint: "Stop all, then start new"
}
],
initial: "blue-green"
});Multiple-choice selection allowing users to select multiple options from a list.
interface MultiSelectOptions extends PromptCommonOptions {
/** Prompt type specification */
type: "multiselect";
/** Initially selected values */
initial?: string[];
/** Available options for selection */
options: (string | SelectOption)[];
/** Whether at least one selection is required */
required?: boolean;
}Usage Examples:
// Basic multi-select
const features = await consola.prompt("Select features to enable:", {
type: "multiselect",
options: ["logging", "caching", "monitoring", "metrics"]
});
// Returns: string[]
// Multi-select with object options and requirements
const services = await consola.prompt("Select required services:", {
type: "multiselect",
required: true,
options: [
{ label: "Database", value: "db", hint: "PostgreSQL database" },
{ label: "Redis Cache", value: "redis", hint: "In-memory cache" },
{ label: "Message Queue", value: "mq", hint: "Background job processing" }
],
initial: ["db"] // Pre-select database
});Comprehensive cancellation handling with configurable behaviors for interrupted prompts.
interface PromptCommonOptions {
/**
* Cancellation handling strategy
* - "default": Return default/initial value
* - "undefined": Return undefined
* - "null": Return null
* - "symbol": Return kCancel symbol
* - "reject": Throw ConsolaPromptCancelledError
*/
cancel?: "reject" | "default" | "undefined" | "null" | "symbol";
}
/** Special symbol returned when cancel is set to "symbol" */
export const kCancel: unique symbol;Usage Examples:
import { consola, kCancel } from "consola";
// Reject on cancellation
try {
const name = await consola.prompt("Enter name:", {
cancel: "reject"
});
} catch (error) {
console.log("User cancelled prompt");
}
// Return symbol on cancellation
const result = await consola.prompt("Continue?", {
type: "confirm",
cancel: "symbol"
});
if (result === kCancel) {
console.log("User cancelled");
} else {
console.log("User confirmed:", result);
}
// Use default value on cancellation
const port = await consola.prompt("Port:", {
default: "3000",
cancel: "default"
});
// Returns "3000" if cancelledAutomatic type inference based on prompt options for compile-time type safety.
// Type inference examples
type inferPromptReturnType<T extends PromptOptions> =
T extends TextPromptOptions ? string :
T extends ConfirmPromptOptions ? boolean :
T extends SelectPromptOptions ?
T["options"][number] extends SelectOption ?
T["options"][number]["value"] :
T["options"][number] :
T extends MultiSelectOptions ? T["options"] :
unknown;
type inferPromptCancelReturnType<T extends PromptOptions> =
T extends { cancel: "reject" } ? never :
T extends { cancel: "default" } ? inferPromptReturnType<T> :
T extends { cancel: "undefined" } ? undefined :
T extends { cancel: "null" } ? null :
T extends { cancel: "symbol" } ? typeof kCancel :
inferPromptReturnType<T>; // default behaviorUsage Examples:
// Automatic type inference
const name: string = await consola.prompt("Name:");
const confirmed: boolean = await consola.prompt("OK?", { type: "confirm" });
const choice: "a" | "b" | "c" = await consola.prompt("Pick:", {
type: "select",
options: ["a", "b", "c"]
});
// With cancellation handling
const result: string | typeof kCancel = await consola.prompt("Input:", {
cancel: "symbol"
});Automatic fallback to browser dialog APIs when clack prompts are unavailable.
Usage Examples:
import { consola } from "consola/browser";
// Browser prompts use native dialog APIs
const name = await consola.prompt("Enter name:");
// Uses window.prompt()
const confirmed = await consola.prompt("Continue?", { type: "confirm" });
// Uses window.confirm()
// Multi-select not supported in browser, falls back to text
const selection = await consola.prompt("Select option:", {
type: "select",
options: ["Option A", "Option B"]
});
// Uses window.prompt() with formatted optionstype PromptOptions =
| TextPromptOptions
| ConfirmPromptOptions
| SelectPromptOptions
| MultiSelectOptions;
interface PromptCommonOptions {
cancel?: "reject" | "default" | "undefined" | "null" | "symbol";
}
interface SelectOption {
label: string;
value: string;
hint?: string;
}
const kCancel: unique symbol;