1
1
import { z , type ZodSchema } from 'zod' ;
2
2
import type { ParsedResult } from '../types/parser.js' ;
3
+ import { ParseError } from '../errors.js' ;
3
4
4
5
export class Envelope {
5
6
/**
@@ -14,14 +15,20 @@ export class Envelope {
14
15
data : unknown ,
15
16
schema : T
16
17
) : z . infer < T > => {
17
- if ( typeof data === 'string' ) {
18
- return schema . parse ( JSON . parse ( data ) ) ;
19
- } else if ( typeof data === 'object' ) {
20
- return schema . parse ( data ) ;
21
- } else
22
- throw new Error (
18
+ if ( typeof data !== 'object' && typeof data !== 'string' ) {
19
+ throw new ParseError (
23
20
`Invalid data type for envelope. Expected string or object, got ${ typeof data } `
24
21
) ;
22
+ }
23
+ try {
24
+ if ( typeof data === 'string' ) {
25
+ return schema . parse ( JSON . parse ( data ) ) ;
26
+ } else if ( typeof data === 'object' ) {
27
+ return schema . parse ( data ) ;
28
+ }
29
+ } catch ( e ) {
30
+ throw new ParseError ( `Failed to parse envelope` , e as Error ) ;
31
+ }
25
32
} ;
26
33
27
34
/**
@@ -38,7 +45,7 @@ export class Envelope {
38
45
if ( typeof input !== 'object' && typeof input !== 'string' ) {
39
46
return {
40
47
success : false ,
41
- error : new Error (
48
+ error : new ParseError (
42
49
`Invalid data type for envelope. Expected string or object, got ${ typeof input } `
43
50
) ,
44
51
originalEvent : input ,
@@ -56,13 +63,13 @@ export class Envelope {
56
63
}
57
64
: {
58
65
success : false ,
59
- error : parsed . error ,
66
+ error : new ParseError ( `Failed to parse envelope` , parsed . error ) ,
60
67
originalEvent : input ,
61
68
} ;
62
69
} catch ( e ) {
63
70
return {
64
71
success : false ,
65
- error : e as Error ,
72
+ error : new ParseError ( `Failed to parse envelope` , e as Error ) ,
66
73
originalEvent : input ,
67
74
} ;
68
75
}
0 commit comments