@ohos-ports/djv 0.0.0-stage → 2.1.4-beta.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.
package/lib/djv.js ADDED
@@ -0,0 +1,304 @@
1
+ const { restore, expression } = require('./utils/template');
2
+ const formats = require('./utils/formats');
3
+ const { generate, State } = require('./utils/state');
4
+ const { add, use } = require('./utils/environment.js');
5
+
6
+ /**
7
+ * Configuration for template
8
+ * @typedef {object} DjvConfig
9
+ * @property {string?} version - defines which version of json-schema draft to use,
10
+ * draft-04 by default
11
+ * @property {function?} versionConfigure - handler to apply for environment version
12
+ * @property {boolean?} inner - a generating object should be considered as inner
13
+ * Default value is false/undefined.
14
+ * If true, then it avoid creating variables in a generated function body,
15
+ * however without proper wrapper function approach will not work.
16
+ * @see template/body, template/body
17
+ * @property {object?} formats - an object containing list of formatters to add for environment
18
+ * @property {function?} errorHandler - a handler to use for generating custom error messages
19
+ */
20
+
21
+ /**
22
+ * @name Environment
23
+ * @description
24
+ * Key constructor used for creating enivornment instance
25
+ * @type {function} constructor
26
+ * @param {DjvConfig} options passed to templater and utilities
27
+ *
28
+ * Usage
29
+ *
30
+ * ```javascript
31
+ * const env = djv();
32
+ * const env = new djv();
33
+ * const env = new djv({ errorHandler: () => ';' });
34
+ * ```
35
+ */
36
+ function Environment(options = {}) {
37
+ if (!(this instanceof Environment)) { return new Environment(options); }
38
+
39
+ this.options = options;
40
+ this.resolved = {};
41
+ this.state = new State(null, this);
42
+
43
+ this.useVersion(options.version, options.versionConfigure);
44
+ this.addFormat(options.formats);
45
+ }
46
+
47
+ Object.assign(Environment, {
48
+ expression,
49
+ });
50
+
51
+ Object.assign(Environment.prototype, {
52
+ /**
53
+ * check if object correspond to schema
54
+ *
55
+ * Usage
56
+ *
57
+ * ```javascript
58
+ * env.validate('test#/common', { type: 'common' });
59
+ * // => undefined
60
+ *
61
+ * env.validate('test#/common', { type: 'custom' });
62
+ * // => 'required: data'
63
+ *
64
+ * @param {string} name
65
+ * @param {object} object
66
+ * @returns {string} error - undefined if it is valid
67
+ */
68
+ validate(name, object) {
69
+ const foundSchema = this.resolve(name);
70
+ return foundSchema.fn(object);
71
+ },
72
+
73
+ /**
74
+ * add schema to djv environment
75
+ *
76
+ * Usage
77
+ *
78
+ * ```javascript
79
+ * env.addSchema('test', jsonSchema);
80
+ * ```
81
+ *
82
+ * @param {string?} name
83
+ * @param {object} schema
84
+ * @param {object} schema
85
+ * @returns {resolved}
86
+ */
87
+ addSchema(name, schema) {
88
+ const realSchema = typeof name === 'object' ? name : schema;
89
+ const resolved = {
90
+ schema: realSchema,
91
+ fn: generate(this, realSchema, undefined, this.options),
92
+ };
93
+
94
+ [name, schema.id]
95
+ .filter(id => typeof id === 'string')
96
+ .forEach((id) => {
97
+ this.resolved[id] = Object.assign({ name: id }, resolved);
98
+ });
99
+
100
+ return resolved;
101
+ },
102
+
103
+ /**
104
+ * removes a schema or the whole structure from djv environment
105
+ *
106
+ * Usage
107
+ *
108
+ * ```javascript
109
+ * env.removeSchema('test');
110
+ * ```
111
+ *
112
+ * @param {string} name
113
+ */
114
+ removeSchema(name) {
115
+ if (name) {
116
+ delete this.resolved[name];
117
+ } else {
118
+ this.resolved = {};
119
+ }
120
+ },
121
+
122
+ /**
123
+ * resolves name by existing environment
124
+ *
125
+ * Usage
126
+ *
127
+ * ```javascript
128
+ * env.resolve('test');
129
+ * // => { name: 'test', schema: {} }, fn: ... }
130
+ * ```
131
+ *
132
+ * @param {string} name
133
+ * @returns {resolved}
134
+ */
135
+ resolve(name) {
136
+ if (typeof name === 'object' || !this.resolved[name]) {
137
+ return this.addSchema(
138
+ name,
139
+ this.state.resolve(name)
140
+ );
141
+ }
142
+
143
+ return this.resolved[name];
144
+ },
145
+
146
+ /**
147
+ * exports the whole structure object from environment or by resolved name
148
+ *
149
+ * Usage
150
+ *
151
+ * ```javascript
152
+ * env.export();
153
+ * // => { test: { name: 'test', schema: {}, ... } }
154
+ * ```
155
+ *
156
+ * @param {string} name
157
+ * @returns {serializedInternalState}
158
+ */
159
+ export(name) {
160
+ let resolved;
161
+ if (name) {
162
+ resolved = this.resolve(name);
163
+ resolved = {
164
+ name,
165
+ schema: resolved.schema,
166
+ fn: resolved.fn.toString()
167
+ };
168
+ } else {
169
+ resolved = {};
170
+ Object.keys(this.resolved).forEach((key) => {
171
+ resolved[key] = {
172
+ name: key,
173
+ schema: this.resolved[key].schema,
174
+ fn: this.resolved[key].fn.toString()
175
+ };
176
+ });
177
+ }
178
+
179
+ return JSON.stringify(resolved);
180
+ },
181
+
182
+ /**
183
+ * imports all found structure objects to internal environment structure
184
+ * Usage
185
+ *
186
+ * ```javascript
187
+ * env.import(config);
188
+ * ```
189
+ *
190
+ * @param {object} config - internal structure or only resolved schema object
191
+ */
192
+ import(config) {
193
+ const item = JSON.parse(config);
194
+ let restoreData = item;
195
+ if (item.name && item.fn && item.schema) {
196
+ restoreData = { [item.name]: item };
197
+ }
198
+
199
+ Object.keys(restoreData).forEach((key) => {
200
+ const { name, schema, fn: source } = restoreData[key];
201
+ const fn = restore(source, schema, this.options);
202
+ this.resolved[name] = { name, schema, fn };
203
+ });
204
+ },
205
+
206
+ /**
207
+ * @name addFormat
208
+ * @type function
209
+ * @description
210
+ * Add formatter to djv environment.
211
+ * When a string is passed it is interpreted as an expression which
212
+ * when returns `true` goes with an error, when returns `false` then a property is valid.
213
+ * When a function is passed it will be executed during schema compilation
214
+ * with a current schema and template helper arguments.
215
+ * @see utils/formats
216
+ *
217
+ * Usage
218
+ *
219
+ * ```javascript
220
+ * env.addFormat('UpperCase', '%s !== %s.toUpperCase()');
221
+ * // or
222
+ * env.addFormat('isOk', function(schema, tpl){
223
+ * return `!${schema.isOk} || %s !== %s.toUpperCase()`;
224
+ * });
225
+ * ```
226
+ *
227
+ * @param {string/object?} name
228
+ * @param {string/function} formatter
229
+ */
230
+ addFormat(name, formatter) {
231
+ if (typeof name === 'string') {
232
+ formats[name] = formatter;
233
+ return;
234
+ }
235
+
236
+ if (typeof name === 'object') {
237
+ Object.assign(formats, name);
238
+ }
239
+ },
240
+
241
+ /**
242
+ * @name setErrorHandler
243
+ * @type function
244
+ * @description
245
+ * Specify custom error handler which will be used in generated functions when problem found.
246
+ * The function should return a string expression, which will be executed when generated
247
+ * validator function is executed. The simpliest use case is the default one
248
+ * @see template/defaultErrorHandler
249
+ * ```javascript
250
+ * function defaultErrorHandler(errorType) {
251
+ * return `return "${errorType}: ${tpl.data}";`;
252
+ * }
253
+ * ```
254
+ * It returns an expression 'return ...', so the output is an error string.
255
+ * Usage
256
+ * ```javascript
257
+ * djv({ errorHandler: () => 'return { error: true };' }) // => returns an object
258
+ * djv({
259
+ * errorHandler: function customErrorHandler(errorType, property) {
260
+ * return `errors.push({
261
+ * type: "${errorType}",
262
+ * schema: "${this.schema[this.schema.length - 1]}",
263
+ * data: "${this.data[this.data.length - 1]}"
264
+ * });`;
265
+ * }
266
+ * });
267
+ * ```
268
+ * When a custom error handler is used, the template body function adds a `error` variable inside
269
+ * a generated validator, which can be used to put error information. `errorType` is always
270
+ * passed to error handler function. Some validate utilities put extra argument, like f.e.
271
+ * currently processed property value. Inside the handler context is a templater instance,
272
+ * which contains `this.schema`, `this.data` paths arrays to identify validator position.
273
+ * @see test/index/setErrorHandler for more examples
274
+ * @param {function} errorHandler - a function called each time compiler creates an error branch
275
+ * @returns void
276
+ */
277
+ setErrorHandler(errorHandler) {
278
+ Object.assign(this.options, { errorHandler });
279
+ },
280
+ /**
281
+ * @name useVersion
282
+ * @type {function}
283
+ * @description
284
+ * Add a specification version for environment
285
+ * A configure function is called with exposed environments, like keys, formats, etc.
286
+ * Updates internals utilities and configurations to fix versions implementation conflicts
287
+ * @param {string} version of json-schema specification to use
288
+ * @param {function} configure
289
+ * @returns void
290
+ */
291
+ useVersion(version, configure) {
292
+ if (typeof configure !== 'function' && version === 'draft-04') {
293
+ /* eslint-disable no-param-reassign, global-require, import/no-extraneous-dependencies */
294
+ configure = require('@korzio/djv-draft-04');
295
+ /* eslint-enable no-param-reassign, global-require, import/no-extraneous-dependencies */
296
+ }
297
+ if (typeof configure === 'function') {
298
+ add(version, configure);
299
+ }
300
+ use(version);
301
+ },
302
+ });
303
+
304
+ module.exports = Environment;
@@ -0,0 +1,38 @@
1
+ /**
2
+ * @module environment
3
+ * @description
4
+ * Update the given environment
5
+ */
6
+ const properties = require('./properties');
7
+ const keywords = require('./keywords');
8
+ const validators = require('../validators');
9
+ const formats = require('./formats');
10
+ const { keys } = require('./uri');
11
+ const { transformation } = require('./schema');
12
+
13
+ const environmentConfig = {};
14
+
15
+ function add(version, config) {
16
+ environmentConfig[version] = config;
17
+ }
18
+
19
+ function use(version) {
20
+ if (!version || !environmentConfig[version]) {
21
+ return;
22
+ }
23
+
24
+ const patchEnvironment = environmentConfig[version];
25
+ patchEnvironment({
26
+ properties,
27
+ keywords,
28
+ validators,
29
+ formats,
30
+ keys,
31
+ transformation,
32
+ });
33
+ }
34
+
35
+ module.exports = {
36
+ add,
37
+ use,
38
+ };
@@ -0,0 +1,29 @@
1
+ /**
2
+ * @module formats
3
+ * @description
4
+ * Validators as string for format keyword rules.
5
+ * A validator is a string, which when executed returns `false` if test is failed, `true` otherwise.
6
+ */
7
+
8
+ const { expression } = require('./template');
9
+
10
+ module.exports = {
11
+ alpha: expression`!/^[a-zA-Z]+$/.test(${'data'})`,
12
+ alphanumeric: expression`!/^[a-zA-Z0-9]+$/.test(${'data'})`,
13
+ identifier: expression`!/^[-_a-zA-Z0-9]+$/.test(${'data'})`,
14
+ hexadecimal: expression`!/^[a-fA-F0-9]+$/.test(${'data'})`,
15
+ numeric: expression`!/^[0-9]+$/.test(${'data'})`,
16
+ 'date-time': expression`isNaN(Date.parse(${'data'})) || ~${'data'}.indexOf(\'/\')`,
17
+ uppercase: expression`${'data'} !== ${'data'}.toUpperCase()`,
18
+ lowercase: expression`${'data'} !== ${'data'}.toLowerCase()`,
19
+ hostname: expression`${'data'}.length >= 256 || !/^([a-zA-Z0-9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-9]*)?(?:\\/(?:[A-Za-z0-9\\-._~!$&\'()*+,;=:@]|%[0-9A-Fa-f]{2})*)*|\\/(?:(?:[A-Za-z0-9\\-._~!$&\'()*+,;=:@]|%[0-9A-Fa-f]{2})+(?:\\/(?:[A-Za-z0-9\\-._~!$&\'()*+,;=:@]|%[0-9A-Fa-f]{2})*)*)?|(?:[A-Za-z0-9\\-._~!$&\'()*+,;=:@]|%[0-9A-Fa-f]{2})+(?:\\/(?:[A-Za-z0-9\\-._~!$&\'()*+,;=:@]|%[0-9A-Fa-f]{2})*)*|)(?:\\?(?:[A-Za-z0-9\\-._~!$&\'()*+,;=:@\\/?]|%[0-9A-Fa-f]{2})*)?(?:\\#(?:[A-Za-z0-9\\-._~!$&\'()*+,;=:@\\/?]|%[0-9A-Fa-f]{2})*)?$/.test(${'data'})`,
21
+ email: expression`!/^[^@]+@[^@]+\\.[^@]+$/.test(${'data'})`,
22
+ ipv4: expression`!/^(\\d?\\d?\\d){0,255}\\.(\\d?\\d?\\d){0,255}\\.(\\d?\\d?\\d){0,255}\\.(\\d?\\d?\\d){0,255}$/.test(${'data'}) || ${'data'}.split(".")[3] > 255`,
23
+ ipv6: expression`!/^((?=.*::)(?!.*::.+::)(::)?([\\dA-F]{1,4}:(:|\\b)|){5}|([\\dA-F]{1,4}:){6})((([\\dA-F]{1,4}((?!\\3)::|:\\b|$))|(?!\\2\\3)){2}|(((2[0-4]|1\\d|[1-9])?\\d|25[0-5])\\.?\\b){4})$/.test(${'data'})`,
24
+ regex: expression`/[^\\\\]\\\\[^.*+?^\${}()|[\\]\\\\bBcdDfnrsStvwWxu0-9]/i.test(${'data'})`,
25
+ // TODO optimize uri-reference regex... too long
26
+ 'json-pointer': expression`!/^$|^\\/(?:~(?=[01])|[^~])*$/i.test(${'data'})`,
27
+ 'uri-reference': expression`!/^(?:[A-Za-z][A-Za-z0-9+\\-.]*:(?:\\/\\/(?:(?:[A-Za-z0-9\\-._~!$&\'()*+,;=:]|%[0-9A-Fa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za-z0-9\\-._~!$&\'()*+,;=]|%[0-9A-Fa-f]{2})*)(?::[0-9]*)?(?:\\/(?:[A-Za-z0-9\\-._~!$&\'()*+,;=:@]|%[0-9A-Fa-f]{2})*)*|\\/(?:(?:[A-Za-z0-9\\-._~!$&\'()*+,;=:@]|%[0-9A-Fa-f]{2})+(?:\\/(?:[A-Za-z0-9\\-._~!$&\'()*+,;=:@]|%[0-9A-Fa-f]{2})*)*)?|(?:[A-Za-z0-9\\-._~!$&\'()*+,;=@]|%[0-9A-Fa-f]{2})+(?:\\/(?:[A-Za-z0-9\\-._~!$&\'()*+,;=:@]|%[0-9A-Fa-f]{2})*)*|)(?:\\?(?:[A-Za-z0-9\\-._~!$&\'()*+,;=:@\\/?]|%[0-9A-Fa-f]{2})*)?(?:\\#(?:[A-Za-z0-9\\-._~!$&\'()*+,;=:@\\/?]|%[0-9A-Fa-f]{2})*)?)$/i.test(${'data'})`,
28
+ 'uri-template': expression`!/^(?:(?:[^\\x00-\\x20"\'<>%\\\\^\`{|}]|%[0-9a-f]{2})|\\{[+#.\\/;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?:\\:[1-9][0-9]{0,3}|\\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?:\\:[1-9][0-9]{0,3}|\\*)?)*\\})*$/i.test(${'data'})`,
29
+ };
@@ -0,0 +1,45 @@
1
+ /**
2
+ * @module utils
3
+ * @description
4
+ * Basic utilities for djv project
5
+ */
6
+
7
+ /**
8
+ * @name asExpression
9
+ * @type {function}
10
+ * @description
11
+ * Transform function or string to expression
12
+ * @see validators
13
+ * @param {function|string} fn
14
+ * @param {object} schema
15
+ * @param {object} tpl templater instance
16
+ * @returns {string} expression
17
+ */
18
+ function asExpression(fn, schema, tpl) {
19
+ if (typeof fn !== 'function') {
20
+ return fn;
21
+ }
22
+
23
+ return fn(schema, tpl);
24
+ }
25
+
26
+ /**
27
+ * @name hasProperty
28
+ * @type {function}
29
+ * @description
30
+ * Check if the property exists in a given object
31
+ * @param {object} object
32
+ * @param {string} property
33
+ * @returns {boolean} exists
34
+ */
35
+ function hasProperty(object, property) {
36
+ return (
37
+ typeof object === 'object' &&
38
+ Object.prototype.hasOwnProperty.call(object, property)
39
+ );
40
+ }
41
+
42
+ module.exports = {
43
+ asExpression,
44
+ hasProperty,
45
+ };
@@ -0,0 +1,29 @@
1
+ /**
2
+ * @module keywords
3
+ * @description
4
+ * A list of keywords used in specification.
5
+ */
6
+ module.exports = [
7
+ '$ref',
8
+ '$schema',
9
+ 'type',
10
+ 'not',
11
+ 'anyOf',
12
+ 'allOf',
13
+ 'oneOf',
14
+ 'properties',
15
+ 'patternProperties',
16
+ 'additionalProperties',
17
+ 'items',
18
+ 'additionalItems',
19
+ 'required',
20
+ 'default',
21
+ 'title',
22
+ 'description',
23
+ 'definitions',
24
+ 'dependencies',
25
+ '$id',
26
+ 'contains',
27
+ 'const',
28
+ 'examples'
29
+ ];
@@ -0,0 +1,94 @@
1
+ /**
2
+ * @module properties
3
+ * @description
4
+ * Validators as string for properties keyword rules.
5
+ * A validator is a function, which when executed returns
6
+ * - `false` if test is failed,
7
+ * - `true` otherwise.
8
+ */
9
+ module.exports = {
10
+ readOnly: 'false',
11
+ exclusiveMinimum(schema) {
12
+ return `%s <= ${schema.exclusiveMinimum}`;
13
+ },
14
+ minimum(schema) {
15
+ return `%s < ${schema.minimum}`;
16
+ },
17
+ exclusiveMaximum(schema) {
18
+ return `%s >= ${schema.exclusiveMaximum}`;
19
+ },
20
+ maximum(schema) {
21
+ return `%s > ${schema.maximum}`;
22
+ },
23
+ multipleOf: '($1/$2) % 1 !== 0 && typeof $1 === "number"',
24
+ // When the instance value is a string
25
+ // this provides a regular expression that a string instance MUST match in order to be valid.
26
+ pattern(schema) {
27
+ let pattern;
28
+ let modifiers;
29
+
30
+ if (typeof schema.pattern === 'string') { pattern = schema.pattern; } else {
31
+ pattern = schema.pattern[0];
32
+ modifiers = schema.pattern[1];
33
+ }
34
+
35
+ const regex = new RegExp(pattern, modifiers);
36
+ return `typeof ($1) === "string" && !${regex}.test($1)`;
37
+ },
38
+ /**
39
+ * Creates an array containing the numeric code points of each Unicode
40
+ * character in the string. While JavaScript uses UCS-2 internally,
41
+ * this function will convert a pair of surrogate halves (each of which
42
+ * UCS-2 exposes as separate characters) into a single code point,
43
+ * matching UTF-16.
44
+ * @see `punycode.ucs2.encode`
45
+ * @see <https://mathiasbynens.be/notes/javascript-encoding>
46
+ * @memberOf punycode.ucs2
47
+ * @name decode
48
+ * @param {String} string The Unicode input string (UCS-2).
49
+ * @returns {Array} The new array of code points.
50
+ */
51
+ minLength: 'typeof $1 === "string" && function dltml(b,c){for(var a=0,d=b.length;a<d&&c;){var e=b.charCodeAt(a++);55296<=e&&56319>=e&&a<d&&56320!==(b.charCodeAt(a++)&64512)&&a--;c--}return!!c}($1, $2)',
52
+ maxLength: 'typeof $1 === "string" && function dmtml(b,c){for(var a=0,d=b.length;a<d&&0<=c;){var e=b.charCodeAt(a++);55296<=e&&56319>=e&&a<d&&56320!==(b.charCodeAt(a++)&64512)&&a--;c--}return 0>c}($1, $2)',
53
+ // This attribute defines the minimum number of values
54
+ // in an array when the array is the instance value.
55
+ minItems: '$1.length < $2 && Array.isArray($1)',
56
+ // This attribute defines the maximum number of values
57
+ // in an array when the array is the instance value.
58
+ maxItems: '$1.length > $2 && Array.isArray($1)',
59
+ // TODO without some
60
+ uniqueItems(schema, fn) {
61
+ if (!schema.uniqueItems) {
62
+ return 'true';
63
+ }
64
+
65
+ fn(fn.cache('{}'));
66
+ return `Array.isArray($1) && $1.some(function(item, key) {
67
+ if(item !== null && typeof item === "object") key = JSON.stringify(item);
68
+ else key = item;
69
+ if(${fn.cache('{}')}.hasOwnProperty(key)) return true;
70
+ ${fn.cache('{}')}[key] = true;
71
+ })`;
72
+ },
73
+ // ***** object validation ****
74
+ minProperties: '!Array.isArray($1) && typeof $1 === "object" && Object.keys($1).length < $2',
75
+ // An object instance is valid against "maxProperties"
76
+ // if its number of properties is less than, or equal to, the value of this keyword.
77
+ maxProperties: '!Array.isArray($1) && typeof $1 === "object" && Object.keys($1).length > $2',
78
+ // ****** all *****
79
+ enum(schema, fn) {
80
+ return schema.enum.map((value) => {
81
+ let $1 = '$1';
82
+ let comparedValue = value;
83
+
84
+ if (typeof value === 'object') {
85
+ comparedValue = `'${JSON.stringify(value)}'`;
86
+ $1 = fn.cache('JSON.stringify($1)');
87
+ } else if (typeof value === 'string') {
88
+ comparedValue = `'${escape(value)}'`;
89
+ }
90
+
91
+ return `${$1} != decodeURIComponent(${comparedValue})`;
92
+ }).join(' && ');
93
+ }
94
+ };
@@ -0,0 +1,91 @@
1
+ /**
2
+ * @module schema
3
+ * @description
4
+ * Low-level utilities to check, create and transform schemas
5
+ */
6
+
7
+ /**
8
+ * @name transformation
9
+ * @type {object}
10
+ * @description
11
+ * Schema values transformation
12
+ */
13
+ const transformation = {
14
+ ANY_SCHEMA: {},
15
+ NOT_ANY_SCHEMA: { not: {} },
16
+ };
17
+
18
+ /**
19
+ * @name is
20
+ * @type {function}
21
+ * @description
22
+ * Verify the object could be a schema
23
+ * Since draft-06 supports boolean as a schema definition
24
+ * @param {object} schema
25
+ * @returns {boolean} isSchema
26
+ */
27
+ function is(schema) {
28
+ return (
29
+ typeof schema === 'object' ||
30
+ typeof schema === 'boolean'
31
+ );
32
+ }
33
+
34
+ /**
35
+ * @name transform
36
+ * @type {function}
37
+ * @description
38
+ * Transform a schema pseudo presentation
39
+ * Since draft-06 supports boolean as a schema definition
40
+ * @param {object} schema
41
+ * @returns {object} schema
42
+ */
43
+ function transform(schema) {
44
+ if (schema === true) {
45
+ return transformation.ANY_SCHEMA;
46
+ } else if (schema === false) {
47
+ return transformation.NOT_ANY_SCHEMA;
48
+ }
49
+ return schema;
50
+ }
51
+
52
+ /**
53
+ * @name make
54
+ * @type {function}
55
+ * @description
56
+ * Generate a simple schema by a given object
57
+ * @param {any} instance
58
+ * @returns {object} schema
59
+ */
60
+ function make(instance) {
61
+ if (typeof instance !== 'object' || instance === null) {
62
+ return { enum: [instance] };
63
+ }
64
+
65
+ if (Array.isArray(instance)) {
66
+ return {
67
+ items: instance.map(make),
68
+ // other items should be valid by `false` schema, aka not exist at all
69
+ additionalItems: false
70
+ };
71
+ }
72
+
73
+ const required = Object.keys(instance);
74
+ return {
75
+ properties: required.reduce((memo, key) => (
76
+ Object.assign({}, memo, {
77
+ [key]: make(instance[key])
78
+ })
79
+ ), {}),
80
+ required,
81
+ // other properties should be valid by `false` schema, aka not exist at all
82
+ // additionalProperties: false,
83
+ };
84
+ }
85
+
86
+ module.exports = {
87
+ is,
88
+ make,
89
+ transform,
90
+ transformation,
91
+ };