diff --git a/README.md b/README.md index 0486be9..6ffa618 100644 --- a/README.md +++ b/README.md @@ -84,7 +84,7 @@ Example: `consola.info('Message')` #### `await prompt(message, { type, cancel })` -Show an input prompt. Type can either of `text`, `confirm`, `select` or `multiselect`. +Show an input prompt. Type can either of `text`, `password`, `confirm`, `select` or `multiselect`. If prompt is canceled by user (with Ctrol+C), default value will be resolved by default. This strategy can be configured by setting `{ cancel: "..." }` option: diff --git a/examples/prompt.ts b/examples/prompt.ts index 1764f1e..ae92d45 100755 --- a/examples/prompt.ts +++ b/examples/prompt.ts @@ -31,6 +31,10 @@ async function main() { initial: ["eslint", "prettier"], }); + const password = await consola.prompt("Enter your password.", { + type: "password", + }); + consola.start("Creating project..."); await new Promise((resolve) => setTimeout(resolve, 1000)); consola.success("Project created!"); diff --git a/src/prompt.ts b/src/prompt.ts index 8aee0e3..3f26b2b 100644 --- a/src/prompt.ts +++ b/src/prompt.ts @@ -1,4 +1,4 @@ -import { text, confirm, select, multiselect } from "@clack/prompts"; +import { text, confirm, select, multiselect, password } from "@clack/prompts"; type SelectOption = { label: string; @@ -103,6 +103,25 @@ export type MultiSelectOptions = PromptCommonOptions & { required?: boolean; }; +export type PasswordPromptOptions = PromptCommonOptions & { + /** + * Specifies the prompt type as password. + */ + type: "password"; + + /** + * The mask character for the password prompt. + * @optional + */ + mask?: string; + + /** + * The validation function for the password prompt. + * @optional + */ + validate?: (value: string) => string | Error | undefined; +}; + /** * Defines a combined type for all prompt options. */ @@ -110,7 +129,8 @@ export type PromptOptions = | TextPromptOptions | ConfirmPromptOptions | SelectPromptOptions - | MultiSelectOptions; + | MultiSelectOptions + | PasswordPromptOptions; type inferPromptReturnType = T extends TextPromptOptions @@ -123,7 +143,9 @@ type inferPromptReturnType = : T["options"][number] : T extends MultiSelectOptions ? T["options"] - : unknown; + : T extends PasswordPromptOptions + ? string + : unknown; type inferPromptCancalReturnType = T extends { cancel: "reject"; @@ -183,7 +205,8 @@ export async function prompt< } default: case "default": { - return (opts as TextPromptOptions).default ?? opts.initial; + if (opts.type === "password") return undefined; + return (opts as TextPromptOptions).default ?? (opts as any).initial; } } }; @@ -225,5 +248,13 @@ export async function prompt< }).then(handleCancel)) as any; } + if (opts.type === "password") { + return (await password({ + message, + mask: opts.mask ?? "", // default mask does not display characters. + validate: opts.validate, + }).then(handleCancel)) as any; + } + throw new Error(`Unknown prompt type: ${opts.type}`); }