valgen 3.2.0 → 4.0.0-alpha.2

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 (140) 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 +38 -0
  14. package/cjs/rules/is-any.js +12 -0
  15. package/cjs/rules/is-array.js +38 -0
  16. package/cjs/rules/is-boolean.js +30 -0
  17. package/cjs/rules/is-date.js +63 -0
  18. package/cjs/rules/is-empty.js +68 -0
  19. package/cjs/rules/is-enum.js +30 -0
  20. package/cjs/rules/is-integer.js +26 -0
  21. package/cjs/rules/is-matches.js +24 -0
  22. package/cjs/rules/is-null.js +40 -0
  23. package/cjs/rules/is-number.js +26 -0
  24. package/cjs/rules/is-object-id.js +28 -0
  25. package/cjs/rules/is-object.js +103 -0
  26. package/cjs/rules/is-record.js +41 -0
  27. package/cjs/rules/is-string.js +79 -0
  28. package/cjs/rules/is-tuple.js +32 -0
  29. package/cjs/rules/length.js +41 -0
  30. package/cjs/rules/optional.js +44 -0
  31. package/cjs/rules/pipe.js +43 -0
  32. package/cjs/rules/range.js +89 -0
  33. package/cjs/rules/string-formats.js +296 -0
  34. package/cjs/rules/union.js +31 -0
  35. package/cjs/rules/utilities.js +31 -0
  36. package/esm/core/constants.js +2 -0
  37. package/esm/core/context.js +61 -0
  38. package/esm/core/index.js +5 -0
  39. package/esm/core/types.js +1 -0
  40. package/esm/core/validation-error.js +7 -0
  41. package/esm/core/validator.js +56 -0
  42. package/esm/helpers/object.utils.js +14 -0
  43. package/esm/helpers/string.utils.js +5 -0
  44. package/esm/index.js +2 -0
  45. package/esm/rules/index.js +22 -0
  46. package/esm/rules/is-any.js +8 -0
  47. package/esm/rules/is-array.js +34 -0
  48. package/esm/rules/is-boolean.js +26 -0
  49. package/esm/rules/is-date.js +55 -0
  50. package/esm/rules/is-empty.js +63 -0
  51. package/esm/rules/is-enum.js +26 -0
  52. package/esm/rules/is-integer.js +22 -0
  53. package/esm/rules/is-matches.js +20 -0
  54. package/esm/rules/is-null.js +34 -0
  55. package/esm/rules/is-number.js +22 -0
  56. package/esm/rules/is-object-id.js +21 -0
  57. package/esm/rules/is-object.js +99 -0
  58. package/esm/rules/is-record.js +37 -0
  59. package/esm/rules/is-string.js +70 -0
  60. package/esm/rules/is-tuple.js +28 -0
  61. package/esm/rules/length.js +35 -0
  62. package/esm/rules/optional.js +38 -0
  63. package/esm/rules/pipe.js +38 -0
  64. package/esm/rules/range.js +81 -0
  65. package/esm/rules/string-formats.js +266 -0
  66. package/esm/rules/union.js +27 -0
  67. package/esm/rules/utilities.js +26 -0
  68. package/package.json +33 -37
  69. package/typings/core/constants.d.ts +2 -0
  70. package/typings/core/context.d.ts +26 -0
  71. package/typings/core/index.d.ts +6 -0
  72. package/typings/core/types.d.ts +18 -0
  73. package/typings/core/validation-error.d.ts +5 -0
  74. package/typings/core/validator.d.ts +18 -0
  75. package/typings/helpers/object.utils.d.ts +2 -0
  76. package/typings/helpers/string.utils.d.ts +1 -0
  77. package/typings/index.d.ts +2 -0
  78. package/typings/rules/index.d.ts +22 -0
  79. package/typings/rules/is-any.d.ts +5 -0
  80. package/typings/rules/is-array.d.ts +7 -0
  81. package/typings/rules/is-boolean.d.ts +7 -0
  82. package/typings/rules/is-date.d.ts +19 -0
  83. package/typings/rules/is-empty.d.ts +13 -0
  84. package/typings/rules/is-enum.d.ts +9 -0
  85. package/typings/rules/is-integer.d.ts +7 -0
  86. package/typings/rules/is-matches.d.ts +9 -0
  87. package/typings/rules/is-null.d.ts +16 -0
  88. package/typings/rules/is-number.d.ts +7 -0
  89. package/typings/rules/is-object-id.d.ts +10 -0
  90. package/typings/rules/is-object.d.ts +22 -0
  91. package/typings/rules/is-record.d.ts +7 -0
  92. package/typings/rules/is-string.d.ts +42 -0
  93. package/typings/rules/is-tuple.d.ts +27 -0
  94. package/typings/rules/length.d.ts +21 -0
  95. package/typings/rules/optional.d.ts +17 -0
  96. package/typings/rules/pipe.d.ts +11 -0
  97. package/typings/rules/range.d.ts +48 -0
  98. package/typings/rules/string-formats.d.ts +140 -0
  99. package/typings/rules/union.d.ts +5 -0
  100. package/typings/rules/utilities.d.ts +11 -0
  101. package/lib/ArrayType.d.ts +0 -5
  102. package/lib/ArrayType.js +0 -43
  103. package/lib/DataType.d.ts +0 -25
  104. package/lib/DataType.js +0 -214
  105. package/lib/ObjectType.d.ts +0 -5
  106. package/lib/ObjectType.js +0 -78
  107. package/lib/SchemaError.d.ts +0 -3
  108. package/lib/SchemaError.js +0 -17
  109. package/lib/UnionType.d.ts +0 -5
  110. package/lib/UnionType.js +0 -54
  111. package/lib/Valgen.d.ts +0 -88
  112. package/lib/Valgen.js +0 -289
  113. package/lib/ValidationError.d.ts +0 -2
  114. package/lib/ValidationError.js +0 -4
  115. package/lib/factories/AnyFactory.d.ts +0 -28
  116. package/lib/factories/AnyFactory.js +0 -73
  117. package/lib/factories/ArrayFactory.d.ts +0 -16
  118. package/lib/factories/ArrayFactory.js +0 -148
  119. package/lib/factories/Base64Factory.d.ts +0 -12
  120. package/lib/factories/Base64Factory.js +0 -31
  121. package/lib/factories/BooleanFactory.d.ts +0 -12
  122. package/lib/factories/BooleanFactory.js +0 -49
  123. package/lib/factories/DateFactory.d.ts +0 -40
  124. package/lib/factories/DateFactory.js +0 -239
  125. package/lib/factories/FunctionFactory.d.ts +0 -12
  126. package/lib/factories/FunctionFactory.js +0 -28
  127. package/lib/factories/IntegerFactory.d.ts +0 -14
  128. package/lib/factories/IntegerFactory.js +0 -33
  129. package/lib/factories/NilFactory.d.ts +0 -4
  130. package/lib/factories/NilFactory.js +0 -20
  131. package/lib/factories/NumberFactory.d.ts +0 -36
  132. package/lib/factories/NumberFactory.js +0 -178
  133. package/lib/factories/ObjectFactory.d.ts +0 -38
  134. package/lib/factories/ObjectFactory.js +0 -326
  135. package/lib/factories/StringFactory.d.ts +0 -16
  136. package/lib/factories/StringFactory.js +0 -94
  137. package/lib/factories/UnionFactory.d.ts +0 -13
  138. package/lib/factories/UnionFactory.js +0 -62
  139. package/lib/index.d.ts +0 -19
  140. package/lib/index.js +0 -37
@@ -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};
@@ -1,40 +0,0 @@
1
- import {AnyFactory} from './AnyFactory';
2
- import {Valgen} from '../Valgen';
3
-
4
- export namespace DateFactory {
5
- export interface ITypeSchema extends Valgen.ITypeSchema {
6
- default?: string;
7
- format?: string;
8
- fast?: boolean;
9
- }
10
- export interface IDateFormatMap {
11
- date?: string,
12
- datetime?: string,
13
- timestamp?: string,
14
- time?: string,
15
- rfc2616?: string
16
- }
17
- export interface IOptions {
18
- dateFormats?: IDateFormatMap;
19
- format?: string;
20
- }
21
- }
22
-
23
-
24
- export class DateFactory extends AnyFactory {
25
-
26
- schema: DateFactory.ITypeSchema;
27
- format?: string;
28
- dateFormats: DateFactory.IDateFormatMap;
29
-
30
- TIMESTAMP_PATTERN: RegExp;
31
- TIMESTAMP_STRICT_PATTERN: RegExp;
32
- DATETIME_PATTERN: RegExp;
33
- DATETIME_STRICT_PATTERN: RegExp;
34
- DATE_PATTERN: RegExp;
35
- DATE_STRICT_PATTERN: RegExp;
36
- TIME_PATTERN: RegExp;
37
- TIME_STRICT_PATTERN: RegExp;
38
-
39
- constructor(options?: DateFactory.IOptions);
40
- }
@@ -1,239 +0,0 @@
1
- 'use strict';
2
-
3
- const {AnyFactory} = require('./AnyFactory');
4
- const {coalesce, coerceToBoolean, coerceToString} = require('putil-varhelpers');
5
-
6
- class DateFactory extends AnyFactory {
7
-
8
- constructor(options) {
9
- super();
10
- this.TIMESTAMP_PATTERN =
11
- /^(\d{4})-?(0[1-9]|1[012])?-?([123]0|[012][1-9]|31)?(?:T?([01][0-9]|2[0-3]):?([0-5][0-9]):?([0-5][0-9])?(?:\.(\d+))?(?:(Z)|(?:([+-])([01]?[0-9]|2[0-3]):?([0-5][0-9])?))?)?$/;
12
- this.TIMESTAMP_STRICT_PATTERN =
13
- /^(\d{4})-(0[1-9]|1[012])-([123]0|[012][1-9]|31)T([01][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])(?:\.?(\d+))?(?:(Z)|(?:([+-])([01]?[0-9]|2[0-3]):([0-5][0-9])))$/;
14
- this.DATETIME_PATTERN =
15
- /^(\d{4})-?(0[1-9]|1[012])?-?([123]0|[012][1-9]|31)?(?:T?([01][0-9]|2[0-3]):?([0-5][0-9]):?([0-5][0-9])?(?:\.?(\d+))?)?$/;
16
- this.DATETIME_STRICT_PATTERN =
17
- /^(\d{4})-(0[1-9]|1[012])-([123]0|[012][1-9]|31)T([01][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])(?:\.?(\d+))?$/;
18
- this.DATE_PATTERN =
19
- /^(\d{4})-?(0[1-9]|1[012])?-?([123]0|[012][1-9]|31)?$/;
20
- this.DATE_STRICT_PATTERN =
21
- /^(\d{4})-(0[1-9]|1[012])-([123]0|[012][1-9]|31)$/;
22
- this.TIME_PATTERN =
23
- /^([01][0-9]|2[0-3]):?([0-5][0-9]):?([0-5][0-9])?(?:\.(\d+))?$/;
24
- this.TIME_STRICT_PATTERN =
25
- /^([01][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])?(?:\.(\d+))?$/;
26
- this.dateFormats = (options && options.dateFormats) || {
27
- 'date': 'date',
28
- 'datetime': 'datetime',
29
- 'timestamp': 'timestamp',
30
- 'time': 'time',
31
- 'rfc2616': 'rfc2616'
32
- };
33
- this.format = options && options.format;
34
- }
35
-
36
- normalizeCompileOptions(options) {
37
- const o = super.normalizeCompileOptions(options);
38
- o.strictFormat = coerceToBoolean(options.strictFormat);
39
- o.coerceTypes = coerceToBoolean(options.coerceTypes);
40
- o.convertDates = coerceToBoolean(options.convertDates);
41
- return o;
42
- }
43
-
44
- normalizeAttribute(attr, v) {
45
- switch (attr) {
46
- case 'default':
47
- return coerceDateOrString(v);
48
- case 'format':
49
- if (v && !this.dateFormats[v])
50
- throw new TypeError(`Unknown date format (${v})`);
51
- return coerceToString(v);
52
- case 'strictFormat':
53
- return coerceToBoolean(v);
54
- case 'fast':
55
- return coerceToBoolean(v);
56
- }
57
- }
58
-
59
- _generateValidationCode(type, options) {
60
- const data = super._generateValidationCode(type, options);
61
- const convertDates = options.convertDates;
62
- const coerceTypes = options.coerceTypes || convertDates;
63
- const formatName = type.get('format') || this.format || 'timestamp';
64
- const format = this.dateFormats[formatName] || formatName;
65
-
66
- const fastDateValidation = type.get('fast') && !convertDates &&
67
- format !== 'rfc2616';
68
- const strictFormat = coalesce(options.strictFormat, type.get('strictFormat'));
69
- const matchDatePattern = this._getMatchDatePatternFn(format, strictFormat);
70
- const dateItemsToISO = this._getFormatDateItemsFn('timestamp');
71
- const formatDate = this._getFormatDateFn(format);
72
- const formatDateItems = this._getFormatDateItemsFn(format);
73
- data.code += `
74
- if (!(value instanceof Date || typeof value === 'string'))
75
- return typeCheck ? Failed : ctx.logError({
76
- message: 'Value must be ${formatName} formatted string or Date instance',
77
- errorType: 'invalid-data-type'
78
- });`;
79
- data.code += `
80
- let d;
81
- let m;
82
- if (typeof value === 'string') {`;
83
- if (format === 'rfc2616') {
84
- if (strictFormat) {
85
- data.code += `
86
- d = String(value).match(/^[A-Za-z]/) && new Date(value);`;
87
- } else
88
- data.code += `
89
- m = matchDatePattern(value);
90
- d = new Date(m ? dateItemsToISO(m) : value);`;
91
- } else
92
- data.code += `
93
- m = matchDatePattern(value);
94
- if (!m)
95
- return typeCheck ? Failed : ctx.logError({
96
- message: 'Value must be ${formatName} formatted string or Date instance',
97
- errorType: 'invalid-data-type'
98
- });
99
- ${fastDateValidation ?
100
- `return ${coerceTypes ? 'formatDateItems(m)' : 'value'};` :
101
- `d = new Date(dateItemsToISO(m));
102
- d = isValidDate(d) && parseInt((m[3]||'01'), 10) === d.getUTCDate() ? d : null;`}
103
- `;
104
- data.code += `
105
- } else d = value;
106
- if (!isValidDate(d))
107
- return typeCheck ? Failed : ctx.logError({
108
- message: 'Value must be ${formatName} formatted string or Date instance',
109
- errorType: 'invalid-data-type'
110
- });`;
111
-
112
- data.code += `
113
- if (typeCheck) return;`;
114
-
115
- if (convertDates)
116
- data.code += '\n value = d;';
117
- else if (coerceTypes) {
118
- data.code += '\n value = m ? formatDateItems(m) : formatDate(d);';
119
- }
120
- data.variables = {
121
- ...data.variables,
122
- isValidDate,
123
- matchDatePattern, formatDateItems, formatDate,
124
- dateItemsToISO,
125
- };
126
- return data;
127
- }
128
-
129
- _getFormatDateFn(format) {
130
- switch (format) {
131
- case 'date':
132
- return (d) => {
133
- const s = d.toISOString();
134
- return s.substring(0, 10);
135
- };
136
- case 'datetime':
137
- return (d) => {
138
- const s = d.toISOString();
139
- return s.substring(0, s.length - 1);
140
- };
141
- case 'time':
142
- return (d) => {
143
- let s = d.toISOString();
144
- return s.endsWith('.000Z') ?
145
- s.substring(11, s.length - 5) : s.substring(11, s.length - 1);
146
- };
147
- case 'timestamp':
148
- return (d) => d.toISOString();
149
- case 'rfc2616':
150
- /* istanbul ignore next : Timezone obstructs testing */
151
- return (d) => d.toString();
152
- }
153
- }
154
-
155
- _getFormatDateItemsFn(format) {
156
- let src = ` const v = `;
157
- if (format === 'rfc2616' || format === 'date' ||
158
- format === 'datetime' || format === 'timestamp') {
159
- src += `
160
- // Date part
161
- m[1] + '-' + (m[2]||'01') + '-' + (m[3]||'01')`;
162
- }
163
- if (format === 'rfc2616' || format === 'datetime' ||
164
- format === 'timestamp') {
165
- src += ` +
166
- // Time part
167
- 'T'`;
168
- }
169
- if (format === 'rfc2616' || format === 'datetime' ||
170
- format === 'timestamp' || format === 'time') {
171
- src += `+ (m[4] || '00') + ':' + (m[5] || '00') + ':' + (m[6] || '00') +
172
- // Millisecond
173
- (m[7] ? '.' + m[7] : '')`;
174
- }
175
- if (format === 'rfc2616' || format === 'timestamp') {
176
- src += `+
177
- // Time zone
178
- (m[9] ? (m[9] + (m[10] || '00') + ':' + (m[11] || '00')) : 'Z')`;
179
- }
180
- if (format === 'rfc2616') {
181
- src += ';\n return new Date(v).toString()';
182
- } else src += ';\n return v;';
183
- return new Function('m', src);
184
- }
185
-
186
- _getMatchDatePatternFn(format, strict) {
187
- if (format === 'time') {
188
- return (v) => {
189
- const m = v.match(strict ? this.TIME_STRICT_PATTERN : this.TIME_PATTERN);
190
- return m && [v, '1970', '01', '01', ...m.slice(1)];
191
- };
192
- }
193
- let src = `
194
- return (v) => {
195
- const m = v.match(pattern);
196
- if (!m || (m[2] === '02' && m[3] > '29'))
197
- return;
198
- `;
199
- if (!strict) {
200
- if (format === 'date')
201
- src += ' m[4]=null;m[5]=null;m[6]=null;m[7]=null;\n';
202
- if (format === 'date' || format === 'datetime')
203
- src += ' m[8]=null;m[9]=null;m[10]=null;m[11]=null;\n';
204
- }
205
- src += `
206
- return m;
207
- }`;
208
- let pattern;
209
- switch (format) {
210
- case 'datetime':
211
- pattern = strict ? this.DATETIME_STRICT_PATTERN :
212
- this.DATETIME_PATTERN;
213
- break;
214
- case 'date':
215
- pattern = strict ? this.DATE_STRICT_PATTERN :
216
- this.DATE_PATTERN;
217
- break;
218
- default:
219
- pattern = strict ?
220
- this.TIMESTAMP_STRICT_PATTERN :
221
- this.TIMESTAMP_PATTERN;
222
- }
223
- return new Function('pattern', src)(pattern);
224
- }
225
-
226
- }
227
-
228
- function isValidDate(d) {
229
- return d && !isNaN(d.getTime());
230
- }
231
-
232
- function coerceDateOrString(v) {
233
- if (v && !(typeof v === 'string' || v instanceof Date))
234
- throw new TypeError(`"${v}" is not a string or Date instance`);
235
- return v;
236
- }
237
-
238
- module.exports = {DateFactory};
239
-
@@ -1,12 +0,0 @@
1
- import {AnyFactory} from './AnyFactory';
2
- import {Valgen} from '../Valgen';
3
-
4
- export namespace FunctionFactory {
5
- export interface ITypeSchema extends Valgen.ITypeSchema {
6
- default?: Function;
7
- }
8
- }
9
-
10
- export class FunctionFactory extends AnyFactory {
11
- schema: FunctionFactory.ITypeSchema;
12
- }
@@ -1,28 +0,0 @@
1
- 'use strict';
2
- const {AnyFactory} = require('./AnyFactory');
3
-
4
- class FunctionFactory extends AnyFactory {
5
-
6
- normalizeAttribute(attr, v) {
7
- switch (attr) {
8
- case 'default':
9
- if (v && typeof v !== 'function')
10
- throw new TypeError(`"${v}" is not a Function`);
11
- return v;
12
- }
13
- return super.normalizeAttribute(attr, v);
14
- }
15
-
16
- _generateValidationCode(dataType, options) {
17
- const data = super._generateValidationCode(dataType, options);
18
- data.code += `
19
- if (typeof value !== 'function')
20
- return typeCheck ? Failed : ctx.logError({
21
- message: 'Value must be a function',
22
- errorType: 'invalid-data-type'
23
- });`;
24
- return data;
25
- }
26
- }
27
-
28
- module.exports = {FunctionFactory};
@@ -1,14 +0,0 @@
1
- import {NumberFactory} from './NumberFactory';
2
-
3
- export namespace IntegerFactory {
4
- export interface IOptions extends NumberFactory.IOptions {
5
- format?: NumberFactory.IntegerFormatType;
6
- }
7
- }
8
-
9
- export class IntegerFactory extends NumberFactory {
10
-
11
- format?: NumberFactory.IntegerFormatType;
12
-
13
- constructor(options?: IntegerFactory.IOptions);
14
- }
@@ -1,33 +0,0 @@
1
- 'use strict';
2
- const {coerceToInt, mapDistinct} = require('putil-varhelpers');
3
- const {NumberFactory, IntegerFormats} = require('./NumberFactory');
4
-
5
- class IntegerFactory extends NumberFactory {
6
-
7
- create(instance) {
8
- instance.options.format = 'int32';
9
- }
10
-
11
- normalizeAttribute(attr, v) {
12
- switch (attr) {
13
- case 'default':
14
- case 'minimum':
15
- case 'maximum':
16
- case 'multipleOf':
17
- return coerceToInt(v);
18
- case 'enum':
19
- if (!Array.isArray(v))
20
- throw new TypeError(`"${v}" is not an array value.`);
21
- return mapDistinct(v, coerceToInt);
22
- case 'format': {
23
- if (v && !IntegerFormats.includes(v))
24
- throw new TypeError(`"${v}" is not a valid integer format identifier.`);
25
- return v;
26
- }
27
- }
28
- return super.normalizeAttribute(attr, v);
29
- }
30
-
31
- }
32
-
33
- module.exports = {IntegerFactory};
@@ -1,4 +0,0 @@
1
- import {AnyFactory} from './AnyFactory';
2
-
3
- export class NilFactory extends AnyFactory {
4
- }
@@ -1,20 +0,0 @@
1
- 'use strict';
2
- const {AnyFactory} = require('./AnyFactory');
3
-
4
- class NilFactory extends AnyFactory {
5
-
6
- normalizeAttribute(attr, v) {
7
- }
8
-
9
- _generateValidationCode(dataType, options) {
10
- const data = super._generateValidationCode(dataType, options);
11
- data.code = ' if (value === undefined) value = null;' + data.code + `
12
- return typeCheck ? Failed : ctx.logError({
13
- message: 'Value must be null',
14
- errorType: 'invalid-data-type'
15
- }); `;
16
- return data;
17
- }
18
- }
19
-
20
- module.exports = {NilFactory};
@@ -1,36 +0,0 @@
1
- import {AnyFactory} from './AnyFactory';
2
- import {Valgen} from '../Valgen';
3
-
4
- export namespace NumberFactory {
5
- export type IntegerFormatType = 'int64' | 'bigint' | 'int32' | 'int' | 'int16' | 'int8' |
6
- 'uint64' | 'uint32' | 'uint16' | 'uint8' | 'long' | 'float';
7
- export type FloatFormatType = 'float' | 'double';
8
- export type NumberFormatType = IntegerFormatType | FloatFormatType;
9
-
10
- export interface ITypeSchema extends Valgen.ITypeSchema {
11
- default?: number;
12
- enum?: number[];
13
- minimum?: number;
14
- maximum?: number;
15
- multipleOf?: number;
16
- strictFormat?: boolean;
17
- }
18
-
19
- export interface IOptions {
20
- format?: NumberFormatType;
21
- }
22
-
23
- }
24
-
25
- export const NumberFormats: string[];
26
- export const IntegerFormats: string[];
27
- export const MinValues: { [format: string]: number };
28
- export const MaxValues: { [format: string]: number };
29
-
30
- export class NumberFactory extends AnyFactory {
31
- schema: NumberFactory.ITypeSchema;
32
- format?: NumberFactory.NumberFormatType;
33
-
34
- constructor(options?: NumberFactory.IOptions);
35
-
36
- }