-
Notifications
You must be signed in to change notification settings - Fork 200
/
Copy pathfromRdf.js
348 lines (313 loc) · 9.52 KB
/
fromRdf.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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
/*
* Copyright (c) 2017 Digital Bazaar, Inc. All rights reserved.
*/
'use strict';
const JsonLdError = require('./JsonLdError');
const graphTypes = require('./graphTypes');
const types = require('./types');
const util = require('./util');
// constants
const {
// RDF,
RDF_LIST,
RDF_FIRST,
RDF_REST,
RDF_NIL,
RDF_TYPE,
// RDF_PLAIN_LITERAL,
// RDF_XML_LITERAL,
RDF_JSON_LITERAL,
// RDF_OBJECT,
// RDF_LANGSTRING,
// XSD,
XSD_BOOLEAN,
XSD_DOUBLE,
XSD_INTEGER,
XSD_STRING,
} = require('./constants');
const REGEX_BCP47 = /^[a-zA-Z]{1,8}(-[a-zA-Z0-9]{1,8})*$/;
const api = {};
module.exports = api;
/**
* Converts an RDF dataset to JSON-LD.
*
* @param dataset the RDF dataset.
* @param options the RDF serialization options.
*
* @return a Promise that resolves to the JSON-LD output.
*/
api.fromRDF = async (
dataset,
{
useRdfType = false,
useNativeTypes = false,
rdfDirection = null,
preserveOrder = false,
}
) => {
const defaultGraph = {};
const graphMap = {'@default': defaultGraph};
const referencedOnce = {};
for(const quad of dataset) {
// TODO: change 'name' to 'graph'
const name = (quad.graph.termType === 'DefaultGraph') ?
'@default' : quad.graph.value;
if(!(name in graphMap)) {
graphMap[name] = {};
}
if(name !== '@default' && !(name in defaultGraph)) {
defaultGraph[name] = {'@id': name};
}
const nodeMap = graphMap[name];
// get subject, predicate, object
const s = quad.subject.value;
const p = quad.predicate.value;
const o = quad.object;
if(!(s in nodeMap)) {
nodeMap[s] = {'@id': s};
}
const node = nodeMap[s];
const objectIsNode = o.termType.endsWith('Node');
if(objectIsNode && !(o.value in nodeMap)) {
nodeMap[o.value] = {'@id': o.value};
}
if(p === RDF_TYPE && !useRdfType && objectIsNode) {
util.addValue(node, '@type', o.value, {propertyIsArray: true});
continue;
}
const value = _RDFToObject(o, useNativeTypes, rdfDirection);
util.addValue(node, p, value, {propertyIsArray: true});
// object may be an RDF list/partial list node but we can't know easily
// until all triples are read
if(objectIsNode) {
if(o.value === RDF_NIL) {
// track rdf:nil uniquely per graph
const object = nodeMap[o.value];
if(!('usages' in object)) {
object.usages = [];
}
object.usages.push({
node,
property: p,
value
});
} else if(o.value in referencedOnce) {
// object referenced more than once
referencedOnce[o.value] = false;
} else {
// keep track of single reference
referencedOnce[o.value] = {
node,
property: p,
value
};
}
}
}
/*
for(let name in dataset) {
const graph = dataset[name];
if(!(name in graphMap)) {
graphMap[name] = {};
}
if(name !== '@default' && !(name in defaultGraph)) {
defaultGraph[name] = {'@id': name};
}
const nodeMap = graphMap[name];
for(let ti = 0; ti < graph.length; ++ti) {
const triple = graph[ti];
// get subject, predicate, object
const s = triple.subject.value;
const p = triple.predicate.value;
const o = triple.object;
if(!(s in nodeMap)) {
nodeMap[s] = {'@id': s};
}
const node = nodeMap[s];
const objectIsId = (o.type === 'IRI' || o.type === 'blank node');
if(objectIsId && !(o.value in nodeMap)) {
nodeMap[o.value] = {'@id': o.value};
}
if(p === RDF_TYPE && !useRdfType && objectIsId) {
util.addValue(node, '@type', o.value, {propertyIsArray: true});
continue;
}
const value = _RDFToObject(o, useNativeTypes);
util.addValue(node, p, value, {propertyIsArray: true});
// object may be an RDF list/partial list node but we can't know easily
// until all triples are read
if(objectIsId) {
if(o.value === RDF_NIL) {
// track rdf:nil uniquely per graph
const object = nodeMap[o.value];
if(!('usages' in object)) {
object.usages = [];
}
object.usages.push({
node: node,
property: p,
value: value
});
} else if(o.value in referencedOnce) {
// object referenced more than once
referencedOnce[o.value] = false;
} else {
// keep track of single reference
referencedOnce[o.value] = {
node: node,
property: p,
value: value
};
}
}
}
}*/
// convert linked lists to @list arrays
for(const name in graphMap) {
const graphObject = graphMap[name];
// no @lists to be converted, continue
if(!(RDF_NIL in graphObject)) {
continue;
}
// iterate backwards through each RDF list
const nil = graphObject[RDF_NIL];
if(!nil.usages) {
continue;
}
for(let usage of nil.usages) {
let node = usage.node;
let property = usage.property;
let head = usage.value;
const list = [];
const listNodes = [];
// ensure node is a well-formed list node; it must:
// 1. Be referenced only once.
// 2. Have an array for rdf:first that has 1 item.
// 3. Have an array for rdf:rest that has 1 item.
// 4. Have no keys other than: @id, rdf:first, rdf:rest, and,
// optionally, @type where the value is rdf:List.
let nodeKeyCount = Object.keys(node).length;
while(property === RDF_REST &&
types.isObject(referencedOnce[node['@id']]) &&
types.isArray(node[RDF_FIRST]) && node[RDF_FIRST].length === 1 &&
types.isArray(node[RDF_REST]) && node[RDF_REST].length === 1 &&
(nodeKeyCount === 3 ||
(nodeKeyCount === 4 && types.isArray(node['@type']) &&
node['@type'].length === 1 && node['@type'][0] === RDF_LIST))) {
list.push(node[RDF_FIRST][0]);
listNodes.push(node['@id']);
// get next node, moving backwards through list
usage = referencedOnce[node['@id']];
node = usage.node;
property = usage.property;
head = usage.value;
nodeKeyCount = Object.keys(node).length;
// if node is not a blank node, then list head found
if(!graphTypes.isBlankNode(node)) {
break;
}
}
// transform list into @list object
delete head['@id'];
head['@list'] = list.reverse();
for(const listNode of listNodes) {
delete graphObject[listNode];
}
}
delete nil.usages;
}
const result = [];
const subjects = preserveOrder ? Object.keys(defaultGraph): Object.keys(defaultGraph).sort();
for(const subject of subjects) {
const node = defaultGraph[subject];
if(subject in graphMap) {
const graph = node['@graph'] = [];
const graphObject = graphMap[subject];
const graphSubjects = preserveOrder ? Object.keys(graphObject) : Object.keys(graphObject).sort();
for(const graphSubject of graphSubjects) {
const node = graphObject[graphSubject];
// only add full subjects to top-level
if(!graphTypes.isSubjectReference(node)) {
graph.push(node);
}
}
}
// only add full subjects to top-level
if(!graphTypes.isSubjectReference(node)) {
result.push(node);
}
}
return result;
};
/**
* Converts an RDF triple object to a JSON-LD object.
*
* @param o the RDF triple object to convert.
* @param useNativeTypes true to output native types, false not to.
*
* @return the JSON-LD object.
*/
function _RDFToObject(o, useNativeTypes, rdfDirection) {
// convert NamedNode/BlankNode object to JSON-LD
if(o.termType.endsWith('Node')) {
return {'@id': o.value};
}
// convert literal to JSON-LD
const rval = {'@value': o.value};
// add language
if(o.language) {
rval['@language'] = o.language;
} else {
let type = o.datatype.value;
if(!type) {
type = XSD_STRING;
}
if(type === RDF_JSON_LITERAL) {
type = '@json';
try {
rval['@value'] = JSON.parse(rval['@value']);
} catch(e) {
throw new JsonLdError(
'JSON literal could not be parsed.',
'jsonld.InvalidJsonLiteral',
{code: 'invalid JSON literal', value: rval['@value'], cause: e});
}
}
// use native types for certain xsd types
if(useNativeTypes) {
if(type === XSD_BOOLEAN) {
if(rval['@value'] === 'true') {
rval['@value'] = true;
} else if(rval['@value'] === 'false') {
rval['@value'] = false;
}
} else if(types.isNumeric(rval['@value'])) {
if(type === XSD_INTEGER) {
const i = parseInt(rval['@value'], 10);
if(i.toFixed(0) === rval['@value']) {
rval['@value'] = i;
}
} else if(type === XSD_DOUBLE) {
rval['@value'] = parseFloat(rval['@value']);
}
}
// do not add native type
if(![XSD_BOOLEAN, XSD_INTEGER, XSD_DOUBLE, XSD_STRING].includes(type)) {
rval['@type'] = type;
}
} else if(rdfDirection === 'i18n-datatype' &&
type.startsWith('https://www.w3.org/ns/i18n#')) {
const [, language, direction] = type.split(/[#_]/);
if(language.length > 0) {
rval['@language'] = language;
if(!language.match(REGEX_BCP47)) {
console.warn(`@language must be valid BCP47: ${language}`);
}
}
rval['@direction'] = direction;
} else if(type !== XSD_STRING) {
rval['@type'] = type;
}
}
return rval;
}