valgen 3.2.1 → 4.0.0-alpha.3

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 (143) hide show
  1. package/CHANGELOG.md +6 -0
  2. package/README.md +12 -7
  3. package/cjs/core/constants.js +5 -0
  4. package/cjs/core/context.js +65 -0
  5. package/cjs/core/index.js +21 -0
  6. package/cjs/core/types.js +2 -0
  7. package/cjs/core/validation-error.js +11 -0
  8. package/cjs/core/validator.js +61 -0
  9. package/cjs/helpers/object.utils.js +19 -0
  10. package/cjs/helpers/string.utils.js +9 -0
  11. package/cjs/index.js +18 -0
  12. package/cjs/package.json +3 -0
  13. package/cjs/rules/index.js +39 -0
  14. package/cjs/rules/is-any.js +12 -0
  15. package/cjs/rules/is-array.js +38 -0
  16. package/cjs/rules/is-bigint.js +21 -0
  17. package/cjs/rules/is-boolean.js +30 -0
  18. package/cjs/rules/is-date.js +63 -0
  19. package/cjs/rules/is-empty.js +68 -0
  20. package/cjs/rules/is-enum.js +30 -0
  21. package/cjs/rules/is-integer.js +26 -0
  22. package/cjs/rules/is-matches.js +24 -0
  23. package/cjs/rules/is-null.js +40 -0
  24. package/cjs/rules/is-number.js +26 -0
  25. package/cjs/rules/is-object-id.js +28 -0
  26. package/cjs/rules/is-object.js +103 -0
  27. package/cjs/rules/is-record.js +41 -0
  28. package/cjs/rules/is-string.js +79 -0
  29. package/cjs/rules/is-tuple.js +32 -0
  30. package/cjs/rules/length.js +41 -0
  31. package/cjs/rules/optional.js +44 -0
  32. package/cjs/rules/pipe.js +43 -0
  33. package/cjs/rules/range.js +89 -0
  34. package/cjs/rules/string-formats.js +296 -0
  35. package/cjs/rules/union.js +31 -0
  36. package/cjs/rules/utilities.js +31 -0
  37. package/esm/core/constants.js +2 -0
  38. package/esm/core/context.js +61 -0
  39. package/esm/core/index.js +5 -0
  40. package/esm/core/types.js +1 -0
  41. package/esm/core/validation-error.js +7 -0
  42. package/esm/core/validator.js +56 -0
  43. package/esm/helpers/object.utils.js +14 -0
  44. package/esm/helpers/string.utils.js +5 -0
  45. package/esm/index.js +2 -0
  46. package/esm/rules/index.js +23 -0
  47. package/esm/rules/is-any.js +8 -0
  48. package/esm/rules/is-array.js +34 -0
  49. package/esm/rules/is-bigint.js +17 -0
  50. package/esm/rules/is-boolean.js +26 -0
  51. package/esm/rules/is-date.js +55 -0
  52. package/esm/rules/is-empty.js +63 -0
  53. package/esm/rules/is-enum.js +26 -0
  54. package/esm/rules/is-integer.js +22 -0
  55. package/esm/rules/is-matches.js +20 -0
  56. package/esm/rules/is-null.js +34 -0
  57. package/esm/rules/is-number.js +22 -0
  58. package/esm/rules/is-object-id.js +21 -0
  59. package/esm/rules/is-object.js +99 -0
  60. package/esm/rules/is-record.js +37 -0
  61. package/esm/rules/is-string.js +70 -0
  62. package/esm/rules/is-tuple.js +28 -0
  63. package/esm/rules/length.js +35 -0
  64. package/esm/rules/optional.js +38 -0
  65. package/esm/rules/pipe.js +38 -0
  66. package/esm/rules/range.js +81 -0
  67. package/esm/rules/string-formats.js +266 -0
  68. package/esm/rules/union.js +27 -0
  69. package/esm/rules/utilities.js +26 -0
  70. package/package.json +33 -37
  71. package/typings/core/constants.d.ts +2 -0
  72. package/typings/core/context.d.ts +26 -0
  73. package/typings/core/index.d.ts +6 -0
  74. package/typings/core/types.d.ts +18 -0
  75. package/typings/core/validation-error.d.ts +5 -0
  76. package/typings/core/validator.d.ts +18 -0
  77. package/typings/helpers/object.utils.d.ts +2 -0
  78. package/typings/helpers/string.utils.d.ts +1 -0
  79. package/typings/index.d.ts +2 -0
  80. package/typings/rules/index.d.ts +23 -0
  81. package/typings/rules/is-any.d.ts +5 -0
  82. package/typings/rules/is-array.d.ts +7 -0
  83. package/typings/rules/is-bigint.d.ts +7 -0
  84. package/typings/rules/is-boolean.d.ts +7 -0
  85. package/typings/rules/is-date.d.ts +19 -0
  86. package/typings/rules/is-empty.d.ts +13 -0
  87. package/typings/rules/is-enum.d.ts +9 -0
  88. package/typings/rules/is-integer.d.ts +7 -0
  89. package/typings/rules/is-matches.d.ts +9 -0
  90. package/typings/rules/is-null.d.ts +16 -0
  91. package/typings/rules/is-number.d.ts +7 -0
  92. package/typings/rules/is-object-id.d.ts +10 -0
  93. package/typings/rules/is-object.d.ts +22 -0
  94. package/typings/rules/is-record.d.ts +7 -0
  95. package/typings/rules/is-string.d.ts +42 -0
  96. package/typings/rules/is-tuple.d.ts +27 -0
  97. package/typings/rules/length.d.ts +21 -0
  98. package/typings/rules/optional.d.ts +17 -0
  99. package/typings/rules/pipe.d.ts +11 -0
  100. package/typings/rules/range.d.ts +48 -0
  101. package/typings/rules/string-formats.d.ts +140 -0
  102. package/typings/rules/union.d.ts +5 -0
  103. package/typings/rules/utilities.d.ts +11 -0
  104. package/lib/ArrayType.d.ts +0 -5
  105. package/lib/ArrayType.js +0 -43
  106. package/lib/DataType.d.ts +0 -25
  107. package/lib/DataType.js +0 -214
  108. package/lib/ObjectType.d.ts +0 -5
  109. package/lib/ObjectType.js +0 -78
  110. package/lib/SchemaError.d.ts +0 -3
  111. package/lib/SchemaError.js +0 -17
  112. package/lib/UnionType.d.ts +0 -5
  113. package/lib/UnionType.js +0 -54
  114. package/lib/Valgen.d.ts +0 -88
  115. package/lib/Valgen.js +0 -289
  116. package/lib/ValidationError.d.ts +0 -2
  117. package/lib/ValidationError.js +0 -4
  118. package/lib/factories/AnyFactory.d.ts +0 -28
  119. package/lib/factories/AnyFactory.js +0 -73
  120. package/lib/factories/ArrayFactory.d.ts +0 -16
  121. package/lib/factories/ArrayFactory.js +0 -148
  122. package/lib/factories/Base64Factory.d.ts +0 -12
  123. package/lib/factories/Base64Factory.js +0 -31
  124. package/lib/factories/BooleanFactory.d.ts +0 -12
  125. package/lib/factories/BooleanFactory.js +0 -49
  126. package/lib/factories/DateFactory.d.ts +0 -40
  127. package/lib/factories/DateFactory.js +0 -239
  128. package/lib/factories/FunctionFactory.d.ts +0 -12
  129. package/lib/factories/FunctionFactory.js +0 -28
  130. package/lib/factories/IntegerFactory.d.ts +0 -14
  131. package/lib/factories/IntegerFactory.js +0 -33
  132. package/lib/factories/NilFactory.d.ts +0 -4
  133. package/lib/factories/NilFactory.js +0 -20
  134. package/lib/factories/NumberFactory.d.ts +0 -36
  135. package/lib/factories/NumberFactory.js +0 -178
  136. package/lib/factories/ObjectFactory.d.ts +0 -38
  137. package/lib/factories/ObjectFactory.js +0 -326
  138. package/lib/factories/StringFactory.d.ts +0 -16
  139. package/lib/factories/StringFactory.js +0 -94
  140. package/lib/factories/UnionFactory.d.ts +0 -13
  141. package/lib/factories/UnionFactory.js +0 -62
  142. package/lib/index.d.ts +0 -19
  143. package/lib/index.js +0 -37
package/lib/Valgen.js DELETED
@@ -1,289 +0,0 @@
1
- const {DataType} = require('./DataType');
2
- const {ObjectType} = require('./ObjectType');
3
- const {ArrayType} = require('./ArrayType');
4
- const {UnionType} = require('./UnionType');
5
- const {AnyFactory} = require('./factories/AnyFactory');
6
- const {BooleanFactory} = require('./factories/BooleanFactory');
7
- const {NumberFactory} = require('./factories/NumberFactory');
8
- const {IntegerFactory} = require('./factories/IntegerFactory');
9
- const {StringFactory} = require('./factories/StringFactory');
10
- const {ArrayFactory} = require('./factories/ArrayFactory');
11
- const {ObjectFactory} = require('./factories/ObjectFactory');
12
- const {UnionFactory} = require('./factories/UnionFactory');
13
- const {DateFactory} = require('./factories/DateFactory');
14
- const {NilFactory} = require('./factories/NilFactory');
15
- const {FunctionFactory} = require('./factories/FunctionFactory');
16
- const {Base64Factory} = require('./factories/Base64Factory');
17
- const {SchemaError} = require('./SchemaError');
18
-
19
- const SQUARE_BRACKETS_PATTERN = /^\[([^\]]+)]$/;
20
-
21
- class Valgen {
22
-
23
- constructor(options = {}) {
24
- this._instances = {};
25
- this._lookupSchemas = {};
26
- this._stacks = [];
27
- this._idSeq = 0;
28
- this.baseTypes = {};
29
- this.defaultType = options.defaultType;
30
- this.schemaLookup = options.schemaLookup;
31
- this.schemas = {};
32
- this.throwOnError = options.throwOnError;
33
- this.baseTypes.object = new ObjectType(this, 'object', new ObjectFactory());
34
- this.baseTypes.array = new ArrayType(this, 'array', new ArrayFactory());
35
- this.baseTypes.union = new UnionType(this, 'union', new UnionFactory());
36
- this.define('any', new AnyFactory());
37
- this.define('boolean', new BooleanFactory());
38
- this.define('number', new NumberFactory());
39
- this.define('string', new StringFactory());
40
- this.define('integer', new IntegerFactory());
41
- this.define('nil', new NilFactory());
42
- this.define('function', new FunctionFactory());
43
- this.define('base64', new Base64Factory());
44
- this.define('datetime', new DateFactory({
45
- dateFormats: {},
46
- format: 'datetime'
47
- }));
48
- this.define('date', new DateFactory({
49
- dateFormats: {},
50
- format: 'date'
51
- }));
52
- this.define('time', new DateFactory({
53
- dateFormats: {},
54
- format: 'time'
55
- }));
56
- }
57
-
58
- addSchema(name, schema) {
59
- if (arguments.length <= 1) {
60
- if (typeof name !== 'object')
61
- throw new TypeError(`You must provide object instance as first argument.`);
62
- schema = name;
63
- name = schema.name;
64
- } else if (typeof schema === 'string')
65
- schema = this._parseTypeName(schema);
66
- else {
67
- if (typeof schema !== 'object')
68
- throw new TypeError(`Second argument must be an object or string.`);
69
- schema = {...schema, name};
70
- }
71
-
72
- if (!(name && typeof name === 'string'))
73
- throw new Error('You must provide type name');
74
-
75
- if (this.schemas[schema.name])
76
- throw new Error(`Schema "${schema.name}" already defined.`);
77
-
78
- this.schemas[name] = schema;
79
- }
80
-
81
- clearCache() {
82
- this._instances = {};
83
- this._lookupSchemas = {};
84
- Object.keys(this.baseTypes).forEach(k => this.baseTypes[k]._fnCache = {});
85
- }
86
-
87
- define(typeName, factory) {
88
- if (!factory)
89
- delete this.baseTypes[typeName];
90
- return this.baseTypes[typeName] = new DataType(this, typeName, factory);
91
- }
92
-
93
- generate(schema, options = {}) {
94
- return this.getType(schema)
95
- .generate(options);
96
- }
97
-
98
- normalizeSchema(schema) {
99
- const baseTypeName = this._getBaseTypeName(schema);
100
- const baseType = this.baseTypes[baseTypeName];
101
- if (!baseType)
102
- throw new Error(`Unable to determine base type.`);
103
-
104
- if (typeof schema === 'string') {
105
- schema = this._parseTypeName(schema);
106
- } else schema = {...schema};
107
-
108
- if (typeof schema === 'string')
109
- schema = {type: schema};
110
- else {
111
- if (schema.type) {
112
- if (Array.isArray(schema.type)) {
113
- schema.type = schema.type.map(t => {
114
- if (typeof t === 'string')
115
- return this._parseTypeName(t);
116
- return this.normalizeSchema(t);
117
- });
118
- if (schema.type.length <= 1)
119
- schema.type = schema.type[0];
120
- } else {
121
- const x = this.normalizeSchema(schema.type);
122
- if (x !== schema.type) {
123
- Object.assign(schema, x);
124
- }
125
- }
126
- }
127
- if (!schema.type)
128
- schema.type = baseTypeName;
129
- }
130
-
131
- return baseType.normalizeSchema(schema);
132
- }
133
-
134
- getType(schemaOrName) {
135
- if (!schemaOrName)
136
- throw new TypeError('Invalid argument');
137
-
138
- if (schemaOrName instanceof DataType)
139
- return schemaOrName;
140
-
141
- let name;
142
- let cacheId;
143
- let schema;
144
- let baseType;
145
- if (typeof schemaOrName === 'string') {
146
- schema = this._parseTypeName(schemaOrName);
147
- if (typeof schema === 'string') {
148
- name = schema;
149
- // Return previously cached type
150
- const t = this._instances[name];
151
- if (t) return t;
152
-
153
- // Check if it is an internal type
154
- baseType = this.baseTypes[name];
155
- if (!baseType) {
156
- // Lookup for schema by name
157
- schema = this.schemas[name] || this._lookupForSchema(name);
158
- if (!schema || schema === name)
159
- throw new TypeError(`Unknown type schema "${name}"`);
160
- if (typeof schema === 'string')
161
- schema = {name, type: schema};
162
- }
163
-
164
- } else
165
- name = schema.name;
166
- cacheId = name;
167
- } else {
168
- schema = schemaOrName;
169
- name = schema.name;
170
- }
171
-
172
- const stack = [name || '(anonymous)'];
173
- this._stacks.push(stack);
174
- try {
175
- if (!baseType) {
176
- const baseTypeName = this._getBaseTypeName(schema);
177
- baseType = this.baseTypes[baseTypeName];
178
- }
179
- const instance = {id: ++this._idSeq, name};
180
- if (cacheId)
181
- this._instances[cacheId] = instance;
182
- baseType.create(instance, schema);
183
- if (baseType.factory.create)
184
- baseType.factory.create(instance);
185
- return instance;
186
- } catch (e) {
187
- delete this._instances[name];
188
- if (e instanceof SchemaError)
189
- throw e;
190
- throw new SchemaError(e, stack);
191
- } finally {
192
- this._stacks.pop();
193
- }
194
- }
195
-
196
- setOption(key, v) {
197
- const m = key.match(/^([^.]+)(?:\.(.+))?$/);
198
- if (m) {
199
- const t = this.baseTypes[m[1]];
200
- if (!t)
201
- return;
202
- if (v === undefined)
203
- delete t.options[m[2]];
204
- else
205
- t.options[m[2]] = v;
206
- }
207
- }
208
-
209
- _lookupForSchema(name) {
210
- let schema = this.schemas[name] || this._lookupSchemas[name];
211
- if (schema)
212
- return schema;
213
- schema = this.schemaLookup && this.schemaLookup(name);
214
- if (schema)
215
- return this._lookupSchemas[name] = schema;
216
- }
217
-
218
- _getBaseTypeName(schema) {
219
- const stack = [];
220
- const getTypeName = (schema) => {
221
- if (typeof schema === 'string')
222
- schema = this._parseTypeName(schema);
223
-
224
- if (typeof schema === 'string') {
225
- if (stack.includes(schema))
226
- throw new Error('Circular reference detected');
227
- const t = this.baseTypes[schema] || this._instances[schema];
228
- if (t)
229
- return t.typeName;
230
- const sch = this._lookupForSchema(schema);
231
- if (!sch || sch === schema)
232
- throw new Error(`Unknown type "${schema}"`);
233
- stack.push(schema);
234
- return getTypeName(sch);
235
- }
236
- let h = (Array.isArray(schema.type) ? schema.type[0] : schema.type);
237
- if (!h) {
238
- if (schema.items)
239
- h = 'array';
240
- else if (schema.properties)
241
- h = 'object';
242
- else if (schema.anyOf)
243
- h = 'union';
244
- else h = this.defaultType || 'any';
245
- }
246
- return getTypeName(h);
247
- };
248
- return getTypeName(schema);
249
- }
250
-
251
- _parseTypeName(v) {
252
- let m = v.match(SQUARE_BRACKETS_PATTERN);
253
- if (m)
254
- v = m[1];
255
- if (v.includes(',')) {
256
- return {
257
- type: v.split(/\s*,\s*/).map(x => this._parseTypeName(x))
258
- };
259
- }
260
- if (v.includes('|')) {
261
- return {
262
- type: 'union',
263
- anyOf: v.split(/\s*\|\s*/).map(x => this._parseTypeName(x))
264
- };
265
- }
266
- if (v.endsWith('[]')) {
267
- const n = this._parseTypeName(v.substring(0, v.length - 2));
268
- return {
269
- type: 'array',
270
- items: n
271
- };
272
- }
273
- if (v.endsWith('{}')) {
274
- const n = this._parseTypeName(v.substring(0, v.length - 2));
275
- return {
276
- type: 'object',
277
- additionalProperties: n
278
- };
279
- }
280
- return v;
281
- }
282
-
283
- get _stack() {
284
- return this._stacks[this._stacks.length - 1];
285
- }
286
-
287
- }
288
-
289
- module.exports = {Valgen};
@@ -1,2 +0,0 @@
1
- export class ValidationError extends Error {
2
- }
@@ -1,4 +0,0 @@
1
- class ValidationError extends Error {
2
- }
3
-
4
- module.exports = ValidationError;
@@ -1,28 +0,0 @@
1
- import {Valgen} from "../Valgen";
2
- import {DataType} from "../DataType";
3
-
4
- export namespace AnyFactory {
5
- export interface FunctionData {
6
- code: string;
7
- variables?: {
8
- [index: string]: any;
9
- };
10
- }
11
- export interface TypeSchema extends Valgen.ITypeSchema {
12
- default?: any;
13
- }
14
- }
15
-
16
- export class AnyFactory implements Valgen.ITypeFactory {
17
-
18
- schema: AnyFactory.TypeSchema;
19
- options: any;
20
-
21
- generate(type: DataType, options?: Valgen.IGenerateOptions): Valgen.ValidateFunction;
22
-
23
- normalizeAttribute: (attr: string, value: any) => any;
24
-
25
- normalizeCompileOptions(options?: Valgen.IGenerateOptions): Valgen.IGenerateOptions;
26
-
27
- protected _generateValidationCode(dataType: DataType, options: Valgen.IGenerateOptions): AnyFactory.FunctionData;
28
- }
@@ -1,73 +0,0 @@
1
- 'use strict';
2
-
3
- const {coerceToBoolean, coerceToString} = require('putil-varhelpers');
4
-
5
- const Failed = Symbol.for('Failed');
6
-
7
- /**
8
- *
9
- * @class AnyFactory
10
- */
11
- class AnyFactory {
12
-
13
- normalizeCompileOptions(options) {
14
- return {
15
- displayName: coerceToString(options.displayName),
16
- resolvePromises: coerceToBoolean(options.resolvePromises),
17
- throwOnError: coerceToBoolean(options.throwOnError)
18
- };
19
- }
20
-
21
- normalizeAttribute(attr, v) {
22
- switch (attr) {
23
- case 'default':
24
- return v;
25
- }
26
- }
27
-
28
- generate(dataType, options) {
29
- const defaultValue = dataType.get('default');
30
- const varNames = ['dataType', 'Failed', 'defaultValue'];
31
- const varValues = [dataType, Failed, defaultValue];
32
- const o = this._generateValidationCode(dataType, options);
33
- /* istanbul ignore else */
34
- if (o.variables)
35
- for (const n of Object.keys(o.variables)) {
36
- varNames.push(n);
37
- varValues.push(o.variables[n]);
38
- }
39
- const code = `return (value, ctx) => {
40
- ${defaultValue !== undefined ?
41
- 'if (value == null) value = defaultValue;' : ''}
42
- ${o.code}
43
- return value;
44
- }`;
45
- return new Function(...varNames, code)(...varValues);
46
- }
47
-
48
- _generateValidationCode(dataType, options) {
49
- const data = {code: '', variables: {}};
50
- data.variables.name = options.displayName || dataType.name;
51
-
52
- data.code += `
53
- if (value == null) return value;
54
- const typeCheck = ctx && ctx.typeCheck;
55
- `;
56
-
57
- const enumValues = dataType.get('enum');
58
- if (enumValues) {
59
- data.variables.enums = new Set(enumValues);
60
- data.code += `
61
- if (!enums.has(value))
62
- return typeCheck ? Failed : ctx.logError({
63
- message: 'Value must be a one of the enumerated values.',
64
- errorType: 'invalid-enum-value'
65
- });`;
66
- }
67
-
68
- return data;
69
- }
70
-
71
- }
72
-
73
- module.exports = {AnyFactory};
@@ -1,16 +0,0 @@
1
- import {AnyFactory} from './AnyFactory';
2
- import {Valgen} from '../Valgen';
3
-
4
- export namespace ArrayFactory {
5
- export interface ITypeSchema extends Valgen.ITypeSchema {
6
- default?: any[];
7
- items?: string | Valgen.ITypeSchema;
8
- minItems?: number;
9
- maxItems?: number;
10
- }
11
- }
12
-
13
-
14
- export class ArrayFactory extends AnyFactory {
15
- schema: ArrayFactory.ITypeSchema;
16
- }
@@ -1,148 +0,0 @@
1
- 'use strict';
2
- const {AnyFactory} = require('./AnyFactory');
3
- const {coerceToInt, coerceToBoolean, coerceToArray, coalesce} = require('putil-varhelpers');
4
-
5
- class ArrayFactory extends AnyFactory {
6
-
7
- normalizeAttribute(attr, v) {
8
- switch (attr) {
9
- case 'default':
10
- return coerceToArray(v);
11
- case 'minItems':
12
- case 'maxItems':
13
- return coerceToInt(v);
14
- case 'uniqueItems':
15
- return coerceToBoolean(v);
16
- case 'items':
17
- return v;
18
- }
19
- return super.normalizeAttribute(attr, v);
20
- }
21
-
22
- set(target, attr, v, info) {
23
- switch (attr) {
24
- case 'default':
25
- target.default = coerceToArray(v);
26
- return;
27
- case 'items': {
28
- target.items = !v ? v :
29
- v instanceof AnyFactory ? /* istanbul ignore next*/ v :
30
- info.library.getType(v);
31
- return;
32
- }
33
- case 'minItems':
34
- case 'maxItems': {
35
- target[attr] = coerceToInt(v);
36
- return;
37
- }
38
- case 'uniqueItems':
39
- target[attr] = coerceToBoolean(v);
40
- return;
41
- }
42
- super.set(target, attr, v, info);
43
- }
44
-
45
- normalizeCompileOptions(options) {
46
- const o = super.normalizeCompileOptions(options);
47
- o.strictFormat = coerceToBoolean(options.strictFormat);
48
- o.coerceTypes = coerceToBoolean(options.coerceTypes);
49
- o.maxArrayErrors = coerceToInt(options.maxArrayErrors);
50
- return o;
51
- }
52
-
53
- _generateValidationCode(dataType, options) {
54
- const data = super._generateValidationCode(dataType, options);
55
- const minItems = coalesce(dataType.get('minItems'), dataType.options.minItems);
56
- const maxItems = coalesce(dataType.get('maxItems'), dataType.options.maxItems);
57
- const uniqueItems = coalesce(dataType.get('uniqueItems'), dataType.options.uniqueItems);
58
- const items = dataType.get('items');
59
- const strictFormat = coalesce(options.strictFormat,
60
- dataType.get('strictFormat'), dataType.options.strictFormat);
61
- const maxErrors = data.variables.maxErrors = options.maxArrayErrors;
62
- const itemsValidator = data.variables.itemsValidator = items &&
63
- items.generate(options);
64
- if (strictFormat)
65
- data.code += `
66
- if (!Array.isArray(value))
67
- return typeCheck ? Failed : ctx.logError({
68
- message: 'Value must be an array',
69
- errorType: 'invalid-data-type'
70
- });`;
71
- data.code += `
72
- const arr = Array.isArray(value) ? value : [value];`;
73
-
74
- if (minItems)
75
- data.code += `
76
- if (arr.length < ${minItems})
77
- return typeCheck ? Failed : ctx.logError({
78
- message: 'Minimum accepted array length is ${minItems}, actual ' + arr.length,
79
- errorType: 'invalid-value-length',
80
- min: ${minItems},
81
- actual: arr.length
82
- });`;
83
- if (maxItems) {
84
- data.code += `
85
- if (arr.length > ${maxItems})
86
- return typeCheck ? Failed : ctx.logError({
87
- message: 'Maximum accepted array length is ${maxItems}, actual ' + arr.length,
88
- errorType: 'invalid-value-length',
89
- max: ${maxItems},
90
- actual: arr.length
91
- });`;
92
- }
93
- const forIterator = itemsValidator || uniqueItems;
94
- if (forIterator) {
95
- data.code += `
96
- const itemsLen = arr.length;
97
- ${maxErrors > 1 ? 'let numErrors = 0;' : ''}
98
- ${itemsValidator && options.coerceTypes ? `
99
- const resultArray = [];
100
- const lookupArray = resultArray;` : `
101
- const lookupArray = arr;`}
102
- ${itemsValidator ? 'const pathData = ctx.path;' : ''}
103
-
104
- ${itemsValidator ? `
105
- if (typeCheck) {
106
- for (let i = 0; i < itemsLen; i++) {
107
- if (!itemsValidator(arr[i], ctx).valid)
108
- return Failed;
109
- }
110
- }` : ''}
111
-
112
- if (typeCheck) return;
113
-
114
- for (let i = 0; i < itemsLen; i++) {
115
- ${itemsValidator ? 'pathData.push(i);' : ''}
116
- ${itemsValidator ? `
117
- let v = itemsValidator(arr[i], ctx);
118
- if (!v.valid) {
119
- ${maxErrors > 1 ?
120
- 'if (++numErrors >= maxErrors) return;' : 'return Failed;'}
121
- } else v = v.value;
122
- ` : 'const v = arr[i];'}
123
- `;
124
- if (uniqueItems)
125
- data.code += `
126
- if (lookupArray.indexOf(v, i+1) >= 0) {
127
- return ctx.logError({
128
- message: 'Items must be unique',
129
- errorType: 'unique-item-error'
130
- });
131
- }`;
132
- data.code += `
133
- ${itemsValidator && options.coerceTypes ? 'resultArray.push(v);' : ''}
134
- ${itemsValidator ? 'pathData.pop();' : ''}
135
- }`;
136
- }
137
-
138
- data.code += `
139
- if (typeCheck) return;`;
140
-
141
- if (options.coerceTypes)
142
- data.code += `
143
- ${itemsValidator ? 'value = resultArray;' : 'value = arr'}`;
144
- return data;
145
- }
146
- }
147
-
148
- module.exports = {ArrayFactory};
@@ -1,12 +0,0 @@
1
- import {AnyFactory} from './AnyFactory';
2
- import {Valgen} from '../Valgen';
3
-
4
- export namespace Base64Factory {
5
- export interface ITypeSchema extends Valgen.ITypeSchema {
6
- default?: string;
7
- }
8
- }
9
-
10
- export class Base64Factory extends AnyFactory {
11
- schema: Base64Factory.ITypeSchema;
12
- }
@@ -1,31 +0,0 @@
1
- 'use strict';
2
- const {coerceToString} = require('putil-varhelpers');
3
- const {AnyFactory} = require('./AnyFactory');
4
-
5
- const Base64Pattern = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;
6
-
7
- class Base64Factory extends AnyFactory {
8
-
9
- normalizeAttribute(attr, v) {
10
- switch (attr) {
11
- case 'default':
12
- return coerceToString(v);
13
- }
14
- return super.normalizeAttribute(attr, v);
15
- }
16
-
17
- _generateValidationCode(dataType, options) {
18
- const data = super._generateValidationCode(dataType, options);
19
- data.variables.base64Pattern = Base64Pattern;
20
-
21
- data.code += `
22
- if (!(typeof value === 'string' && value.match(base64Pattern)))
23
- return typeCheck ? Failed : ctx.logError({
24
- message: 'Value must be base64 encoded string',
25
- errorType: 'invalid-data-type'
26
- });`;
27
- return data;
28
- }
29
- }
30
-
31
- module.exports = {Base64Factory};
@@ -1,12 +0,0 @@
1
- import {AnyFactory} from './AnyFactory';
2
- import {Valgen} from '../Valgen';
3
-
4
- export namespace BooleanFactory {
5
- export interface ITypeSchema extends Valgen.ITypeSchema {
6
- default?: boolean;
7
- }
8
- }
9
-
10
- export class BooleanFactory extends AnyFactory {
11
- schema: BooleanFactory.ITypeSchema;
12
- }
@@ -1,49 +0,0 @@
1
- 'use strict';
2
- const {coerceToBoolean, coalesce} = require('putil-varhelpers');
3
- const {AnyFactory} = require('./AnyFactory');
4
-
5
- class BooleanFactory extends AnyFactory {
6
-
7
- normalizeCompileOptions(options) {
8
- const o = super.normalizeCompileOptions(options);
9
- o.strictFormat = coerceToBoolean(options.strictFormat);
10
- o.coerceTypes = coerceToBoolean(options.coerceTypes);
11
- return o;
12
- }
13
-
14
- normalizeAttribute(attr, v) {
15
- switch (attr) {
16
- case 'default':
17
- return coerceToBoolean(v);
18
- case 'strictFormat':
19
- return coerceToBoolean(v);
20
- }
21
- }
22
-
23
- _generateValidationCode(dataType, options) {
24
- const data = super._generateValidationCode(dataType, options);
25
- const strictFormat = coalesce(options.strictFormat, dataType.options.strictFormat);
26
- data.code += `
27
- if (!(typeof value === 'boolean'`;
28
- if (!strictFormat)
29
- data.code +=
30
- ` || (value === 0 || value === 1 || value === 'false' || value === 'true')`;
31
- data.code += `)
32
- )
33
- return typeCheck ? Failed : ctx.logError({
34
- message: 'Value must be a boolean',
35
- errorType: 'invalid-data-type'
36
- });
37
- `;
38
-
39
- data.code += `
40
- if (typeCheck) return;`;
41
-
42
- if (options.coerceTypes && !strictFormat)
43
- data.code += '\n value = value === \'false\' ? false : !!value';
44
- return data;
45
- }
46
-
47
- }
48
-
49
- module.exports = {BooleanFactory};