this repo has no description
1import type { PromptValidator, ValidationResponse } from "@topcli/prompts";
2import { getMaxUnsignedInt } from "./bit-manipulation.ts";
3
4export function createStringPromptValidator(
5 validate: (input: string) => ValidationResponse,
6): PromptValidator<string> {
7 return {
8 validate: validate,
9 };
10}
11
12export function createIntPromptValidator(
13 validate?: (input: number) => ValidationResponse,
14) {
15 if (validate == undefined) {
16 validate = () => ({ isValid: true });
17 }
18
19 return createStringPromptValidator((input) => {
20 // Number.parseInt() truncates floats, but we want to reject them
21 const inputNumber = Number.parseFloat(input);
22 if (Number.isNaN(inputNumber)) {
23 return { isValid: false, error: "Input was not a number" };
24 }
25 if (!Number.isInteger(inputNumber)) {
26 return { isValid: false, error: "Input was not an integer" };
27 }
28 return validate(inputNumber);
29 });
30}
31
32export function createUintPromptValidator(
33 uintLengthBits: number,
34 errorMsg?: string,
35) {
36 return createIntPromptValidator((input) => {
37 if (input < getMaxUnsignedInt(uintLengthBits)) {
38 return { isValid: true } as const;
39 } else {
40 return {
41 isValid: false,
42 error:
43 errorMsg ?? `Input does not fit in ${uintLengthBits} bits`,
44 } as const;
45 }
46 });
47}
48
49export const nonNegativeIntPromptValidator = createIntPromptValidator(
50 (input) => {
51 if (input >= 0) {
52 return { isValid: true } as const;
53 } else {
54 return {
55 isValid: false,
56 error: `Input was negative`,
57 } as const;
58 }
59 },
60);