diff --git a/src/cli/argvParser.ts b/src/cli/argvParser.ts new file mode 100644 index 0000000000..5edf535efc --- /dev/null +++ b/src/cli/argvParser.ts @@ -0,0 +1,259 @@ +import { z } from "zod"; + +import { err, ok, type Result } from "../domain/result.js"; + +/** + * REA's argv parser for one command: binds tokens to the command's + * positionals and options, then validates them with the command's schemas. + * Option keys are camelCase; each is spelled `--kebab-case` on the command + * line and also accepted as `--camelCase`. A boolean option is set by its + * bare flag and cleared by `--no-`; `--flag=value` and `--flag value` + * both bind a value; an array option collects every occurrence; a short + * alias may be stacked (`-ab`) when all but the last are booleans or + * counts; a count option adds one per occurrence (`-vvv`). `--` is + * not a separator here: after the command it is an unknown flag. The + * messages and field errors match what REA has always printed (#11654). + */ + +/** One field that failed validation, as REA prints it. */ +export interface CliFieldError { + readonly code: string; + /** The caller did not supply the field at all. */ + readonly missing: boolean; + /** Dotted path within the positionals or options. */ + readonly path: string; + readonly expected: string; + readonly received: string; + readonly message: string; +} + +/** + * Why argv was refused: a token the parser cannot bind (an unknown flag or a + * missing value), or bound positionals or options their schema refused. + */ +export type CliArgvFailure = + | { readonly kind: "parse"; readonly message: string } + | { + readonly kind: "validation"; + readonly message: string; + readonly fieldErrors: readonly CliFieldError[]; + }; + +const parseFailure = (message: string): Result => + err({ kind: "parse", message }); + +export interface CliArgvSchemas { + /** Positionals in argv order; a final array field takes the rest. */ + readonly args?: z.ZodObject | undefined; + readonly options?: z.ZodObject | undefined; + /** Short alias by option key, such as `{ yes: "y" }`. */ + readonly alias?: Readonly> | undefined; +} + +export interface CliParsedArgv { + readonly args: Record; + readonly options: Record; +} + +const kebabCase = (key: string): string => + key.replaceAll(/[A-Z]/gu, (letter) => `-${letter.toLowerCase()}`); + +/** The declared type below optional, default, nullable and similar wrappers. */ +const declaredType = (field: z.ZodType): z.ZodType => { + let current = field; + for ( + let inner: unknown = Reflect.get(current.def, "innerType"); + inner instanceof z.ZodType; + inner = Reflect.get(current.def, "innerType") + ) + current = inner; + return current; +}; + +const fieldOf = ( + schema: z.ZodObject | undefined, + name: string, +): z.ZodType | undefined => + schema === undefined + ? undefined + : (schema.shape as Readonly>)[name]; + +const isBoolean = (schema: z.ZodObject | undefined, name: string): boolean => { + const field = fieldOf(schema, name); + return field !== undefined && declaredType(field) instanceof z.ZodBoolean; +}; + +/** A count option (`.meta({ count: true })`) adds one per occurrence. */ +const isCount = (schema: z.ZodObject | undefined, name: string): boolean => + fieldOf(schema, name)?.meta()?.count === true; + +const isArray = (schema: z.ZodObject | undefined, name: string): boolean => { + const field = fieldOf(schema, name); + return field !== undefined && declaredType(field) instanceof z.ZodArray; +}; + +/** Number and boolean options arrive as text; the schema validates the result. */ +const coerce = (value: unknown, schema: z.ZodObject, name: string): unknown => { + const field = fieldOf(schema, name); + if (field === undefined || typeof value !== "string") return value; + const type = declaredType(field); + if (type instanceof z.ZodNumber) return Number(value); + if (type instanceof z.ZodBoolean) return value === "true"; + return value; +}; + +/** Whether the raw input holds the issue's whole path. */ +const hasPath = (data: unknown, path: readonly PropertyKey[]): boolean => { + let current = data; + for (const part of path) { + if (typeof current !== "object" || current === null) return false; + if (!(part in current)) return false; + current = (current as Record)[part]; + } + return true; +}; + +/** Validate with `schema`, reporting each issue as a field error. */ +export const validateCliInputs = ( + schema: z.ZodObject, + data: Readonly>, +): Result, CliArgvFailure> => { + const parsed = schema.safeParse(data); + if (parsed.success) return ok(parsed.data); + const { issues } = parsed.error; + return err({ + kind: "validation", + message: + issues.map(({ message }) => message).join("; ") || "Validation failed", + fieldErrors: issues.map((issue) => ({ + code: issue.code, + missing: !hasPath(data, issue.path), + path: issue.path.join("."), + expected: stringField(issue, "expected"), + received: stringField(issue, "received"), + message: issue.message, + })), + }); +}; + +/** Zod reports `expected` (and older issues `received`) as text when present. */ +const stringField = (issue: object, key: string): string => + (Reflect.get(issue, key) as string | undefined) ?? ""; + +/** Bind and validate one command's argv. */ +export const parseCliArgv = ( + argv: readonly string[], + schemas: CliArgvSchemas, +): Result => { + const { args: argsSchema, options: optionsSchema, alias } = schemas; + const known = new Set( + optionsSchema === undefined ? [] : Object.keys(optionsSchema.shape), + ); + const camelOf = new Map( + [...known].flatMap((name) => + kebabCase(name) === name ? [] : [[kebabCase(name), name] as const], + ), + ); + const optionName = (raw: string): string | undefined => { + const name = camelOf.get(raw) ?? raw; + return known.has(name) ? name : undefined; + }; + const aliasName = new Map( + Object.entries(alias ?? {}).map(([name, short]) => [short, name] as const), + ); + const positionals: string[] = []; + const options: Record = {}; + const set = (name: string, value: string): void => { + if (!isArray(optionsSchema, name)) { + options[name] = value; + return; + } + const existing = options[name]; + if (Array.isArray(existing)) existing.push(value); + else options[name] = [value]; + }; + for (let index = 0; index < argv.length; index += 1) { + const token = argv[index]!; + if (token.startsWith("--no-") && token.length > 5) { + const name = optionName(token.slice(5)); + if (name === undefined) return parseFailure(`Unknown flag: ${token}`); + options[name] = false; + } else if (token.startsWith("--")) { + const equals = token.indexOf("="); + if (equals !== -1) { + const raw = token.slice(2, equals); + const name = optionName(raw); + if (name === undefined) return parseFailure(`Unknown flag: --${raw}`); + set(name, token.slice(equals + 1)); + continue; + } + const name = optionName(token.slice(2)); + if (name === undefined) return parseFailure(`Unknown flag: ${token}`); + if (isCount(optionsSchema, name)) { + options[name] = ((options[name] as number | undefined) ?? 0) + 1; + continue; + } + if (isBoolean(optionsSchema, name)) { + options[name] = true; + continue; + } + const value = argv[index + 1]; + if (value === undefined) + return parseFailure(`Missing value for flag: ${token}`); + set(name, value); + index += 1; + } else if (token.startsWith("-") && token.length >= 2) { + const shorts = token.slice(1); + for (const [position, short] of [...shorts].entries()) { + const name = aliasName.get(short); + if (name === undefined) return parseFailure(`Unknown flag: -${short}`); + if (isCount(optionsSchema, name)) { + options[name] = ((options[name] as number | undefined) ?? 0) + 1; + continue; + } + if (isBoolean(optionsSchema, name)) { + options[name] = true; + continue; + } + if (position !== shorts.length - 1) + return parseFailure( + `Non-boolean flag -${short} must be last in a stacked alias`, + ); + const value = argv[index + 1]; + if (value === undefined) + return parseFailure(`Missing value for flag: -${short}`); + set(name, value); + index += 1; + } + } else { + positionals.push(token); + } + } + const rawArgs: Record = {}; + if (argsSchema !== undefined) { + const keys = Object.keys(argsSchema.shape); + for (const [position, key] of keys.entries()) { + if (isArray(argsSchema, key)) { + if (position !== keys.length - 1) + throw new Error( + `Variadic arg "${key}" must be the last key in the args schema`, + ); + const rest = positionals.slice(position); + if (rest.length > 0) rawArgs[key] = rest; + } else if (positionals[position] !== undefined) + rawArgs[key] = positionals[position]; + } + } + // Positionals are validated first; their failure is reported alone. + const parsedArgs = + argsSchema === undefined ? ok({}) : validateCliInputs(argsSchema, rawArgs); + if (!parsedArgs.ok) return parsedArgs; + if (optionsSchema === undefined) + return ok({ args: parsedArgs.value, options: {} }); + for (const [name, value] of Object.entries(options)) + options[name] = coerce(value, optionsSchema, name); + const parsedOptions = validateCliInputs(optionsSchema, options); + return parsedOptions.ok + ? ok({ args: parsedArgs.value, options: parsedOptions.value }) + : parsedOptions; +}; diff --git a/src/cli/strictPositionals.ts b/src/cli/strictPositionals.ts index 3830cb6fbf..10c4feba52 100644 --- a/src/cli/strictPositionals.ts +++ b/src/cli/strictPositionals.ts @@ -1,15 +1,16 @@ import { AsyncLocalStorage } from "node:async_hooks"; -import { Errors, Parser } from "incur"; +import { Errors } from "incur"; import { z } from "zod"; import { splitIncurBuiltinArguments } from "../cliBuiltinArguments.js"; +import { parseCliArgv } from "./argvParser.js"; import type { CliInstance } from "./types.js"; import { visitRegisteredCommands } from "./visitRegisteredCommands.js"; type ServeOptions = NonNullable[1]>; -/** Match the wrapper types the pinned Incur parser unwraps for token binding. */ +/** Match the wrapper types the argv parser unwraps for token binding. */ const tokenType = (field: z.ZodType): z.ZodType => { let inner = field; while ("innerType" in inner.def) { @@ -111,11 +112,21 @@ export const validateCliArguments = ( : token, ) : rest; - const parsed = Parser.parse(admitted, { + const bound = parseCliArgv(admitted, { args, options, alias: command.alias as Record | undefined, }); + // The dispatcher already bound these tokens with the real schemas, + // so a refusal here is reported as the dispatcher reports its own. + if (!bound.ok) + throw bound.error.kind === "parse" + ? new Errors.ParseError({ message: bound.error.message }) + : new Errors.ValidationError({ + message: bound.error.message, + fieldErrors: [...bound.error.fieldErrors], + }); + const parsed = bound.value; const dryRunValues: unknown = "dryRun" in parsed.options ? parsed.options.dryRun : undefined; if ( diff --git a/tests/boundary/cli/argvParser.test.ts b/tests/boundary/cli/argvParser.test.ts new file mode 100644 index 0000000000..c8e09df5a1 --- /dev/null +++ b/tests/boundary/cli/argvParser.test.ts @@ -0,0 +1,140 @@ +import { z } from "zod"; +import { describe, expect, it } from "vitest"; + +import { parseCliArgv } from "../../../src/cli/argvParser.js"; + +const schemas = { + args: z.object({ path: z.string(), rest: z.array(z.string()).optional() }), + options: z.object({ + blockSize: z.number().default(4096), + global: z.boolean().default(true), + yes: z.boolean().optional(), + column: z.array(z.string()).optional(), + mode: z.enum(["a", "b"]).optional(), + }), + alias: { yes: "y", mode: "m" }, +}; + +const bound = ( + argv: readonly string[], + selected: Parameters[1] = schemas, +) => { + const result = parseCliArgv(argv, selected); + if (!result.ok) throw new Error(result.error.message); + return result.value; +}; + +const failure = (argv: readonly string[]) => { + const result = parseCliArgv(argv, schemas); + if (result.ok) throw new Error("parse succeeded"); + return result.error; +}; + +describe("parseCliArgv", () => { + it("binds kebab-case and camelCase spellings, values and negations", () => { + expect( + bound([ + "file", + "--block-size", + "256", + "--no-global", + "--column=a", + "--column", + "b", + "x", + "y", + ]), + ).toEqual({ + args: { path: "file", rest: ["x", "y"] }, + options: { blockSize: 256, global: false, column: ["a", "b"] }, + }); + expect(bound(["file", "--blockSize=512", "--global"]).options).toEqual({ + blockSize: 512, + global: true, + }); + }); + + it("stacks short aliases when all but the last are booleans", () => { + expect(bound(["file", "-ym", "a"]).options).toMatchObject({ + yes: true, + mode: "a", + }); + expect(failure(["file", "-my"])).toEqual({ + kind: "parse", + message: "Non-boolean flag -m must be last in a stacked alias", + }); + }); + + it.each([ + [["file", "--nope"], "Unknown flag: --nope"], + [["file", "--nope=1"], "Unknown flag: --nope"], + [["file", "--no-nope"], "Unknown flag: --no-nope"], + [["file", "-z"], "Unknown flag: -z"], + [["file", "--"], "Unknown flag: --"], + [["file", "--block-size"], "Missing value for flag: --block-size"], + [["file", "-m"], "Missing value for flag: -m"], + ])("refuses %j with the message REA prints", (argv, message) => { + expect(failure(argv)).toEqual({ kind: "parse", message }); + }); + + it("reports schema failures as field errors", () => { + // Positionals are validated first, so the missing path is reported alone. + expect(failure(["--block-size", "abc", "--mode", "c"])).toEqual({ + kind: "validation", + message: "Invalid input: expected string, received undefined", + fieldErrors: [ + { + code: "invalid_type", + missing: true, + path: "path", + expected: "string", + received: "", + message: "Invalid input: expected string, received undefined", + }, + ], + }); + // Captured from incur 0.6.1's Parser.parse with the same schema and argv. + expect(failure(["file", "--block-size", "abc", "--mode", "c"])).toEqual({ + kind: "validation", + message: + 'Invalid input: expected number, received NaN; Invalid option: expected one of "a"|"b"', + fieldErrors: [ + { + code: "invalid_type", + missing: false, + path: "blockSize", + expected: "number", + received: "NaN", + message: "Invalid input: expected number, received NaN", + }, + { + code: "invalid_value", + missing: false, + path: "mode", + expected: "", + received: "", + message: 'Invalid option: expected one of "a"|"b"', + }, + ], + }); + }); + + it("adds one per occurrence of a count option, stacked or spelled out", () => { + const counted = { + options: z.object({ + verbosity: z.number().default(0).meta({ count: true }), + yes: z.boolean().optional(), + }), + alias: { verbosity: "v", yes: "y" }, + }; + expect(bound(["-vyv", "--verbosity"], counted).options).toEqual({ + verbosity: 3, + yes: true, + }); + }); + + it("reads boolean text as true only for 'true'", () => { + expect(bound(["file", "--yes=maybe"]).options.yes).toBe(false); + expect(bound(["file", "--yes=true"]).options.yes).toBe(true); + }); +});