| 1 | import prompts from "prompts"; |
| 2 | import type { RunOptions } from "../types"; |
| 3 | import type { Validator } from "./types"; |
| 4 | |
| 5 | export * from "./validators/index.js"; |
| 6 | |
| 7 | interface Chainable<T = Record<string, never>> { |
| 8 | validator<V>(val: Validator<V>): Chainable<T & V>; |
| 9 | exec(): Promise<T>; |
| 10 | } |
| 11 | |
| 12 | /** |
| 13 | * `Validate` performs some validation logic sequencially each time returning the validated and sanitized option |
| 14 | * If interactive mode is run validate also creates a prompt queue that will get executed to ask options to the user in real time |
| 15 | * > NOTE: Order of validators in the chain matters! |
| 16 | */ |
| 17 | export function validate(options: RunOptions): Chainable { |
| 18 | // eslint-disable-next-line @typescript-eslint/no-explicit-any |
| 19 | const validators: Validator<any>[] = []; |
| 20 | |
| 21 | // eslint-disable-next-line @typescript-eslint/no-explicit-any |
| 22 | async function exec(): Promise<any> { |
| 23 | const interactiveQuestions: prompts.PromptObject<string>[] = []; |
| 24 | const validatedOptions = {}; |
| 25 | |
| 26 | const validated = await Promise.all(validators.map((v) => v(options))); |
| 27 | |
| 28 | for (const item of validated) { |
| 29 | const [d, q] = item; |
| 30 | if (q) { |
| 31 | interactiveQuestions.push(...q); |
| 32 | } else { |
| 33 | Object.assign(validatedOptions, d); |
| 34 | } |
| 35 | } |
| 36 | |
| 37 | if (interactiveQuestions.length > 0) { |
| 38 | const questionsResponse = await prompts(interactiveQuestions); |
| 39 | Object.assign(validatedOptions, questionsResponse); |
| 40 | } |
| 41 | |
| 42 | return validatedOptions; |
| 43 | } |
| 44 | |
| 45 | function validator<T>(val: Validator<T>) { |
| 46 | validators.push(val); |
| 47 | return { |
| 48 | validator, |
| 49 | exec, |
| 50 | }; |
| 51 | } |
| 52 | |
| 53 | return { |
| 54 | validator, |
| 55 | exec, |
| 56 | }; |
| 57 | } |