@cleverbrush/schema 1.0.0-beta.4 → 1.0.0

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.
Files changed (76) hide show
  1. package/README.md +118 -320
  2. package/dist/builders/AnySchemaBuilder.d.ts +76 -0
  3. package/dist/builders/AnySchemaBuilder.js +112 -0
  4. package/dist/builders/ArraySchemaBuilder.d.ts +112 -14
  5. package/dist/builders/ArraySchemaBuilder.js +254 -111
  6. package/dist/builders/BooleanSchemaBuilder.d.ts +69 -29
  7. package/dist/builders/BooleanSchemaBuilder.js +134 -74
  8. package/dist/builders/DateSchemaBuilder.d.ts +177 -0
  9. package/dist/builders/DateSchemaBuilder.js +433 -0
  10. package/dist/builders/FunctionSchemaBuilder.d.ts +59 -23
  11. package/dist/builders/FunctionSchemaBuilder.js +103 -56
  12. package/dist/builders/NumberSchemaBuilder.d.ts +159 -59
  13. package/dist/builders/NumberSchemaBuilder.js +345 -165
  14. package/dist/builders/ObjectSchemaBuilder.d.ts +357 -81
  15. package/dist/builders/ObjectSchemaBuilder.js +519 -283
  16. package/dist/builders/SchemaBuilder.d.ts +158 -34
  17. package/dist/builders/SchemaBuilder.js +258 -71
  18. package/dist/builders/StringSchemaBuilder.d.ts +138 -13
  19. package/dist/builders/StringSchemaBuilder.js +261 -115
  20. package/dist/builders/UnionSchemaBuilder.d.ts +129 -9
  21. package/dist/builders/UnionSchemaBuilder.js +196 -75
  22. package/dist/index.d.ts +20 -40
  23. package/dist/index.js +19 -32
  24. package/dist/utils/transaction.d.ts +46 -0
  25. package/dist/utils/transaction.js +178 -0
  26. package/package.json +27 -14
  27. package/dist/defaultSchemas.d.ts +0 -4
  28. package/dist/defaultSchemas.js +0 -45
  29. package/dist/schema.d.ts +0 -230
  30. package/dist/schema.js +0 -2
  31. package/dist/schemaRegistry.d.ts +0 -49
  32. package/dist/schemaRegistry.js +0 -278
  33. package/dist/validators/validateArray.d.ts +0 -3
  34. package/dist/validators/validateArray.js +0 -60
  35. package/dist/validators/validateBoolean.d.ts +0 -2
  36. package/dist/validators/validateBoolean.js +0 -30
  37. package/dist/validators/validateFunction.d.ts +0 -2
  38. package/dist/validators/validateFunction.js +0 -21
  39. package/dist/validators/validateNumber.d.ts +0 -2
  40. package/dist/validators/validateNumber.js +0 -69
  41. package/dist/validators/validateObject.d.ts +0 -3
  42. package/dist/validators/validateObject.js +0 -95
  43. package/dist/validators/validateString.d.ts +0 -2
  44. package/dist/validators/validateString.js +0 -50
  45. package/dist/validators/validateUnion.d.ts +0 -3
  46. package/dist/validators/validateUnion.js +0 -30
  47. package/src/builders/ArraySchemaBuilder.test.ts +0 -270
  48. package/src/builders/ArraySchemaBuilder.ts +0 -381
  49. package/src/builders/BooleanSchemaBuilder.test.ts +0 -196
  50. package/src/builders/BooleanSchemaBuilder.ts +0 -155
  51. package/src/builders/FunctionSchemaBuilder.test.ts +0 -134
  52. package/src/builders/FunctionSchemaBuilder.ts +0 -109
  53. package/src/builders/NumberSchemaBuilder.test.ts +0 -493
  54. package/src/builders/NumberSchemaBuilder.ts +0 -789
  55. package/src/builders/ObjectSchemaBuilder.test.ts +0 -657
  56. package/src/builders/ObjectSchemaBuilder.ts +0 -794
  57. package/src/builders/SchemaBuilder.test.ts +0 -73
  58. package/src/builders/SchemaBuilder.ts +0 -135
  59. package/src/builders/StringSchemaBuilder.test.ts +0 -318
  60. package/src/builders/StringSchemaBuilder.ts +0 -392
  61. package/src/builders/UnionSchemaBuilder.test.ts +0 -162
  62. package/src/builders/UnionSchemaBuilder.ts +0 -154
  63. package/src/defaultSchemas.ts +0 -44
  64. package/src/index.ts +0 -66
  65. package/src/schema.ts +0 -827
  66. package/src/schemaRegistry.builders.test.ts +0 -1393
  67. package/src/schemaRegistry.test.ts +0 -118
  68. package/src/schemaRegistry.ts +0 -461
  69. package/src/validators/validateArray.ts +0 -76
  70. package/src/validators/validateBoolean.ts +0 -36
  71. package/src/validators/validateFunction.ts +0 -25
  72. package/src/validators/validateNumber.ts +0 -82
  73. package/src/validators/validateObject.ts +0 -119
  74. package/src/validators/validateString.ts +0 -59
  75. package/src/validators/validateUnion.ts +0 -36
  76. package/tsconfig.json +0 -16
@@ -1,90 +1,150 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.boolean = exports.BooleanSchemaBuilder = void 0;
4
- const SchemaBuilder_js_1 = require("./SchemaBuilder.js");
5
- const defaultSchemas_js_1 = require("../defaultSchemas.js");
6
- class BooleanSchemaBuilder extends SchemaBuilder_js_1.SchemaBuilder {
7
- type = 'boolean';
8
- get _schema() {
9
- return Object.assign({
10
- type: this.type
11
- }, this.getCommonSchema(), typeof this._equals !== 'undefined' ? { equals: this._equals } : {});
12
- }
13
- clone() {
14
- return BooleanSchemaBuilder.create(this._schema);
15
- }
16
- static create(obj) {
17
- return new BooleanSchemaBuilder(obj);
1
+ import { SchemaBuilder } from './SchemaBuilder.js';
2
+ /**
3
+ * Similar to `boolean` type in TypeScript.
4
+ * Allows to define a schema for a boolean value. It can be required or optional.
5
+ * It can be restricted to be equal to a certain value.
6
+ *
7
+ * **NOTE** this class is exported only to give opportunity to extend it
8
+ * by inheriting. It is not recommended to create an instance of this class
9
+ * directly. Use {@link boolean | boolean()} function instead.
10
+ *
11
+ * @example ```ts
12
+ * const schema = boolean().equals(true);
13
+ * const result = await schema.validate(true);
14
+ * // result.valid === true
15
+ * // result.object === true
16
+ * ```
17
+ * @example ```ts
18
+ * const schema = boolean().equals(false);
19
+ * const result = await schema.validate(true);
20
+ * // result.valid === false
21
+ * // result.errors[0].message === 'is expected to be equal to 'false''
22
+ * ```
23
+ * @example ```ts
24
+ * const schema = boolean().equals(true).optional();
25
+ * const result = await schema.validate(undefined);
26
+ * // result.valid === true
27
+ * // result.object === undefined
28
+ * ```
29
+ *
30
+ * @see {@link boolean}
31
+ */
32
+ export class BooleanSchemaBuilder extends SchemaBuilder {
33
+ #equalsTo;
34
+ static create(props) {
35
+ return new BooleanSchemaBuilder({
36
+ type: 'boolean',
37
+ ...props
38
+ });
18
39
  }
19
- constructor(obj) {
20
- super(obj);
21
- if (typeof obj === 'object' && obj) {
22
- if (typeof obj.equals !== 'undefined') {
23
- this._equals = obj.equals;
24
- }
25
- }
26
- else {
27
- const defaultSchema = defaultSchemas_js_1.defaultSchemas['boolean'];
28
- this.isRequired = defaultSchema.isRequired;
29
- this.isNullable = defaultSchema.isNullable;
40
+ constructor(props) {
41
+ super(props);
42
+ if (typeof props.equalsTo === 'boolean' ||
43
+ typeof props.equalsTo === 'undefined') {
44
+ this.#equalsTo = props.equalsTo;
30
45
  }
31
46
  }
32
- _equals;
33
- equals(val) {
34
- if (this._equals === val) {
35
- return this;
36
- }
37
- return BooleanSchemaBuilder.create({
38
- ...this._schema,
39
- equals: val
47
+ introspect() {
48
+ return {
49
+ ...super.introspect(),
50
+ /**
51
+ * If set, restrict object to be equal to a certain value.
52
+ */
53
+ equalsTo: this.#equalsTo
54
+ };
55
+ }
56
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
57
+ hasType(notUsed) {
58
+ return this.createFromProps({
59
+ ...this.introspect()
40
60
  });
41
61
  }
42
- clearEqualsTo() {
43
- if (typeof this._equals === 'undefined') {
44
- return this;
45
- }
46
- return BooleanSchemaBuilder.create({
47
- ...this._schema,
48
- equals: undefined
62
+ clearHasType() {
63
+ return this.createFromProps({
64
+ ...this.introspect()
49
65
  });
50
66
  }
51
- optional() {
52
- if (this.isRequired === false) {
53
- return this;
67
+ /**
68
+ * Performs validion of the schema over `object`. Basically runs
69
+ * validators, preprocessors and checks for required (if schema is not optional).
70
+ * @param context Optional `ValidationContext` settings.
71
+ */
72
+ async validate(object, context) {
73
+ const superResult = await super.preValidate(object, context);
74
+ const { valid, context: prevalidationContext, transaction: preValidationTransaction, errors } = superResult;
75
+ const { path } = prevalidationContext;
76
+ if (!valid) {
77
+ return { valid, errors };
54
78
  }
55
- return BooleanSchemaBuilder.create({
56
- ...this._schema,
57
- isRequired: false
58
- });
79
+ const { object: { validatedObject: objToValidate } } = preValidationTransaction;
80
+ if ((typeof objToValidate === 'undefined' || objToValidate === null) &&
81
+ this.isRequired === false) {
82
+ return {
83
+ valid: true,
84
+ object: objToValidate
85
+ };
86
+ }
87
+ if (typeof objToValidate !== 'boolean') {
88
+ return {
89
+ valid: false,
90
+ errors: [
91
+ {
92
+ message: 'expected to be boolean',
93
+ path: path
94
+ }
95
+ ]
96
+ };
97
+ }
98
+ if (typeof this.#equalsTo !== 'undefined' &&
99
+ objToValidate !== this.#equalsTo) {
100
+ return {
101
+ valid: false,
102
+ errors: [
103
+ {
104
+ message: `is expected to be equal to '${this.#equalsTo}'`,
105
+ path: path
106
+ }
107
+ ]
108
+ };
109
+ }
110
+ return {
111
+ valid: true,
112
+ object: objToValidate
113
+ };
114
+ }
115
+ createFromProps(props) {
116
+ return BooleanSchemaBuilder.create(props);
59
117
  }
60
118
  required() {
61
- if (this.isRequired === true) {
62
- return this;
63
- }
64
- return BooleanSchemaBuilder.create({
65
- ...this._schema,
66
- isRequired: true
67
- });
119
+ return super.required();
68
120
  }
69
- nullable() {
70
- if (this.isNullable === true) {
71
- return this;
72
- }
73
- return BooleanSchemaBuilder.create({
74
- ...this._schema,
75
- isNullable: true
121
+ optional() {
122
+ return super.optional();
123
+ }
124
+ /**
125
+ * Restricts object to be equal to `value`.
126
+ */
127
+ equals(value) {
128
+ if (typeof value !== 'boolean')
129
+ throw new Error('boolean expected');
130
+ return this.createFromProps({
131
+ ...this.introspect(),
132
+ equalsTo: value
76
133
  });
77
134
  }
78
- notNullable() {
79
- if (this.isNullable === false) {
80
- return this;
81
- }
82
- return BooleanSchemaBuilder.create({
83
- ...this._schema,
84
- isNullable: false
135
+ /**
136
+ * Removes a `value` defeined by `equals()` call.
137
+ */
138
+ clearEquals() {
139
+ return this.createFromProps({
140
+ ...this.introspect(),
141
+ equalsTo: undefined
85
142
  });
86
143
  }
87
144
  }
88
- exports.BooleanSchemaBuilder = BooleanSchemaBuilder;
89
- const boolean = () => BooleanSchemaBuilder.create();
90
- exports.boolean = boolean;
145
+ /**
146
+ * Creates a `boolean` schema.
147
+ */
148
+ export const boolean = () => BooleanSchemaBuilder.create({
149
+ isRequired: true
150
+ });
@@ -0,0 +1,177 @@
1
+ import { Preprocessor, SchemaBuilder, ValidationResult, ValidationContext, Validator } from './SchemaBuilder.js';
2
+ type DateSchemaBuilderCreateProps<T = Date, R extends boolean = true> = Partial<ReturnType<DateSchemaBuilder<T, R>['introspect']>>;
3
+ /**
4
+ * Allows to create Date schema. It can be required or optional.
5
+ * It can be restricted to be: equal to a certain value, in future, in past, in a certain range.
6
+ * Supports parsing from JSON string and UNIX epoch (using preprocessors).
7
+ *
8
+ * **NOTE** this class is exported only to give opportunity to extend it
9
+ * by inheriting. It is not recommended to create an instance of this class
10
+ * directly. Use {@link date | date()} function instead.
11
+ *
12
+ * @example ```ts
13
+ * const date = new Date(2020, 0, 2);
14
+ * const schema = date().min(new Date(2020, 0, 1));
15
+ * const result = await schema.validate(date);
16
+ * // result.valid === true
17
+ * // result.object === date
18
+ * ```
19
+ *
20
+ * @example ```ts
21
+ * const schema = date();
22
+ * const result = await schema.validate('2020-01-01');
23
+ * // result.valid === false
24
+ * // result.errors[0].message === 'is expected to be a date'
25
+ * ```
26
+ *
27
+ * @example ```ts
28
+ * const schema = date().parseFromJson();
29
+ * const result = await schema.validate('2020-01-01T00:00:00.000Z');
30
+ * // result.valid === true
31
+ * // result.object is equal to corresponding Date object
32
+ * ```
33
+ *
34
+ * @example ```ts
35
+ * const schema = date().parseFromEpoch();
36
+ * const result = await schema.validate(1577836800000);
37
+ * // result.valid === true
38
+ * // result.object is equal to corresponding Date object
39
+ * ```
40
+ *
41
+ * @see {@link date}
42
+ */
43
+ export declare class DateSchemaBuilder<TResult = Date, TRequired extends boolean = true> extends SchemaBuilder<TResult, TRequired> {
44
+ #private;
45
+ static create(props: DateSchemaBuilderCreateProps): DateSchemaBuilder<Date, true>;
46
+ private constructor();
47
+ introspect(): {
48
+ /**
49
+ * Min valid value (if defined).
50
+ */
51
+ min: Date | undefined;
52
+ /**
53
+ * Max valid value (if defined).
54
+ */
55
+ max: Date | undefined;
56
+ /**
57
+ * Make sure that date is in future. `false` by default.
58
+ */
59
+ ensureIsInFuture: boolean;
60
+ /**
61
+ * Make sure that date is in past. `false` by default.
62
+ */
63
+ ensureIsInPast: boolean;
64
+ /**
65
+ * If set, restrict date to be equal to a certain value.
66
+ */
67
+ equalsTo: Date | undefined;
68
+ /**
69
+ * If set, schema will try to parse date from the UNIX epoch (number).
70
+ * `false` by default.
71
+ */
72
+ parseFromEpoch: boolean;
73
+ /**
74
+ * If set, schema will try to parse date from JSON string.
75
+ * `false` by default.
76
+ */
77
+ parseFromJson: boolean;
78
+ /**
79
+ * Array of preprocessor functions
80
+ */
81
+ preprocessors: Preprocessor<TResult>[];
82
+ /**
83
+ * Array of validator functions
84
+ */
85
+ validators: Validator<TResult>[];
86
+ type: string;
87
+ isRequired: boolean;
88
+ };
89
+ /**
90
+ * @hidden
91
+ */
92
+ hasType<T>(notUsed?: T): DateSchemaBuilder<T, true>;
93
+ /**
94
+ * @hidden
95
+ */
96
+ clearHasType(): DateSchemaBuilder<Date, TRequired>;
97
+ /**
98
+ * Performs validion of Date schema over `object`.
99
+ * @param context Optional `ValidationContext` settings.
100
+ */
101
+ validate(object: TResult, context?: ValidationContext): Promise<ValidationResult<TResult>>;
102
+ /**
103
+ * @hidden
104
+ */
105
+ protected createFromProps<T, TReq extends boolean>(props: DateSchemaBuilderCreateProps<T, TReq>): this;
106
+ /**
107
+ * Restricts Date to be equal to `value`.
108
+ */
109
+ equals<T extends Date>(value: T): DateSchemaBuilder<T, TRequired>;
110
+ /**
111
+ * Clears `equals()` call.
112
+ */
113
+ clearEquals(): DateSchemaBuilder<Date, TRequired>;
114
+ /**
115
+ * @hidden
116
+ */
117
+ required(): DateSchemaBuilder<TResult, true>;
118
+ /**
119
+ * @hidden
120
+ */
121
+ optional(): DateSchemaBuilder<TResult, false>;
122
+ /**
123
+ * Accept only dates in the future.
124
+ */
125
+ isInFuture(): DateSchemaBuilder<TResult, TRequired>;
126
+ /**
127
+ * Cancel `isInFuture()` call.
128
+ */
129
+ clearIsInFuture(): DateSchemaBuilder<TResult, TRequired>;
130
+ /**
131
+ * Accept only dates in the past.
132
+ */
133
+ isInPast(): DateSchemaBuilder<TResult, TRequired>;
134
+ /**
135
+ * Cancel `isInPast()` call.
136
+ */
137
+ clearIsInPast(): DateSchemaBuilder<TResult, TRequired>;
138
+ /**
139
+ * Set minimal valid Date value for schema.
140
+ */
141
+ min(minValue: Date): DateSchemaBuilder<TResult, TRequired>;
142
+ /**
143
+ * Clear `min()` call.
144
+ */
145
+ clearMin(): DateSchemaBuilder<TResult, TRequired>;
146
+ /**
147
+ * Set maximal valid Date value for schema.
148
+ */
149
+ max(maxValue: Date): DateSchemaBuilder<TResult, TRequired>;
150
+ /**
151
+ * Clear `max()` call.
152
+ */
153
+ clearMax(): DateSchemaBuilder<TResult, TRequired>;
154
+ /**
155
+ * Accepts JSON string as a valid Date.
156
+ * String must be in ISO format and will be parsed using `JSON.parse()`.
157
+ */
158
+ acceptJsonString(): DateSchemaBuilder<TResult, TRequired>;
159
+ /**
160
+ * Cancel `acceptJsonString()` call.
161
+ */
162
+ doNotAcceptJsonString(): DateSchemaBuilder<TResult, TRequired>;
163
+ /**
164
+ * Accepts epoch number as a valid Date.
165
+ * Epoch number will be parsed using `new Date(epoch)`.
166
+ */
167
+ acceptEpoch(): DateSchemaBuilder<TResult, TRequired>;
168
+ /**
169
+ * Cancel `acceptEpoch()` call.
170
+ */
171
+ doNotAcceptEpoch(): DateSchemaBuilder<TResult, TRequired>;
172
+ }
173
+ /**
174
+ * Creates a Date schema.
175
+ */
176
+ export declare const date: () => DateSchemaBuilder<Date, true>;
177
+ export {};