-
Notifications
You must be signed in to change notification settings - Fork 200
/
Copy pathtoRdf.js
470 lines (444 loc) · 13 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
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
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
/*
* Copyright (c) 2017-2023 Digital Bazaar, Inc. All rights reserved.
*/
'use strict';
const {createNodeMap} = require('./nodeMap');
const {isKeyword} = require('./context');
const graphTypes = require('./graphTypes');
const jsonCanonicalize = require('canonicalize');
const JsonLdError = require('./JsonLdError');
const types = require('./types');
const util = require('./util');
const {
handleEvent: _handleEvent
} = require('./events');
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 {
isAbsolute: _isAbsoluteIri
} = require('./url');
const api = {};
module.exports = api;
/**
* Outputs an RDF dataset for the expanded JSON-LD input.
*
* @param input the expanded JSON-LD input.
* @param options the RDF serialization options.
*
* @return the RDF dataset.
*/
api.toRDF = (input, options) => {
// create node map for default graph (and any named graphs)
const issuer = new util.IdentifierIssuer('_:b');
const nodeMap = {'@default': {}};
createNodeMap(input, nodeMap, '@default', issuer);
const dataset = [];
const graphNames = Object.keys(nodeMap).sort();
for(const graphName of graphNames) {
let graphTerm;
if(graphName === '@default') {
graphTerm = {termType: 'DefaultGraph', value: ''};
} else if(_isAbsoluteIri(graphName)) {
if(graphName.startsWith('_:')) {
graphTerm = {termType: 'BlankNode'};
} else {
graphTerm = {termType: 'NamedNode'};
}
graphTerm.value = graphName;
} else {
// skip relative IRIs (not valid RDF)
if(options.eventHandler) {
_handleEvent({
event: {
type: ['JsonLdEvent'],
code: 'relative graph reference',
level: 'warning',
message: 'Relative graph reference found.',
details: {
graph: graphName
}
},
options
});
}
continue;
}
_graphToRDF(dataset, nodeMap[graphName], graphTerm, issuer, options);
}
return dataset;
};
/**
* Adds RDF quads for a particular graph to the given dataset.
*
* @param dataset the dataset to append RDF quads to.
* @param graph the graph to create RDF quads for.
* @param graphTerm the graph term for each quad.
* @param issuer a IdentifierIssuer for assigning blank node names.
* @param options the RDF serialization options.
*
* @return the array of RDF triples for the given graph.
*/
function _graphToRDF(dataset, graph, graphTerm, issuer, options) {
const ids = Object.keys(graph).sort();
for(const id of ids) {
const node = graph[id];
const properties = Object.keys(node).sort();
for(let property of properties) {
const items = node[property];
if(property === '@type') {
property = RDF_TYPE;
} else if(isKeyword(property)) {
continue;
}
for(const item of items) {
// RDF subject
const subject = {
termType: id.startsWith('_:') ? 'BlankNode' : 'NamedNode',
value: id
};
// skip relative IRI subjects (not valid RDF)
if(!_isAbsoluteIri(id)) {
if(options.eventHandler) {
_handleEvent({
event: {
type: ['JsonLdEvent'],
code: 'relative subject reference',
level: 'warning',
message: 'Relative subject reference found.',
details: {
subject: id
}
},
options
});
}
continue;
}
// RDF predicate
const predicate = {
termType: property.startsWith('_:') ? 'BlankNode' : 'NamedNode',
value: property
};
// skip relative IRI predicates (not valid RDF)
if(!_isAbsoluteIri(property)) {
if(options.eventHandler) {
_handleEvent({
event: {
type: ['JsonLdEvent'],
code: 'relative predicate reference',
level: 'warning',
message: 'Relative predicate reference found.',
details: {
predicate: property
}
},
options
});
}
continue;
}
// skip blank node predicates unless producing generalized RDF
if(predicate.termType === 'BlankNode' &&
!options.produceGeneralizedRdf) {
if(options.eventHandler) {
_handleEvent({
event: {
type: ['JsonLdEvent'],
code: 'blank node predicate',
level: 'warning',
message: 'Dropping blank node predicate.',
details: {
// FIXME: add better issuer API to get reverse mapping
property: issuer.getOldIds()
.find(key => issuer.getId(key) === property)
}
},
options
});
}
continue;
}
// convert list, value or node object to triple
const object = _objectToRDF(
item, issuer, dataset, graphTerm, options.rdfDirection, options);
// skip null objects (they are relative IRIs)
if(object) {
dataset.push({
subject,
predicate,
object,
graph: graphTerm
});
}
}
}
}
}
/**
* Converts a @list value into linked list of blank node RDF quads
* (an RDF collection).
*
* @param list the @list value.
* @param issuer a IdentifierIssuer for assigning blank node names.
* @param dataset the array of quads to append to.
* @param graphTerm the graph term for each quad.
* @param options the RDF serialization options.
*
* @return the head of the list.
*/
function _listToRDF(list, issuer, dataset, graphTerm, rdfDirection, options) {
const first = {termType: 'NamedNode', value: RDF_FIRST};
const rest = {termType: 'NamedNode', value: RDF_REST};
const nil = {termType: 'NamedNode', value: RDF_NIL};
const last = list.pop();
// Result is the head of the list
const result = last ? {termType: 'BlankNode', value: issuer.getId()} : nil;
let subject = result;
for(const item of list) {
const object = _objectToRDF(
item, issuer, dataset, graphTerm, rdfDirection, options);
const next = {termType: 'BlankNode', value: issuer.getId()};
dataset.push({
subject,
predicate: first,
object,
graph: graphTerm
});
dataset.push({
subject,
predicate: rest,
object: next,
graph: graphTerm
});
subject = next;
}
// Tail of list
if(last) {
const object = _objectToRDF(
last, issuer, dataset, graphTerm, rdfDirection, options);
dataset.push({
subject,
predicate: first,
object,
graph: graphTerm
});
dataset.push({
subject,
predicate: rest,
object: nil,
graph: graphTerm
});
}
return result;
}
/**
* Converts a JSON-LD value object to an RDF literal or a JSON-LD string,
* node object to an RDF resource, or adds a list.
*
* @param item the JSON-LD value or node object.
* @param issuer a IdentifierIssuer for assigning blank node names.
* @param dataset the dataset to append RDF quads to.
* @param graphTerm the graph term for each quad.
* @param options the RDF serialization options.
*
* @return the RDF literal or RDF resource.
*/
function _objectToRDF(
item, issuer, dataset, graphTerm, rdfDirection, options
) {
const object = {};
// convert value object to RDF
if(graphTypes.isValue(item)) {
object.termType = 'Literal';
object.value = undefined;
object.datatype = {
termType: 'NamedNode'
};
let value = item['@value'];
const datatype = item['@type'] || null;
// convert to XSD/JSON datatypes as appropriate
if(datatype === '@json') {
object.value = jsonCanonicalize(value);
object.datatype.value = RDF_JSON_LITERAL;
} else if(types.isBoolean(value)) {
object.value = value.toString();
object.datatype.value = datatype || XSD_BOOLEAN;
} else if(types.isDouble(value) || datatype === XSD_DOUBLE) {
if(!types.isDouble(value)) {
value = parseFloat(value);
}
// canonical double representation
object.value = value.toExponential(15).replace(/(\d)0*e\+?/, '$1E');
object.datatype.value = datatype || XSD_DOUBLE;
} else if(types.isNumber(value)) {
object.value = value.toFixed(0);
object.datatype.value = datatype || XSD_INTEGER;
} else if('@direction' in item && rdfDirection === 'i18n-datatype') {
const language = (item['@language'] || '').toLowerCase();
const direction = item['@direction'];
const datatype = `https://www.w3.org/ns/i18n#${language}_${direction}`;
object.datatype.value = datatype;
object.value = value;
} else if('@direction' in item && rdfDirection === 'compound-literal') {
const language = (item['@language'] || '').toLowerCase();
const direction = item['@direction'];
// blank node
object.termType = 'BlankNode';
object.value = issuer.getId();
object.datatype = undefined;
// value
dataset.push({
subject: {
termType: object.termType,
value: object.value
},
predicate: {
termType: 'NamedNode',
value: RDF + 'value'
},
object: {
termType: 'Literal',
value,
datatype: {
termType: 'NamedNode',
value: XSD_STRING
}
},
graph: graphTerm
});
// language if preset
if(language !== '') {
dataset.push({
subject: {
termType: object.termType,
value: object.value
},
predicate: {
termType: 'NamedNode',
value: RDF + 'language'
},
object: {
termType: 'Literal',
value: language,
datatype: {
termType: 'NamedNode',
value: XSD_STRING
}
},
graph: graphTerm
});
}
// direction
dataset.push({
subject: {
termType: object.termType,
value: object.value
},
predicate: {
termType: 'NamedNode',
value: RDF + 'direction'
},
object: {
termType: 'Literal',
value: direction,
datatype: {
termType: 'NamedNode',
value: XSD_STRING
}
},
graph: graphTerm
});
} else if('@direction' in item && rdfDirection) {
throw new JsonLdError(
'Unknown rdfDirection value.',
'jsonld.InvalidRdfDirection',
{value: rdfDirection});
} else if('@language' in item) {
if('@direction' in item && rdfDirection === null) {
if(options.eventHandler) {
// FIXME: only emit once?
_handleEvent({
event: {
type: ['JsonLdEvent'],
code: 'rdfDirection not set',
level: 'warning',
message: 'rdfDirection not set for @direction.',
details: {
object: object.value
}
},
options
});
}
}
object.value = value;
object.datatype.value = datatype || RDF_LANGSTRING;
object.language = item['@language'];
} else {
if('@direction' in item && rdfDirection === null) {
if(options.eventHandler) {
// FIXME: only emit once?
_handleEvent({
event: {
type: ['JsonLdEvent'],
code: 'rdfDirection not set',
level: 'warning',
message: 'rdfDirection not set for @direction.',
details: {
object: object.value
}
},
options
});
}
}
object.value = value;
object.datatype.value = datatype || XSD_STRING;
}
} else if(graphTypes.isList(item)) {
const _list = _listToRDF(
item['@list'], issuer, dataset, graphTerm, rdfDirection, options);
object.termType = _list.termType;
object.value = _list.value;
} else {
// convert string/node object to RDF
const id = types.isObject(item) ? item['@id'] : item;
object.termType = id.startsWith('_:') ? 'BlankNode' : 'NamedNode';
object.value = id;
}
// skip relative IRIs, not valid RDF
if(object.termType === 'NamedNode' && !_isAbsoluteIri(object.value)) {
if(options.eventHandler) {
_handleEvent({
event: {
type: ['JsonLdEvent'],
code: 'relative object reference',
level: 'warning',
message: 'Relative object reference found.',
details: {
object: object.value
}
},
options
});
}
return null;
}
return object;
}