@esmj/schema 0.3.2 → 0.3.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -33,7 +33,7 @@ When choosing a schema validation library, bundle size can be an important facto
33
33
 
34
34
  | Library | Bundle Size (minified + gzipped) |
35
35
  |------------------|---------------------------------|
36
- | `@esmj/schema` | `~1,1 KB` |
36
+ | `@esmj/schema` | `~1,2 KB` |
37
37
  | Superstruct | ~3.2 KB |
38
38
  | Yup | ~12.2 KB |
39
39
  | Zod@3 | ~13 KB |
@@ -134,8 +134,14 @@ console.log(result);
134
134
 
135
135
  Creates a string schema. You can optionally pass `options` to customize error messages.
136
136
 
137
+ - **`message`**: Can be either a constant string or a function `(value) => string`.
138
+
137
139
  ```typescript
138
140
  const stringSchema = s.string({
141
+ message: 'This is a constant error message.',
142
+ });
143
+
144
+ const stringSchemaFunc = s.string({
139
145
  message: (value) => `Custom error: "${value}" is not a valid string.`,
140
146
  });
141
147
  ```
@@ -144,8 +150,14 @@ const stringSchema = s.string({
144
150
 
145
151
  Creates a number schema. You can optionally pass `options` to customize error messages.
146
152
 
153
+ - **`message`**: Can be either a constant string or a function `(value) => string`.
154
+
147
155
  ```typescript
148
156
  const numberSchema = s.number({
157
+ message: 'This is a constant error message.',
158
+ });
159
+
160
+ const numberSchemaFunc = s.number({
149
161
  message: (value) => `Custom error: "${value}" is not a valid number.`,
150
162
  });
151
163
  ```
@@ -154,8 +166,14 @@ const numberSchema = s.number({
154
166
 
155
167
  Creates a boolean schema. You can optionally pass `options` to customize error messages.
156
168
 
169
+ - **`message`**: Can be either a constant string or a function `(value) => string`.
170
+
157
171
  ```typescript
158
172
  const booleanSchema = s.boolean({
173
+ message: 'This is a constant error message.',
174
+ });
175
+
176
+ const booleanSchemaFunc = s.boolean({
159
177
  message: (value) => `Custom error: "${value}" is not a valid boolean.`,
160
178
  });
161
179
  ```
@@ -164,8 +182,14 @@ const booleanSchema = s.boolean({
164
182
 
165
183
  Creates a date schema. You can optionally pass `options` to customize error messages.
166
184
 
185
+ - **`message`**: Can be either a constant string or a function `(value) => string`.
186
+
167
187
  ```typescript
168
188
  const dateSchema = s.date({
189
+ message: 'This is a constant error message.',
190
+ });
191
+
192
+ const dateSchemaFunc = s.date({
169
193
  message: (value) => `Custom error: "${value}" is not a valid date.`,
170
194
  });
171
195
  ```
@@ -174,8 +198,20 @@ const dateSchema = s.date({
174
198
 
175
199
  Creates an object schema with the given definition. You can optionally pass `options` to customize error messages.
176
200
 
201
+ - **`message`**: Can be either a constant string or a function `(value) => string`.
202
+
177
203
  ```typescript
178
204
  const objectSchema = s.object(
205
+ {
206
+ key: s.string(),
207
+ value: s.number(),
208
+ },
209
+ {
210
+ message: 'This is a constant error message.',
211
+ },
212
+ );
213
+
214
+ const objectSchemaFunc = s.object(
179
215
  {
180
216
  key: s.string(),
181
217
  value: s.number(),
@@ -190,8 +226,14 @@ const objectSchema = s.object(
190
226
 
191
227
  Creates an array schema with the given item definition. You can optionally pass `options` to customize error messages.
192
228
 
229
+ - **`message`**: Can be either a constant string or a function `(value) => string`.
230
+
193
231
  ```typescript
194
232
  const arraySchema = s.array(s.string(), {
233
+ message: 'This is a constant error message.',
234
+ });
235
+
236
+ const arraySchemaFunc = s.array(s.string(), {
195
237
  message: (value) => `Custom error: "${JSON.stringify(value)}" is not a valid array.`,
196
238
  });
197
239
  ```
@@ -200,10 +242,14 @@ const arraySchema = s.array(s.string(), {
200
242
 
201
243
  Creates an enum schema that validates against a predefined set of string values. You can optionally pass `options` to customize error messages.
202
244
 
203
- - **`values`**: An array of strings representing the allowed values for the enum. Each value must be a string.
245
+ - **`message`**: Can be either a constant string or a function `(value) => string`.
204
246
 
205
247
  ```typescript
206
248
  const enumSchema = s.enum(['admin', 'user', 'guest'], {
249
+ message: 'This is a constant error message.',
250
+ });
251
+
252
+ const enumSchemaFunc = s.enum(['admin', 'user', 'guest'], {
207
253
  message: (value) => `Custom error: "${value}" is not a valid enum value.`,
208
254
  });
209
255
  ```
@@ -212,43 +258,24 @@ const enumSchema = s.enum(['admin', 'user', 'guest'], {
212
258
 
213
259
  Creates a schema that validates against multiple schemas (a union of schemas). The value must match at least one of the provided schemas. You can optionally pass `options` to customize error messages.
214
260
 
215
- - **`definitions`**: An array of schemas to validate against.
261
+ - **`message`**: Can be either a constant string or a function `(value) => string`.
216
262
 
217
263
  ```typescript
218
264
  const schema = s.union([
219
265
  s.string(),
220
266
  s.number(),
221
267
  s.boolean(),
222
- ]);
223
-
224
- const validString = schema.parse('hello');
225
- console.log(validString);
226
- // 'hello'
227
-
228
- const validNumber = schema.parse(42);
229
- console.log(validNumber);
230
- // 42
231
-
232
- const validBoolean = schema.parse(true);
233
- console.log(validBoolean);
234
- // true
235
-
236
- const invalidValue = schema.safeParse({ key: 'value' });
237
- console.log(invalidValue.success);
238
- // false
239
- console.log(invalidValue.error.message);
240
- // Validation failed. Expected the value to match one of the schemas: "string" | "number" | "boolean", but received "object" with value "{"key":"value"}".
241
- ```
242
-
243
- **Use Case**: The `union` method is useful when you need to validate data that can be of multiple types, such as a value that can be a string, number, or boolean.
268
+ ], {
269
+ message: 'This is a constant error message.',
270
+ });
244
271
 
245
- ```typescript
246
- const schema = s.union(
247
- [s.string(), s.number(), s.boolean()],
248
- {
249
- message: (value) => `Custom error: "${value}" does not match any of the union schemas.`,
250
- },
251
- );
272
+ const schemaFunc = s.union([
273
+ s.string(),
274
+ s.number(),
275
+ s.boolean(),
276
+ ], {
277
+ message: (value) => `Custom error: "${value}" does not match any of the union schemas.`,
278
+ });
252
279
  ```
253
280
 
254
281
  #### `s.any()`
package/dist/index.d.mts CHANGED
@@ -24,9 +24,7 @@ interface SchemaInterface<Input, Output> {
24
24
  nullish(): SchemaInterface<Input, Output | undefined | null>;
25
25
  default(defaultValue: Partial<Input> | (() => Partial<Input>) | Partial<Output>): SchemaInterface<Input, Output>;
26
26
  pipe<NewOutput>(schema: SchemaInterface<Output, NewOutput>): SchemaInterface<Output, NewOutput>;
27
- refine(validation: (value: Output) => boolean, { message }: {
28
- message: ErrorMessage;
29
- }): SchemaInterface<Input, Output>;
27
+ refine(validation: (value: Output) => boolean, options?: SchemaInterfaceOptions): SchemaInterface<Input, Output>;
30
28
  }
31
29
  interface UnionSchemaInterface<T extends Array<SchemaInterface<unknown, unknown>>> extends SchemaInterface<ReturnType<T[number]['parse']>, ReturnType<T[number]['parse']>> {
32
30
  }
@@ -50,26 +48,26 @@ interface ObjectSchemaInterface<T extends Record<string, SchemaType>> extends Sc
50
48
  }
51
49
  type SchemaType = StringSchemaInterface | SchemaInterface<unknown, unknown> | SchemaInterface<string, string> | SchemaInterface<string, string | undefined> | SchemaInterface<string, string | null> | SchemaInterface<string, string | undefined | null> | ObjectSchemaInterface<Record<string, SchemaType>> | SchemaInterface<object, object> | SchemaInterface<object, object | undefined> | SchemaInterface<object, object | null> | SchemaInterface<object, object | undefined | null> | NumberSchemaInterface | SchemaInterface<number, number> | SchemaInterface<number, number | undefined> | SchemaInterface<number, number | null> | SchemaInterface<number, number | undefined | null> | BooleanSchemaInterface | SchemaInterface<boolean, boolean> | SchemaInterface<boolean, boolean | undefined> | SchemaInterface<boolean, boolean | null> | SchemaInterface<boolean, boolean | undefined | null> | DateSchemaInterface | SchemaInterface<Date, Date> | SchemaInterface<Date, Date | undefined> | SchemaInterface<Date, Date | null> | SchemaInterface<Date, Date | undefined | null> | EnumSchemaInterface<string> | UnionSchemaInterface<Array<SchemaInterface<unknown, unknown>>> | ArraySchemaInterface<StringSchemaInterface | ObjectSchemaInterface<Record<string, SchemaType>> | NumberSchemaInterface | BooleanSchemaInterface | DateSchemaInterface | EnumSchemaInterface<string>> | SchemaInterface<Array<unknown>, Array<unknown>> | SchemaInterface<Array<unknown>, Array<unknown> | undefined> | SchemaInterface<Array<unknown>, Array<unknown> | null> | SchemaInterface<Array<unknown>, Array<unknown> | undefined | null>;
52
50
  type ErrorMessage = string | ((value: unknown) => string);
53
- type ExtenderType = (inter: SchemaType, validation: Function, options: {
51
+ type ExtenderType = (inter: SchemaType, validation: Function, options?: {
54
52
  message: ErrorMessage;
55
53
  type: string;
56
54
  }) => SchemaType;
57
55
  interface CreateSchemaInterfaceOptions {
58
56
  type?: string;
59
- message?: (value: unknown) => string;
57
+ message?: ErrorMessage;
60
58
  }
61
59
  type SchemaInterfaceOptions = Omit<CreateSchemaInterfaceOptions, 'type'>;
62
60
  declare const s: {
63
- object<T extends Record<string, SchemaType>>(definition: { [Property in keyof T]: T[Property]; }, options: SchemaInterfaceOptions): ObjectSchemaInterface<T>;
64
- string(options: SchemaInterfaceOptions): StringSchemaInterface;
65
- number(options: SchemaInterfaceOptions): NumberSchemaInterface;
66
- boolean(options: SchemaInterfaceOptions): BooleanSchemaInterface;
67
- date(options: SchemaInterfaceOptions): DateSchemaInterface;
68
- enum(definition: Readonly<Array<string>>, options: SchemaInterfaceOptions): EnumSchemaInterface<(typeof definition)[number]>;
69
- array<T extends SchemaType>(definition: T, options: SchemaInterfaceOptions): ArraySchemaInterface<T>;
61
+ object<T extends Record<string, SchemaType>>(definition: { [Property in keyof T]: T[Property]; }, options?: SchemaInterfaceOptions): ObjectSchemaInterface<T>;
62
+ string(options?: SchemaInterfaceOptions): StringSchemaInterface;
63
+ number(options?: SchemaInterfaceOptions): NumberSchemaInterface;
64
+ boolean(options?: SchemaInterfaceOptions): BooleanSchemaInterface;
65
+ date(options?: SchemaInterfaceOptions): DateSchemaInterface;
66
+ enum(definition: Readonly<Array<string>>, options?: SchemaInterfaceOptions): EnumSchemaInterface<(typeof definition)[number]>;
67
+ array<T extends SchemaType>(definition: T, options?: SchemaInterfaceOptions): ArraySchemaInterface<T>;
70
68
  any(): any;
71
69
  preprocess<T extends SchemaType>(callback: Function, schema: T): T;
72
- union<T extends Array<SchemaType>>(definitions: T, options: SchemaInterfaceOptions): UnionSchemaInterface<T>;
70
+ union<T extends Array<SchemaType>>(definitions: T, options?: SchemaInterfaceOptions): UnionSchemaInterface<T>;
73
71
  };
74
72
  declare function extend(callback: ExtenderType): void;
75
73
  type Infer<T> = T extends SchemaType ? ReturnType<T['parse']> : unknown;
package/dist/index.d.ts CHANGED
@@ -24,9 +24,7 @@ interface SchemaInterface<Input, Output> {
24
24
  nullish(): SchemaInterface<Input, Output | undefined | null>;
25
25
  default(defaultValue: Partial<Input> | (() => Partial<Input>) | Partial<Output>): SchemaInterface<Input, Output>;
26
26
  pipe<NewOutput>(schema: SchemaInterface<Output, NewOutput>): SchemaInterface<Output, NewOutput>;
27
- refine(validation: (value: Output) => boolean, { message }: {
28
- message: ErrorMessage;
29
- }): SchemaInterface<Input, Output>;
27
+ refine(validation: (value: Output) => boolean, options?: SchemaInterfaceOptions): SchemaInterface<Input, Output>;
30
28
  }
31
29
  interface UnionSchemaInterface<T extends Array<SchemaInterface<unknown, unknown>>> extends SchemaInterface<ReturnType<T[number]['parse']>, ReturnType<T[number]['parse']>> {
32
30
  }
@@ -50,26 +48,26 @@ interface ObjectSchemaInterface<T extends Record<string, SchemaType>> extends Sc
50
48
  }
51
49
  type SchemaType = StringSchemaInterface | SchemaInterface<unknown, unknown> | SchemaInterface<string, string> | SchemaInterface<string, string | undefined> | SchemaInterface<string, string | null> | SchemaInterface<string, string | undefined | null> | ObjectSchemaInterface<Record<string, SchemaType>> | SchemaInterface<object, object> | SchemaInterface<object, object | undefined> | SchemaInterface<object, object | null> | SchemaInterface<object, object | undefined | null> | NumberSchemaInterface | SchemaInterface<number, number> | SchemaInterface<number, number | undefined> | SchemaInterface<number, number | null> | SchemaInterface<number, number | undefined | null> | BooleanSchemaInterface | SchemaInterface<boolean, boolean> | SchemaInterface<boolean, boolean | undefined> | SchemaInterface<boolean, boolean | null> | SchemaInterface<boolean, boolean | undefined | null> | DateSchemaInterface | SchemaInterface<Date, Date> | SchemaInterface<Date, Date | undefined> | SchemaInterface<Date, Date | null> | SchemaInterface<Date, Date | undefined | null> | EnumSchemaInterface<string> | UnionSchemaInterface<Array<SchemaInterface<unknown, unknown>>> | ArraySchemaInterface<StringSchemaInterface | ObjectSchemaInterface<Record<string, SchemaType>> | NumberSchemaInterface | BooleanSchemaInterface | DateSchemaInterface | EnumSchemaInterface<string>> | SchemaInterface<Array<unknown>, Array<unknown>> | SchemaInterface<Array<unknown>, Array<unknown> | undefined> | SchemaInterface<Array<unknown>, Array<unknown> | null> | SchemaInterface<Array<unknown>, Array<unknown> | undefined | null>;
52
50
  type ErrorMessage = string | ((value: unknown) => string);
53
- type ExtenderType = (inter: SchemaType, validation: Function, options: {
51
+ type ExtenderType = (inter: SchemaType, validation: Function, options?: {
54
52
  message: ErrorMessage;
55
53
  type: string;
56
54
  }) => SchemaType;
57
55
  interface CreateSchemaInterfaceOptions {
58
56
  type?: string;
59
- message?: (value: unknown) => string;
57
+ message?: ErrorMessage;
60
58
  }
61
59
  type SchemaInterfaceOptions = Omit<CreateSchemaInterfaceOptions, 'type'>;
62
60
  declare const s: {
63
- object<T extends Record<string, SchemaType>>(definition: { [Property in keyof T]: T[Property]; }, options: SchemaInterfaceOptions): ObjectSchemaInterface<T>;
64
- string(options: SchemaInterfaceOptions): StringSchemaInterface;
65
- number(options: SchemaInterfaceOptions): NumberSchemaInterface;
66
- boolean(options: SchemaInterfaceOptions): BooleanSchemaInterface;
67
- date(options: SchemaInterfaceOptions): DateSchemaInterface;
68
- enum(definition: Readonly<Array<string>>, options: SchemaInterfaceOptions): EnumSchemaInterface<(typeof definition)[number]>;
69
- array<T extends SchemaType>(definition: T, options: SchemaInterfaceOptions): ArraySchemaInterface<T>;
61
+ object<T extends Record<string, SchemaType>>(definition: { [Property in keyof T]: T[Property]; }, options?: SchemaInterfaceOptions): ObjectSchemaInterface<T>;
62
+ string(options?: SchemaInterfaceOptions): StringSchemaInterface;
63
+ number(options?: SchemaInterfaceOptions): NumberSchemaInterface;
64
+ boolean(options?: SchemaInterfaceOptions): BooleanSchemaInterface;
65
+ date(options?: SchemaInterfaceOptions): DateSchemaInterface;
66
+ enum(definition: Readonly<Array<string>>, options?: SchemaInterfaceOptions): EnumSchemaInterface<(typeof definition)[number]>;
67
+ array<T extends SchemaType>(definition: T, options?: SchemaInterfaceOptions): ArraySchemaInterface<T>;
70
68
  any(): any;
71
69
  preprocess<T extends SchemaType>(callback: Function, schema: T): T;
72
- union<T extends Array<SchemaType>>(definitions: T, options: SchemaInterfaceOptions): UnionSchemaInterface<T>;
70
+ union<T extends Array<SchemaType>>(definitions: T, options?: SchemaInterfaceOptions): UnionSchemaInterface<T>;
73
71
  };
74
72
  declare function extend(callback: ExtenderType): void;
75
73
  type Infer<T> = T extends SchemaType ? ReturnType<T['parse']> : unknown;
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- 'use strict';var h=e=>typeof e=="string"||e instanceof String,I=e=>typeof e=="number"||e instanceof Number,l=e=>e===true||e===false,y=e=>e instanceof Date&&!Number.isNaN(e.getTime()),S=e=>Array.isArray(e),d=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),g={object(e,c){let s=p(d,{...c,type:"object"});return i(s,"_parse",(u,...o)=>{let t=u(...o);if(t.success===false)return t;let n={};for(let r in e){let a=e[r]._parse(t.data[r]);if(a.success)n[r]=a.data;else {a=a;let f=a?.error?.cause?.key?`${r}.${a?.error?.cause?.key}`:r;return a.error.message=`Error parsing key "${f}": ${a.error.message}`,a.error.cause={key:f},a}}return {success:true,data:n}}),s},string(e){return p(h,{...e,type:"string"})},number(e){return p(I,{...e,type:"number"})},boolean(e){return p(l,{...e,type:"boolean"})},date(e){return p(y,{...e,type:"date"})},enum(e,c){let s=n=>e.includes(n),u=n=>`Invalid ${o} value. Expected ${e.map(r=>`"${r}"`).join(" | ")}, received "${n}".`,o="enum";return p(s,{message:u,...c,type:o})},array(e,c){let s=p(S,{...c,type:"array"});return i(s,"_parse",(u,...o)=>{let t=u(...o);if(t.success===false)return t;let n=[];for(let r=0;r<t.data.length;r++){let a=e._parse(t.data[r]);if(a.success)n.push(a.data);else {a=a;let f=a.error?.cause?.key?`${r}.${a.error.cause.key}`:`${r}`;return a.error.message=`Error parsing index "${r}": ${a.error.message}`,a.error.cause={key:f},a}}return {success:true,data:n}}),s},any(){return p(()=>true)},preprocess(e,c){return i(c,"_parse",(s,u)=>(u=e(u),s(u))),c},union(e,c){return p(t=>{for(let n=0;n<e.length;n++)if(e[n]._parse(t).success)return true;return false},{message:t=>`Invalid union value. Expected the value to match one of the schemas: ${e.map(n=>`"${n._getType()}"`).join(" | ")}, but received "${typeof t}" with value "${t}".`,...c,type:"union"})}};function T(e){return c=>`The value "${c}" must be type of ${e} but is type of "${typeof c}".`}function i(e,c,s){let u=e[c];e[c]=(...o)=>s(u,...o);}function p(e,{type:c="any",message:s}={}){s=s||T(c);let u={message:s,type:c},o={_getType(){return c},_parse(t){return e(t)?{success:true,data:t}:{success:false,error:{message:s(t)}}},parse(t){let n=o._parse(t);if(!n.success)throw n=n,new Error(n.error.message,{cause:n.error.cause});return n.data},safeParse(t){return o._parse(t)},transform(t){return i(this,"_parse",(n,r)=>{let a=n(r);return a.success&&(a.data=t(a.data)),a}),this},optional(){return i(this,"_parse",(t,n)=>{let r=t(n);return r.success||(r.data=void 0,r.success=true),r}),this},nullable(){return i(this,"_parse",(t,n)=>{let r=t(n);return r.success||(r.data=null,r.success=true),r}),this},nullish(){return i(this,"_parse",(t,n)=>{let r=t(n);return !r.success&&n==null&&(r.success=true,r.data=n),r}),this},default(t){return i(this,"_parse",(n,r)=>(r===void 0&&(r=t,r=typeof t=="function"?t():t),n(r))),this},pipe(t){return i(this,"_parse",(n,r)=>{let a=n(r);return a.success?t._parse(a.data):a}),this},refine(t,{message:n}){return i(this,"_parse",(r,a)=>{let f=r(a);return t(f.data)?f:{success:false,error:{message:n}}}),this}};return m.length>0?m.reduce((t,n)=>n(t,e,u)??t,o):o}var m=[];function b(e){m.push(e);}exports.extend=b;exports.s=g;
1
+ 'use strict';var h=e=>typeof e=="string"||e instanceof String,I=e=>typeof e=="number"||e instanceof Number,y=e=>e===true||e===false,l=e=>e instanceof Date&&!Number.isNaN(e.getTime()),S=e=>Array.isArray(e),d=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),b={object(e,c){let s=f(d,{...c,type:"object"});return i(s,"_parse",(u,...o)=>{let n=u(...o);if(n.success===false)return n;let t={};for(let r in e){let a=e[r]._parse(n.data[r]);if(a.success)t[r]=a.data;else {a=a;let p=a?.error?.cause?.key?`${r}.${a?.error?.cause?.key}`:r;return a.error.message=`Error parsing key "${p}": ${a.error.message}`,a.error.cause={key:p},a}}return {success:true,data:t}}),s},string(e){return f(h,{...e,type:"string"})},number(e){return f(I,{...e,type:"number"})},boolean(e){return f(y,{...e,type:"boolean"})},date(e){return f(l,{...e,type:"date"})},enum(e,c){let s=t=>e.includes(t),u=t=>`Invalid ${o} value. Expected ${e.map(r=>`"${r}"`).join(" | ")}, received "${t}".`,o="enum";return f(s,{message:u,...c,type:o})},array(e,c){let s=f(S,{...c,type:"array"});return i(s,"_parse",(u,...o)=>{let n=u(...o);if(n.success===false)return n;let t=[];for(let r=0;r<n.data.length;r++){let a=e._parse(n.data[r]);if(a.success)t.push(a.data);else {a=a;let p=a.error?.cause?.key?`${r}.${a.error.cause.key}`:`${r}`;return a.error.message=`Error parsing index "${r}": ${a.error.message}`,a.error.cause={key:p},a}}return {success:true,data:t}}),s},any(){return f(()=>true)},preprocess(e,c){return i(c,"_parse",(s,u)=>(u=e(u),s(u))),c},union(e,c){return f(n=>{for(let t=0;t<e.length;t++)if(e[t]._parse(n).success)return true;return false},{message:n=>`Invalid union value. Expected the value to match one of the schemas: ${e.map(t=>`"${t._getType()}"`).join(" | ")}, but received "${typeof n}" with value "${n}".`,...c,type:"union"})}};function T(e){return c=>`The value "${c}" must be type of ${e} but is type of "${typeof c}".`}function i(e,c,s){let u=e[c];e[c]=(...o)=>s(u,...o);}function f(e,{type:c="any",message:s}={}){s=s||T(c);let u={message:s,type:c},o={_getType(){return c},_parse(n){return e(n)?{success:true,data:n}:{success:false,error:{message:typeof s=="function"?s(n):s}}},parse(n){let t=o._parse(n);if(!t.success)throw t=t,new Error(t.error.message,{cause:t.error.cause});return t.data},safeParse(n){return o._parse(n)},transform(n){return i(this,"_parse",(t,r)=>{let a=t(r);return a.success&&(a.data=n(a.data)),a}),this},optional(){return i(this,"_parse",(n,t)=>{let r=n(t);return r.success||(r.data=void 0,r.success=true),r}),this},nullable(){return i(this,"_parse",(n,t)=>{let r=n(t);return r.success||(r.data=null,r.success=true),r}),this},nullish(){return i(this,"_parse",(n,t)=>{let r=n(t);return !r.success&&t==null&&(r.success=true,r.data=t),r}),this},default(n){return i(this,"_parse",(t,r)=>(r===void 0&&(r=n,r=typeof n=="function"?n():n),t(r))),this},pipe(n){return i(this,"_parse",(t,r)=>{let a=t(r);return a.success?n._parse(a.data):a}),this},refine(n,{message:t}={}){return i(this,"_parse",(r,a)=>{let p=r(a);return p.success?n(p.data)?p:{success:false,error:{message:typeof t=="function"?t(a):t}}:p}),this}};return m.length>0?m.reduce((n,t)=>t(n,e,u)??n,o):o}var m=[];function g(e){m.push(e);}exports.extend=g;exports.s=b;
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- var h=e=>typeof e=="string"||e instanceof String,I=e=>typeof e=="number"||e instanceof Number,l=e=>e===true||e===false,y=e=>e instanceof Date&&!Number.isNaN(e.getTime()),S=e=>Array.isArray(e),d=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),g={object(e,c){let s=p(d,{...c,type:"object"});return i(s,"_parse",(u,...o)=>{let t=u(...o);if(t.success===false)return t;let n={};for(let r in e){let a=e[r]._parse(t.data[r]);if(a.success)n[r]=a.data;else {a=a;let f=a?.error?.cause?.key?`${r}.${a?.error?.cause?.key}`:r;return a.error.message=`Error parsing key "${f}": ${a.error.message}`,a.error.cause={key:f},a}}return {success:true,data:n}}),s},string(e){return p(h,{...e,type:"string"})},number(e){return p(I,{...e,type:"number"})},boolean(e){return p(l,{...e,type:"boolean"})},date(e){return p(y,{...e,type:"date"})},enum(e,c){let s=n=>e.includes(n),u=n=>`Invalid ${o} value. Expected ${e.map(r=>`"${r}"`).join(" | ")}, received "${n}".`,o="enum";return p(s,{message:u,...c,type:o})},array(e,c){let s=p(S,{...c,type:"array"});return i(s,"_parse",(u,...o)=>{let t=u(...o);if(t.success===false)return t;let n=[];for(let r=0;r<t.data.length;r++){let a=e._parse(t.data[r]);if(a.success)n.push(a.data);else {a=a;let f=a.error?.cause?.key?`${r}.${a.error.cause.key}`:`${r}`;return a.error.message=`Error parsing index "${r}": ${a.error.message}`,a.error.cause={key:f},a}}return {success:true,data:n}}),s},any(){return p(()=>true)},preprocess(e,c){return i(c,"_parse",(s,u)=>(u=e(u),s(u))),c},union(e,c){return p(t=>{for(let n=0;n<e.length;n++)if(e[n]._parse(t).success)return true;return false},{message:t=>`Invalid union value. Expected the value to match one of the schemas: ${e.map(n=>`"${n._getType()}"`).join(" | ")}, but received "${typeof t}" with value "${t}".`,...c,type:"union"})}};function T(e){return c=>`The value "${c}" must be type of ${e} but is type of "${typeof c}".`}function i(e,c,s){let u=e[c];e[c]=(...o)=>s(u,...o);}function p(e,{type:c="any",message:s}={}){s=s||T(c);let u={message:s,type:c},o={_getType(){return c},_parse(t){return e(t)?{success:true,data:t}:{success:false,error:{message:s(t)}}},parse(t){let n=o._parse(t);if(!n.success)throw n=n,new Error(n.error.message,{cause:n.error.cause});return n.data},safeParse(t){return o._parse(t)},transform(t){return i(this,"_parse",(n,r)=>{let a=n(r);return a.success&&(a.data=t(a.data)),a}),this},optional(){return i(this,"_parse",(t,n)=>{let r=t(n);return r.success||(r.data=void 0,r.success=true),r}),this},nullable(){return i(this,"_parse",(t,n)=>{let r=t(n);return r.success||(r.data=null,r.success=true),r}),this},nullish(){return i(this,"_parse",(t,n)=>{let r=t(n);return !r.success&&n==null&&(r.success=true,r.data=n),r}),this},default(t){return i(this,"_parse",(n,r)=>(r===void 0&&(r=t,r=typeof t=="function"?t():t),n(r))),this},pipe(t){return i(this,"_parse",(n,r)=>{let a=n(r);return a.success?t._parse(a.data):a}),this},refine(t,{message:n}){return i(this,"_parse",(r,a)=>{let f=r(a);return t(f.data)?f:{success:false,error:{message:n}}}),this}};return m.length>0?m.reduce((t,n)=>n(t,e,u)??t,o):o}var m=[];function b(e){m.push(e);}export{b as extend,g as s};
1
+ var h=e=>typeof e=="string"||e instanceof String,I=e=>typeof e=="number"||e instanceof Number,y=e=>e===true||e===false,l=e=>e instanceof Date&&!Number.isNaN(e.getTime()),S=e=>Array.isArray(e),d=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),b={object(e,c){let s=f(d,{...c,type:"object"});return i(s,"_parse",(u,...o)=>{let n=u(...o);if(n.success===false)return n;let t={};for(let r in e){let a=e[r]._parse(n.data[r]);if(a.success)t[r]=a.data;else {a=a;let p=a?.error?.cause?.key?`${r}.${a?.error?.cause?.key}`:r;return a.error.message=`Error parsing key "${p}": ${a.error.message}`,a.error.cause={key:p},a}}return {success:true,data:t}}),s},string(e){return f(h,{...e,type:"string"})},number(e){return f(I,{...e,type:"number"})},boolean(e){return f(y,{...e,type:"boolean"})},date(e){return f(l,{...e,type:"date"})},enum(e,c){let s=t=>e.includes(t),u=t=>`Invalid ${o} value. Expected ${e.map(r=>`"${r}"`).join(" | ")}, received "${t}".`,o="enum";return f(s,{message:u,...c,type:o})},array(e,c){let s=f(S,{...c,type:"array"});return i(s,"_parse",(u,...o)=>{let n=u(...o);if(n.success===false)return n;let t=[];for(let r=0;r<n.data.length;r++){let a=e._parse(n.data[r]);if(a.success)t.push(a.data);else {a=a;let p=a.error?.cause?.key?`${r}.${a.error.cause.key}`:`${r}`;return a.error.message=`Error parsing index "${r}": ${a.error.message}`,a.error.cause={key:p},a}}return {success:true,data:t}}),s},any(){return f(()=>true)},preprocess(e,c){return i(c,"_parse",(s,u)=>(u=e(u),s(u))),c},union(e,c){return f(n=>{for(let t=0;t<e.length;t++)if(e[t]._parse(n).success)return true;return false},{message:n=>`Invalid union value. Expected the value to match one of the schemas: ${e.map(t=>`"${t._getType()}"`).join(" | ")}, but received "${typeof n}" with value "${n}".`,...c,type:"union"})}};function T(e){return c=>`The value "${c}" must be type of ${e} but is type of "${typeof c}".`}function i(e,c,s){let u=e[c];e[c]=(...o)=>s(u,...o);}function f(e,{type:c="any",message:s}={}){s=s||T(c);let u={message:s,type:c},o={_getType(){return c},_parse(n){return e(n)?{success:true,data:n}:{success:false,error:{message:typeof s=="function"?s(n):s}}},parse(n){let t=o._parse(n);if(!t.success)throw t=t,new Error(t.error.message,{cause:t.error.cause});return t.data},safeParse(n){return o._parse(n)},transform(n){return i(this,"_parse",(t,r)=>{let a=t(r);return a.success&&(a.data=n(a.data)),a}),this},optional(){return i(this,"_parse",(n,t)=>{let r=n(t);return r.success||(r.data=void 0,r.success=true),r}),this},nullable(){return i(this,"_parse",(n,t)=>{let r=n(t);return r.success||(r.data=null,r.success=true),r}),this},nullish(){return i(this,"_parse",(n,t)=>{let r=n(t);return !r.success&&t==null&&(r.success=true,r.data=t),r}),this},default(n){return i(this,"_parse",(t,r)=>(r===void 0&&(r=n,r=typeof n=="function"?n():n),t(r))),this},pipe(n){return i(this,"_parse",(t,r)=>{let a=t(r);return a.success?n._parse(a.data):a}),this},refine(n,{message:t}={}){return i(this,"_parse",(r,a)=>{let p=r(a);return p.success?n(p.data)?p:{success:false,error:{message:typeof t=="function"?t(a):t}}:p}),this}};return m.length>0?m.reduce((n,t)=>t(n,e,u)??n,o):o}var m=[];function g(e){m.push(e);}export{g as extend,b as s};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@esmj/schema",
3
- "version": "0.3.2",
3
+ "version": "0.3.4",
4
4
  "description": "Tiny extendable package for schema validation.",
5
5
  "keywords": [
6
6
  "schema",