11import { z , type ZodSchema } from 'zod' ;
22import type { ParsedResult } from '../types/parser.js' ;
3+ import { ParseError } from '../errors.js' ;
34
45export class Envelope {
56 /**
@@ -14,14 +15,20 @@ export class Envelope {
1415 data : unknown ,
1516 schema : T
1617 ) : 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 (
2320 `Invalid data type for envelope. Expected string or object, got ${ typeof data } `
2421 ) ;
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+ }
2532 } ;
2633
2734 /**
@@ -38,7 +45,7 @@ export class Envelope {
3845 if ( typeof input !== 'object' && typeof input !== 'string' ) {
3946 return {
4047 success : false ,
41- error : new Error (
48+ error : new ParseError (
4249 `Invalid data type for envelope. Expected string or object, got ${ typeof input } `
4350 ) ,
4451 originalEvent : input ,
@@ -56,13 +63,13 @@ export class Envelope {
5663 }
5764 : {
5865 success : false ,
59- error : parsed . error ,
66+ error : new ParseError ( `Failed to parse envelope` , parsed . error ) ,
6067 originalEvent : input ,
6168 } ;
6269 } catch ( e ) {
6370 return {
6471 success : false ,
65- error : e as Error ,
72+ error : new ParseError ( `Failed to parse envelope` , e as Error ) ,
6673 originalEvent : input ,
6774 } ;
6875 }
0 commit comments