From 8093f3c2a5f7db000b5869b65724c403651fa387 Mon Sep 17 00:00:00 2001 From: Bruno Rocha <100330057+orochaa@users.noreply.github.com> Date: Thu, 9 Jan 2025 01:15:58 -0300 Subject: [PATCH] feat(@clack/core,@clack/prompts): add `Error` support for `prompt.validate` (#165) Co-authored-by: Nate Moore --- .changeset/moody-hairs-learn.md | 6 ++++++ packages/core/src/prompts/prompt.ts | 4 ++-- packages/prompts/src/index.ts | 4 ++-- 3 files changed, 10 insertions(+), 4 deletions(-) create mode 100644 .changeset/moody-hairs-learn.md diff --git a/.changeset/moody-hairs-learn.md b/.changeset/moody-hairs-learn.md new file mode 100644 index 00000000..9bf92454 --- /dev/null +++ b/.changeset/moody-hairs-learn.md @@ -0,0 +1,6 @@ +--- +'@clack/prompts': patch +'@clack/core': patch +--- + +Adds `Error` support to the `validate` function diff --git a/packages/core/src/prompts/prompt.ts b/packages/core/src/prompts/prompt.ts index 16dcf80d..6707450d 100644 --- a/packages/core/src/prompts/prompt.ts +++ b/packages/core/src/prompts/prompt.ts @@ -14,7 +14,7 @@ export interface PromptOptions { render(this: Omit): string | undefined; placeholder?: string; initialValue?: any; - validate?: ((value: any) => string | undefined) | undefined; + validate?: ((value: any) => string | Error | undefined) | undefined; input?: Readable; output?: Writable; debug?: boolean; @@ -207,7 +207,7 @@ export default class Prompt { if (this.opts.validate) { const problem = this.opts.validate(this.value); if (problem) { - this.error = problem; + this.error = problem instanceof Error ? problem.message : problem; this.state = 'error'; this.rl?.write(this.value); } diff --git a/packages/prompts/src/index.ts b/packages/prompts/src/index.ts index 45471005..2c152845 100644 --- a/packages/prompts/src/index.ts +++ b/packages/prompts/src/index.ts @@ -102,7 +102,7 @@ export interface TextOptions { placeholder?: string; defaultValue?: string; initialValue?: string; - validate?: (value: string) => string | undefined; + validate?: (value: string) => string | Error | undefined; } export const text = (opts: TextOptions) => { return new TextPrompt({ @@ -138,7 +138,7 @@ export const text = (opts: TextOptions) => { export interface PasswordOptions { message: string; mask?: string; - validate?: (value: string) => string | undefined; + validate?: (value: string) => string | Error | undefined; } export const password = (opts: PasswordOptions) => { return new PasswordPrompt({