UNPKG

1.97 kBJavaScriptView Raw
1/*
2 * Copyright 2019 Adobe. All rights reserved.
3 * This file is licensed to you under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License. You may obtain a copy
5 * of the License at http://www.apache.org/licenses/LICENSE-2.0
6 *
7 * Unless required by applicable law or agreed to in writing, software distributed under
8 * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
9 * OF ANY KIND, either express or implied. See the License for the specific language
10 * governing permissions and limitations under the License.
11 */
12
13const { list, eq, contains } = require('ferrum');
14const { parent, pointer } = require('./symbols');
15
16function isSkippableKeyword(schema) {
17 const skippableKeywords = ['examples', 'required', 'properties'];
18 const containsCurrentSchema = contains((keyword) => eq(keyword, schema[pointer].split('/').pop()));
19
20 return containsCurrentSchema(skippableKeywords);
21}
22
23function reducer({ seen, ids }, schema) {
24 if (schema
25 && schema[parent]
26 && (seen.has(schema) || (schema.$id && ids.indexOf(schema.$id) >= 0))) {
27 return { seen, ids };
28 } else if (Array.isArray(schema)) {
29 if (isSkippableKeyword(schema)) {
30 return { seen, ids };
31 }
32 return schema.reduce(reducer, { seen, ids });
33 } else if (schema && typeof schema === 'object') {
34 if (isSkippableKeyword(schema)) {
35 return [...Object.values(schema)].reduce(reducer, { seen, ids });
36 }
37 seen.add(schema);
38 if (schema.$id) {
39 ids.push(schema.$id);
40 }
41 return [...Object.values(schema)].reduce(reducer, { seen, ids });
42 }
43 return { seen, ids };
44}
45
46/**
47 * Traverses a Schema node (containing a JSON Schema) to find sub-schemas,
48 * which are then emitted as asequence.
49 * @param {Schema} node
50 */
51function traverse(schemas) {
52 return Array.from(list(schemas).reduce(reducer, { seen: new Set(), ids: [] }).seen);
53}
54
55module.exports = traverse;