All files / linter printError.ts

65.38% Statements 17/26
60% Branches 9/15
71.42% Functions 5/7
64% Lines 16/25

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69    2x                   21x       8x 6x     2x 2x       2x 2x 2x           2x 6x   8x   8x 2x               6x                   2x                      
import { ZodError, ZodIssue } from "zod";
 
import { CLI_FORMAT_RED } from "../tester/cliFormat";
 
export interface LintIssueFromZod {
  message: string;
  path: (string | number)[];
  code?: string;
  value?: unknown;
}
 
function normalizePath(path: PropertyKey[]): (string | number)[] {
  return path.map((segment) => (typeof segment === "symbol" ? String(segment) : segment));
}
 
function getInvalidUnionIssue(issue: ZodIssue): ZodIssue | undefined {
  if (issue.code !== "invalid_union" || issue.path.length > 0) {
    return undefined;
  }
 
  const unionErrors = (issue as any).unionErrors as ZodError[] | undefined;
  Iif (Array.isArray(unionErrors) && unionErrors.length > 0) {
    return unionErrors[unionErrors.length - 1].issues[0];
  }
 
  const errors = (issue as any).errors as ZodIssue[][] | undefined;
  if (Array.isArray(errors) && errors.length > 0) {
    return errors[errors.length - 1][0];
  }
 
  return undefined;
}
 
export function getLintIssuesFromZodError(e: ZodError): LintIssueFromZod[] {
  return e.issues
    .map((issue) => {
      const nestedIssue = getInvalidUnionIssue(issue);
 
      if (nestedIssue) {
        return {
          message: nestedIssue.message,
          path: normalizePath(nestedIssue.path),
          code: nestedIssue.code,
          value: (nestedIssue as any).received,
        };
      }
 
      return {
        message: issue.message,
        path: normalizePath(issue.path),
        code: issue.code,
        value: (issue as any).received,
      };
    })
    .filter(Boolean);
}
 
export function printZodError(e: ZodError) {
  const issues = getLintIssuesFromZodError(e);
  issues.forEach((issue) => {
    console.error(CLI_FORMAT_RED, `  => Error: ${issue.message}`);
    console.error("     Path:", issue.path.join("."));
    Iif (typeof issue.value !== "undefined" && issue.value !== "undefined") {
      console.error("     Value:", issue.value);
    }
    console.error("");
  });
}