-
Notifications
You must be signed in to change notification settings - Fork 25
/
toRdf.js
77 lines (59 loc) · 2.18 KB
/
toRdf.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
68
69
70
71
72
73
74
75
76
77
// original file https://raw.githubusercontent.com/w3c/wot-thing-description/main/context/toRDF.js
const fs = require('fs');
const ld = 'http://www.w3.org/ns/json-ld#';
const a = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#type';
function fullIRI(curie, ctx) {
let capture = /^(\w+):(\w+)$/.exec(curie);
if (capture) {
let [str, ns, name] = capture;
if (ctx[ns]) return ctx[ns] + name;
else console.warn('No mapping found for prefix ' + ns);
}
return curie;
}
function scopeName(id) {
return id ? id.substring(id.indexOf('#') + 1) + "-" : ""; // TODO hash
}
function context(obj, id) {
let ctx = obj['@context'];
let scope = scopeName(id);
if (!ctx) {
return '';
}
let txt = `_:${scope}context <${a}> <${ld}Context> .\r\n`;
if (ctx['@vocab']) {
let vocab = fullIRI(ctx['@vocab'], ctx);
txt += `_:${scope}context <${ld}vocab> <${vocab}> .\r\n`;
}
Object.entries(ctx)
.filter(([k, v]) => !k.startsWith('@'))
.map(([k, v]) => {
txt += `_:${scope}context <${ld}definition> _:${scope}${k} .\r\n`;
txt += `_:${scope}${k} <${a}> <${ld}Mapping> .\r\n`;
txt += `_:${scope}${k} <${ld}term> "${k}" .\r\n`;
let iri = fullIRI(v instanceof Object ? v['@id'] : v, ctx);
if (!iri.startsWith('@')) {
txt += `_:${scope}${k} <${ld}iri> <${iri}> .\r\n`;
}
if (v instanceof Object) {
if (v['@container']) {
let container = v['@container'].replace('@', '');
txt += `_:${scope}${k} <${ld}container> <${ld + container}> .\r\n`;
}
if (v['@type']) {
let type = v['@type'];
if (type != '@id' && type != '@vocab') {
txt += `_:${scope}${k} <${ld}type> <${type}> .\r\n`;
}
}
if (v['@context']) {
txt += `_:${scope}${k} <${ld}context> _:${scopeName(iri)}context .\r\n`;
txt += context(v, iri);
}
}
});
return txt;
}
module.exports = {
context
}