@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.
@@ -0,0 +1,273 @@
1
+ /**
2
+ * @module state
3
+ * @description
4
+ * State module is responsible for scope schemas resolution.
5
+ * It also exports a main `generate` function.
6
+ */
7
+
8
+ const { list: validators } = require('../validators');
9
+ const { body, restore, template } = require('./template');
10
+ const { hasProperty } = require('./');
11
+ const {
12
+ normalize,
13
+ makePath,
14
+ head,
15
+ isFullUri,
16
+ fragment,
17
+ keys,
18
+ } = require('./uri');
19
+ const {
20
+ is: isSchema,
21
+ transform: transformSchema,
22
+ } = require('./schema');
23
+
24
+ /* eslint-disable no-unused-vars */
25
+ function State(schema = {}, env) {
26
+ /* eslint-enable no-unused-vars */
27
+ Object.assign(this, {
28
+ context: [],
29
+ entries: new Map(),
30
+ env,
31
+ });
32
+ }
33
+
34
+ /**
35
+ * @name generate
36
+ * @type {function}
37
+ * @description
38
+ * The main schema process function.
39
+ * Available and used both in external and internal generation.
40
+ * Saves the state for internal recursive calls.
41
+ * @param {object} env - djv environment
42
+ * @param {object} schema - to process
43
+ * @param {State} state - saved state
44
+ * @param {Environment} options
45
+ * @returns {function} restoredFunction
46
+ */
47
+ function generate(env, schema, state = new State(schema, env), options) {
48
+ const tpl = template(state, options);
49
+ tpl.visit(schema);
50
+
51
+ const source = body(tpl, state, options);
52
+ return restore(source, schema, options);
53
+ }
54
+
55
+ State.prototype = Object.assign(Object.create(Array.prototype), {
56
+ /**
57
+ * @name addEntry
58
+ * @type {function}
59
+ * @description
60
+ * Generates an internal function.
61
+ * Usually necessary for `allOf` types of validators.
62
+ * Caches generated functions by schema object key.
63
+ * Checks for an existing schema in a context stack to avoid double parsing and generation.
64
+ * @param {string} url
65
+ * @param {object} schema
66
+ * @returns {number/boolean} index
67
+ */
68
+ addEntry(url, schema) {
69
+ let entry = this.entries.get(schema);
70
+ if (entry === false) {
71
+ // has already been added to process queue
72
+ // will be revealed as an entry
73
+ return this.context.push(schema);
74
+ }
75
+
76
+ if (typeof entry === 'undefined') {
77
+ // start to process schema
78
+ this.entries.set(schema, false);
79
+ entry = generate(this.env, schema, this, { inner: true });
80
+ this.entries.set(schema, entry);
81
+ this.revealReference(schema);
82
+ }
83
+
84
+ return this.context.push(entry);
85
+ },
86
+ /**
87
+ * @name revealReference
88
+ * @type {function}
89
+ * @description
90
+ * If a schema was added during the add entry phase
91
+ * Then it should be revealed in this step
92
+ * @param {object} schema
93
+ * @returns {void}
94
+ */
95
+ revealReference(schema) {
96
+ for (
97
+ let doubled = this.context.indexOf(schema);
98
+ doubled !== -1;
99
+ doubled = this.context.indexOf(schema)
100
+ ) {
101
+ this.context[doubled] = this.context.length;
102
+ }
103
+ },
104
+ /**
105
+ * @name link
106
+ * @type {function}
107
+ * @description
108
+ * Returns an entry's index in a context stack.
109
+ * @param {string} url
110
+ * @returns {string} entry
111
+ */
112
+ link(url) {
113
+ const schema = this.resolve(url);
114
+ const entry = this.addEntry(url, schema);
115
+ return entry;
116
+ },
117
+ /**
118
+ * @name resolveReference
119
+ * @type {function}
120
+ * @description
121
+ * Resolve reference against the stack.
122
+ * @param {string} reference
123
+ * @returns {string} resolvedReference
124
+ */
125
+ resolveReference(reference) {
126
+ if (isFullUri(reference)) {
127
+ return reference;
128
+ }
129
+
130
+ // find last full URI schema
131
+ let lastFullURIReference;
132
+ let lastFullURISchemaIndex;
133
+
134
+ for (let i = this.length - 1; i >= 0; i -= 1, lastFullURIReference = false) {
135
+ const { [keys.id]: id, $ref } = this[i];
136
+ lastFullURIReference = id || $ref;
137
+ if (isFullUri(lastFullURIReference)) {
138
+ lastFullURISchemaIndex = i;
139
+ break;
140
+ }
141
+ }
142
+
143
+ // collect all partial routes for it
144
+ const partialReferences = [];
145
+ for (let i = this.length - 1; i > lastFullURISchemaIndex; i -= 1) {
146
+ const { [keys.id]: id, $ref } = this[i];
147
+ const partialReference = id || $ref;
148
+ if (head(partialReference)) {
149
+ partialReferences.push(partialReference);
150
+ }
151
+ }
152
+
153
+ // attach reference and make path
154
+ const path = makePath([lastFullURIReference, ...partialReferences, reference]);
155
+ return path;
156
+ },
157
+ /**
158
+ * @name ascend
159
+ * @private
160
+ * @type {function}
161
+ * @description
162
+ * Search for a parent schema by reference.
163
+ * Iterates over the chain of schemas.
164
+ * @param {string} reference
165
+ * @returns {object} parentSchema
166
+ */
167
+ ascend(reference) {
168
+ const path = head(reference);
169
+ let { schema: parentSchema = this[0] } = this.env.resolved[path] || {};
170
+
171
+ // Search while it is a full schema, not a ref
172
+ while (
173
+ parentSchema.$ref &&
174
+ // avoid infinite loop
175
+ head(parentSchema.$ref) !== head(reference) &&
176
+ // > All other properties in a "$ref" object MUST be ignored.
177
+ // @see https://tools.ietf.org/html/draft-wright-json-schema-01#section-8
178
+ Object.keys(parentSchema).length === 1
179
+ ) {
180
+ parentSchema = this.ascend(parentSchema.$ref);
181
+ }
182
+
183
+ return parentSchema;
184
+ },
185
+ /**
186
+ * @name descend
187
+ * @private
188
+ * @type {function}
189
+ * @description
190
+ * Search for a child schema by reference.
191
+ * Iterates over the chain of schemas.
192
+ * @param {string} reference
193
+ * @returns {object} currentSchema
194
+ */
195
+ descend(reference, parentSchema) {
196
+ let uriFragment = fragment(reference);
197
+ if (!uriFragment && isFullUri(reference)) {
198
+ return parentSchema;
199
+ }
200
+
201
+ if (!uriFragment) {
202
+ uriFragment = reference;
203
+ }
204
+
205
+ const parts = uriFragment.split('/');
206
+ const currentSchema = parts
207
+ .map(normalize)
208
+ .reduce((schema, part, index) => {
209
+ let subSchema = schema[part];
210
+ if (!isSchema(subSchema)) {
211
+ subSchema = schema.definitions && schema.definitions[part];
212
+ }
213
+
214
+ if (
215
+ // last will be pushed on visit
216
+ // @see /draft4/refRemote.json:http://localhost:1234/scope_change_defs2.json
217
+ index !== parts.length - 1 &&
218
+ hasProperty(subSchema, keys.id)
219
+ ) {
220
+ this.push(subSchema);
221
+ }
222
+
223
+ return subSchema;
224
+ }, parentSchema);
225
+
226
+ return isSchema(currentSchema) ? currentSchema : parentSchema;
227
+ },
228
+ /**
229
+ * @name resolve
230
+ * @type {function}
231
+ * @description
232
+ * Resolves schema by given reference and current registered context stack.
233
+ * @param {string} url
234
+ * @returns {object} schema
235
+ */
236
+ resolve(reference) {
237
+ if (typeof reference !== 'string') {
238
+ return reference;
239
+ }
240
+
241
+ const fullReference = this.resolveReference(reference);
242
+ const parentSchema = this.ascend(fullReference);
243
+ const subSchema = this.descend(reference, parentSchema);
244
+
245
+ return subSchema;
246
+ },
247
+ /**
248
+ * @name visit
249
+ * @type {function}
250
+ * @description
251
+ * Calls each registered validator with given schema and template instance.
252
+ * Validator may or may not add code to generated validator function.
253
+ * @param {object} pseudoSchema
254
+ * @param {object} tpl
255
+ * @returns {void}
256
+ */
257
+ visit(pseudoSchema, tpl) {
258
+ const schema = transformSchema(pseudoSchema);
259
+ const initialLength = this.length;
260
+ this.push(schema);
261
+
262
+ validators.some(validator => (
263
+ validator(schema, tpl)
264
+ ));
265
+
266
+ this.length = initialLength;
267
+ },
268
+ });
269
+
270
+ module.exports = {
271
+ State,
272
+ generate,
273
+ };
@@ -0,0 +1,308 @@
1
+ /**
2
+ * @module template
3
+ * @description
4
+ * Defines a small templater functionality for creating functions body.
5
+ */
6
+
7
+ function sanitizeString(str) {
8
+ if (typeof str !== 'string') {
9
+ return str;
10
+ }
11
+
12
+ const sanitzedStr = String.prototype.replace.call(str, /[^a-z0-9áéíóúñü .,_-]/gim, '');
13
+ return String.prototype.trim.call(sanitzedStr);
14
+ }
15
+
16
+ /**
17
+ * @name template
18
+ * @type function
19
+ * @description
20
+ * Provides a templater function, which adds a line of code into generated function body.
21
+ *
22
+ * @param {object} state - used in visit and reference method to iterate and find schemas.
23
+ * @param {DjvConfig} options
24
+ * @return {function} tpl
25
+ */
26
+ function template(state, options) {
27
+ function tpl(expression, ...args) {
28
+ let last;
29
+
30
+ tpl.lines.push(
31
+ expression
32
+ .replace(/%i/g, () => 'i')
33
+ .replace(/\$(\d)/g, (match, index) => `${sanitizeString(args[index - 1])}`)
34
+ .replace(/(%[sd])/g, () => {
35
+ if (args.length) {
36
+ last = args.shift();
37
+ }
38
+
39
+ return `${last}`;
40
+ })
41
+ );
42
+
43
+ return tpl;
44
+ }
45
+
46
+ function clearDecode(tplString) {
47
+ return tplString
48
+ .replace('[', '')
49
+ .replace(']', '')
50
+ .replace('(', '')
51
+ .replace(')', '')
52
+ .replace('decodeURIComponent', '');
53
+ }
54
+
55
+ const error = typeof options.errorHandler === 'function' ?
56
+ options.errorHandler :
57
+ function defaultErrorHandler(errorType) {
58
+ const path = this.data.toString()
59
+ .replace(/^data/, '');
60
+ const dataPath = path
61
+ .replace(/\['([^']+)'\]/ig, '.$1')
62
+ .replace(/\[(i[0-9]*)\]/ig, '[\'+$1+\']');
63
+ const schemaPath = `#${
64
+ path
65
+ .replace(/\[i([0-9]*)\]/ig, '/items')
66
+ .replace(/\['([^']+)'\]/ig, '/properties/$1')
67
+ }/${errorType}`;
68
+
69
+ return `return {
70
+ keyword: '${errorType}',
71
+ dataPath: decodeURIComponent("${clearDecode(dataPath)}"),
72
+ schemaPath: decodeURIComponent("${clearDecode(schemaPath)}")
73
+ };`;
74
+ };
75
+
76
+ Object.assign(tpl, {
77
+ cachedIndex: 0,
78
+ cached: [],
79
+ cache(expression) {
80
+ const layer = tpl.cached[tpl.cached.length - 1];
81
+ if (layer[expression]) {
82
+ return `i${layer[expression]}`;
83
+ }
84
+
85
+ tpl.cachedIndex += 1;
86
+ layer[expression] = tpl.cachedIndex;
87
+ return `(i${layer[expression]} = ${expression})`;
88
+ },
89
+ data: ['data'],
90
+ error,
91
+ lines: [],
92
+ schema: ['schema'],
93
+ push: tpl,
94
+ /**
95
+ * @name link
96
+ * @description
97
+ * Get schema validator by url
98
+ * Call state link to generate or get cached function
99
+ * @type {function}
100
+ * @param {string} url
101
+ * @return {string} functionName
102
+ */
103
+ link(url) {
104
+ return `f${state.link(url)}`;
105
+ },
106
+ /**
107
+ * @name visit
108
+ * @description
109
+ * Create new cache scope and visit given schema
110
+ * @type {function}
111
+ * @param {object} schema
112
+ * @return {void}
113
+ */
114
+ visit(schema) {
115
+ tpl.cached.push({});
116
+ state.visit(schema, tpl);
117
+ tpl.cached.pop();
118
+ },
119
+ });
120
+
121
+ function dataToString() {
122
+ return this.join('.').replace(/\.\[/g, '[');
123
+ }
124
+ tpl.data.toString = dataToString;
125
+ tpl.schema.toString = dataToString;
126
+
127
+ return tpl;
128
+ }
129
+
130
+ /**
131
+ * @name restore
132
+ * @type function
133
+ * @description
134
+ * Generate a function by given body with a schema in a closure
135
+ *
136
+ * @param {string} source - function inner & outer body
137
+ * @param {object} schema - passed as argument to meta function
138
+ * @param {DjvConfig} config
139
+ * @return {function} tpl
140
+ */
141
+ function restore(source, schema, { inner } = {}) {
142
+ /* eslint-disable no-new-func */
143
+ const tpl = new Function('schema', source)(schema);
144
+ /* eslint-enable no-new-func */
145
+
146
+ if (!inner) {
147
+ tpl.toString = function toString() {
148
+ return source;
149
+ };
150
+ }
151
+
152
+ return tpl;
153
+ }
154
+
155
+ /**
156
+ * Configuration for template functions
157
+ * @typedef {object} TemplateOptions
158
+ * @property {string[]} context
159
+ * @property {string[]} index
160
+ * @property {boolean?} inner - a generating object should be considered as inner
161
+ * @property {boolean?} defineErrors - if erros should be defined
162
+ * @property {string[]} lines - content templates
163
+ */
164
+
165
+ /**
166
+ * @private
167
+ * @name makeVariables
168
+ * @type function
169
+ * @description
170
+ * Generate internal variables
171
+ *
172
+ * @param {TemplateOptions} options
173
+ * @return {string} variables
174
+ */
175
+ function makeVariables({ defineErrors, index }) {
176
+ /**
177
+ * @var {array} errors - empty array for pushing errors ability
178
+ * @see errorHandler
179
+ */
180
+ const errors = defineErrors ? 'const errors = [];' : '';
181
+ const variables = index ?
182
+ `let i${Array(...Array(index))
183
+ .map((value, i) => i + 1)
184
+ .join(',i')};` :
185
+ '';
186
+
187
+ // @see map array with holes trick
188
+ // http://2ality.com/2013/11/initializing-arrays.html
189
+ // TODO change var to const
190
+ return `
191
+ ${errors}
192
+ ${variables}
193
+ `;
194
+ }
195
+
196
+ /**
197
+ * @private
198
+ * @name makeHelpers
199
+ * @type function
200
+ * @description
201
+ * Generate internal helpers executed in outer function
202
+ *
203
+ * @param {TemplateOptions} options
204
+ * @return {string} functions
205
+ */
206
+ function makeHelpers({ context, inner }) {
207
+ if (inner || !context.length) {
208
+ return '';
209
+ }
210
+
211
+ const functions = [];
212
+ const references = [];
213
+
214
+ context
215
+ .forEach((value, i) => {
216
+ if (typeof value === 'number') {
217
+ references.push(`${i + 1} = f${value + 1}`);
218
+ return;
219
+ }
220
+ functions.push(`${i + 1} = ${value}`);
221
+ });
222
+
223
+ return `const f${functions.concat(references).join(', f')};`;
224
+ }
225
+
226
+ /**
227
+ * @private
228
+ * @name makeContent
229
+ * @type function
230
+ * @description
231
+ * Generate internal function body content, including variables
232
+ *
233
+ * @param {TemplateOptions} options
234
+ * @return {string} functions
235
+ */
236
+ function makeContent(options) {
237
+ const { defineErrors, lines } = options;
238
+
239
+ const variables = makeVariables(options);
240
+ const errors = defineErrors ? 'if(errors.length) return errors;' : '';
241
+ const content = lines.join('\n');
242
+
243
+ return `
244
+ "use strict";
245
+ ${variables}
246
+ ${content}
247
+ ${errors}
248
+ `;
249
+ }
250
+
251
+ /**
252
+ * @name body
253
+ * @type function
254
+ * @description
255
+ * Generate a function body, containing internal variables and helpers
256
+ *
257
+ * @param {object} tpl - template instance, containing all analyzed schema related data
258
+ * @param {object} state - state of schema generation
259
+ * @param {DjvConfig} config
260
+ * @return {string} body
261
+ */
262
+ function body({ cachedIndex, lines }, { context }, { inner, errorHandler } = {}) {
263
+ const options = {
264
+ context,
265
+ inner,
266
+ defineErrors: errorHandler,
267
+ index: cachedIndex,
268
+ lines,
269
+ };
270
+
271
+ const helpers = makeHelpers(options);
272
+ const content = makeContent(options);
273
+
274
+ return `
275
+ ${helpers}
276
+ function f0(data) {
277
+ ${content}
278
+ }
279
+ return f0;
280
+ `;
281
+ }
282
+
283
+ /**
284
+ * @name templateExpression
285
+ * @type function
286
+ * @description
287
+ * Es6 template helper function
288
+ * Transforms a validator utilities into generated functions body
289
+ * @return {function} template
290
+ */
291
+ function templateExpression(strings, ...keys) {
292
+ return (...values) => {
293
+ let dict = values[values.length - 1] || {};
294
+ let result = [strings[0]];
295
+ keys.forEach((key, i) => {
296
+ let value = Number.isInteger(key) ? values[key] : dict[key];
297
+ result.push(value, strings[i + 1]);
298
+ });
299
+ return result.join('');
300
+ };
301
+ }
302
+
303
+ module.exports = {
304
+ body,
305
+ restore,
306
+ template,
307
+ expression: templateExpression,
308
+ };
@@ -0,0 +1,10 @@
1
+ module.exports = {
2
+ null: '%s !== null',
3
+ string: 'typeof %s !== "string"',
4
+ boolean: 'typeof %s !== "boolean"',
5
+ number: 'typeof %s !== "number" || %s !== %s',
6
+ integer: 'typeof %s !== "number" || %s % 1 !== 0',
7
+ object: '!%s || typeof %s !== "object" || Array.isArray(%s)',
8
+ array: '!Array.isArray(%s)',
9
+ date: '!(%s instanceof Date)'
10
+ };
@@ -0,0 +1,133 @@
1
+ /**
2
+ * @module utils
3
+ * @description
4
+ * Utilities to check and normalize uri
5
+ */
6
+ const REGEXP_URI = /:\/\//;
7
+ const REGEXP_URI_FRAGMENT = /#\/?/;
8
+ const REGEXP_URI_PATH = /(^[^:]+:\/\/[^?#]*\/).*/;
9
+
10
+ /**
11
+ * @name keys
12
+ * @type {object}
13
+ * @description
14
+ * Keys to apply schema attributes & values
15
+ */
16
+ const keys = {
17
+ id: '$id',
18
+ };
19
+
20
+ /**
21
+ * @name head
22
+ * @type {function}
23
+ * @description
24
+ * Clean an id from its fragment
25
+ * @example
26
+ * head('http://domain.domain:2020/test/a#test')
27
+ * // returns 'http://domain.domain:2020/test/a'
28
+ * @param {string} id
29
+ * @returns {string} cleaned
30
+ */
31
+ function head(uri) {
32
+ if (typeof uri !== 'string') {
33
+ return uri;
34
+ }
35
+
36
+ const parts = uri.split(REGEXP_URI_FRAGMENT);
37
+ return parts[0];
38
+ }
39
+
40
+ function isFullUri(uri) {
41
+ return REGEXP_URI.test(uri);
42
+ }
43
+
44
+ /**
45
+ * @name path
46
+ * @type {function}
47
+ * @description
48
+ * Gets a scheme, domain and a path part from the uri
49
+ * @example
50
+ * path('http://domain.domain:2020/test/a?test')
51
+ * // returns 'http://domain.domain:2020/test/'
52
+ * @param {string} uri
53
+ * @returns {string} path
54
+ */
55
+ function path(uri) {
56
+ return uri.replace(REGEXP_URI_PATH, '$1');
57
+ }
58
+
59
+ /**
60
+ * @description
61
+ * Get the fragment (#...) part of the uri
62
+ * @see https://tools.ietf.org/html/rfc3986#section-3
63
+ * @param {string} uri
64
+ * @returns {string} fragment
65
+ */
66
+ function fragment(uri) {
67
+ if (typeof uri !== 'string') {
68
+ return uri;
69
+ }
70
+
71
+ const parts = uri.split(REGEXP_URI_FRAGMENT);
72
+ return parts[1];
73
+ }
74
+
75
+ /**
76
+ * @name makePath
77
+ * @type function
78
+ * @description
79
+ * Concat parts into single uri
80
+ * @see https://tools.ietf.org/html/rfc3986#section-3
81
+ * @param {array<string>} parts
82
+ * @returns {string} uri
83
+ */
84
+ function makePath(parts) {
85
+ return parts
86
+ .filter(part => typeof part === 'string')
87
+ .reduce((uri, id) => {
88
+ // if id is full replace uri
89
+ if (!uri.length || isFullUri(id)) {
90
+ return id;
91
+ }
92
+ if (!id) {
93
+ return uri;
94
+ }
95
+
96
+ // if fragment found
97
+ if (id.indexOf('#') === 0) {
98
+ // should replace uri's sharp with id
99
+ const sharpUriIndex = uri.indexOf('#');
100
+ if (sharpUriIndex === -1) {
101
+ return uri + id;
102
+ }
103
+
104
+ return uri.slice(0, sharpUriIndex) + id;
105
+ }
106
+
107
+ // get path part of uri
108
+ // and replace the rest with id
109
+ const partialUri = path(uri) + id;
110
+ return partialUri + (partialUri.indexOf('#') === -1 ? '#' : '');
111
+ }, '');
112
+ }
113
+
114
+ /**
115
+ * @name normalize
116
+ * @type {function}
117
+ * @description
118
+ * Replace json-pointer special symbols in a given uri.
119
+ * @param {string} uri
120
+ * @returns {string} normalizedUri
121
+ */
122
+ function normalize(uri) {
123
+ return decodeURIComponent(uri.replace(/~1/g, '/').replace(/~0/g, '~'));
124
+ }
125
+
126
+ module.exports = {
127
+ makePath,
128
+ isFullUri,
129
+ head,
130
+ fragment,
131
+ normalize,
132
+ keys,
133
+ };