1- import { bold , red } from 'ansis' ;
1+ import { bold } from 'ansis' ;
22import path from 'node:path' ;
3- import type { z } from 'zod' ;
4- import {
5- type MessageBuilder ,
6- fromError ,
7- isZodErrorLike ,
8- } from 'zod-validation-error' ;
3+ import { ZodError , z } from 'zod' ;
94
105type SchemaValidationContext = {
116 schemaType : string ;
@@ -15,43 +10,16 @@ type SchemaValidationContext = {
1510export class SchemaValidationError extends Error {
1611 constructor (
1712 { schemaType, sourcePath } : SchemaValidationContext ,
18- error : Error ,
13+ error : ZodError ,
1914 ) {
20- const validationError = fromError ( error , {
21- messageBuilder : zodErrorMessageBuilder ,
22- } ) ;
15+ const formattedError = z . prettifyError ( error ) ;
2316 const pathDetails = sourcePath
2417 ? ` in ${ bold ( path . relative ( process . cwd ( ) , sourcePath ) ) } `
2518 : '' ;
26- super (
27- `Failed parsing ${ schemaType } ${ pathDetails } .\n\n${ validationError . message } ` ,
28- ) ;
19+ super ( `Failed parsing ${ schemaType } ${ pathDetails } .\n\n${ formattedError } ` ) ;
2920 }
3021}
3122
32- export function formatErrorPath ( errorPath : ( string | number ) [ ] ) : string {
33- return errorPath
34- . map ( ( key , index ) => {
35- if ( typeof key === 'number' ) {
36- return `[${ key } ]` ;
37- }
38- return index > 0 ? `.${ key } ` : key ;
39- } )
40- . join ( '' ) ;
41- }
42-
43- const zodErrorMessageBuilder : MessageBuilder = issues =>
44- issues
45- . map ( issue => {
46- const formattedMessage = red ( `${ bold ( issue . code ) } : ${ issue . message } ` ) ;
47- const formattedPath = formatErrorPath ( issue . path ) ;
48- if ( formattedPath ) {
49- return `Validation error at ${ bold ( formattedPath ) } \n${ formattedMessage } \n` ;
50- }
51- return `${ formattedMessage } \n` ;
52- } )
53- . join ( '\n' ) ;
54-
5523export function parseSchema < T extends z . ZodTypeAny > (
5624 schema : T ,
5725 data : z . input < T > ,
@@ -60,7 +28,7 @@ export function parseSchema<T extends z.ZodTypeAny>(
6028 try {
6129 return schema . parse ( data ) ;
6230 } catch ( error ) {
63- if ( isZodErrorLike ( error ) ) {
31+ if ( error instanceof ZodError ) {
6432 throw new SchemaValidationError ( { schemaType, sourcePath } , error ) ;
6533 }
6634 throw error ;
0 commit comments