-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
67 lines (54 loc) · 1.59 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
var extend = require('xtend');
var isSchema = require('schema-is-schema');
var normalizeId = require('./lib/normalizeId');
module.exports = function jsonldContext (schema) {
// ensure schema
isSchema(schema, { throw: true });
return schemaToContext(schema);
};
function schemaToContext (schema, name) {
// create context to return
var context = {};
// prefixes
for (var key in schema.prefixes) {
var val = schema.prefixes[key];
if (typeof key === 'string' && key.length === 0) {
key = "@vocab";
}
context[key] = val;
}
// if has id, use normlized id as name
if (schema.id) {
name = normalizeId(schema.id);
}
// current level context
if (schema.context) {
context[name] = schema.context;
}
// if schema composed of many schemas, recurse into each and combine with extend
var manySchema = schema.allOf || schema.anyOf || schema.oneOf;
if (manySchema) {
var manyContexts = manySchema.map(function (aSchema) {
return schemaToContext(aSchema, name);
})
context = extend.apply(this, [context].concat(manyContexts));
}
// if array of items, recurse into items schema
if (schema.type === 'array' && schema.items) {
context = extend(context, schemaToContext(schema.items, name));
}
// property contexts
for (var key in schema.properties) {
var val = schema.properties[key];
if (val.context) {
context = extend(context, schemaToContext(val, key));
}
};
// strip when key, value is the same
for (var key in context) {
if (key === context[key]) {
delete context[key];
}
}
return context;
}