make[1]: Entering directory `/work/src/jsonld.js'
Line | Hits | Source |
---|---|---|
1 | /** | |
2 | * A JavaScript implementation of the JSON-LD API. | |
3 | * | |
4 | * @author Dave Longley | |
5 | * | |
6 | * BSD 3-Clause License | |
7 | * Copyright (c) 2011-2013 Digital Bazaar, Inc. | |
8 | * All rights reserved. | |
9 | * | |
10 | * Redistribution and use in source and binary forms, with or without | |
11 | * modification, are permitted provided that the following conditions are met: | |
12 | * | |
13 | * Redistributions of source code must retain the above copyright notice, | |
14 | * this list of conditions and the following disclaimer. | |
15 | * | |
16 | * Redistributions in binary form must reproduce the above copyright | |
17 | * notice, this list of conditions and the following disclaimer in the | |
18 | * documentation and/or other materials provided with the distribution. | |
19 | * | |
20 | * Neither the name of the Digital Bazaar, Inc. nor the names of its | |
21 | * contributors may be used to endorse or promote products derived from | |
22 | * this software without specific prior written permission. | |
23 | * | |
24 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS | |
25 | * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED | |
26 | * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A | |
27 | * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT | |
28 | * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, | |
29 | * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED | |
30 | * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR | |
31 | * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF | |
32 | * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING | |
33 | * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS | |
34 | * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. | |
35 | */ | |
36 | 1 | (function() { |
37 | ||
38 | // determine if in-browser or using node.js | |
39 | 1 | var _nodejs = (typeof module === 'object' && module.exports); |
40 | 1 | var _browser = !_nodejs && window; |
41 | ||
42 | // attaches jsonld API to the given object | |
43 | 1 | var wrapper = function(jsonld) { |
44 | ||
45 | /* Core API */ | |
46 | ||
47 | /** | |
48 | * Performs JSON-LD compaction. | |
49 | * | |
50 | * @param input the JSON-LD input to compact. | |
51 | * @param ctx the context to compact with. | |
52 | * @param [options] options to use: | |
53 | * [base] the base IRI to use. | |
54 | * [strict] use strict mode (default: true). | |
55 | * [compactArrays] true to compact arrays to single values when | |
56 | * appropriate, false not to (default: true). | |
57 | * [graph] true to always output a top-level graph (default: false). | |
58 | * [skipExpansion] true to assume the input is expanded and skip | |
59 | * expansion, false not to, defaults to false. | |
60 | * [loadContext(url, callback(err, url, result))] the context loader. | |
61 | * @param callback(err, compacted, ctx) called once the operation completes. | |
62 | */ | |
63 | 2 | jsonld.compact = function(input, ctx, options, callback) { |
64 | // get arguments | |
65 | 86 | if(typeof options === 'function') { |
66 | 0 | callback = options; |
67 | 0 | options = {}; |
68 | } | |
69 | 86 | options = options || {}; |
70 | ||
71 | // nothing to compact | |
72 | 86 | if(input === null) { |
73 | 0 | return callback(null, null); |
74 | } | |
75 | ||
76 | // set default options | |
77 | 86 | if(!('base' in options)) { |
78 | 0 | options.base = ''; |
79 | } | |
80 | 86 | if(!('strict' in options)) { |
81 | 86 | options.strict = true; |
82 | } | |
83 | 86 | if(!('compactArrays' in options)) { |
84 | 86 | options.compactArrays = true; |
85 | } | |
86 | 86 | if(!('graph' in options)) { |
87 | 65 | options.graph = false; |
88 | } | |
89 | 86 | if(!('skipExpansion' in options)) { |
90 | 65 | options.skipExpansion = false; |
91 | } | |
92 | 86 | if(!('loadContext' in options)) { |
93 | 65 | options.loadContext = jsonld.loadContext; |
94 | } | |
95 | ||
96 | 86 | var expand = function(input, options, callback) { |
97 | 86 | if(options.skipExpansion) { |
98 | 21 | return callback(null, input); |
99 | } | |
100 | 65 | jsonld.expand(input, options, callback); |
101 | }; | |
102 | ||
103 | // expand input then do compaction | |
104 | 86 | expand(input, options, function(err, expanded) { |
105 | 86 | if(err) { |
106 | 0 | return callback(new JsonLdError( |
107 | 'Could not expand input before compaction.', | |
108 | 'jsonld.CompactError', {cause: err})); | |
109 | } | |
110 | ||
111 | // process context | |
112 | 86 | var activeCtx = _getInitialContext(options); |
113 | 86 | jsonld.processContext(activeCtx, ctx, options, function(err, activeCtx) { |
114 | 86 | if(err) { |
115 | 0 | return callback(new JsonLdError( |
116 | 'Could not process context before compaction.', | |
117 | 'jsonld.CompactError', {cause: err})); | |
118 | } | |
119 | ||
120 | 86 | try { |
121 | // do compaction | |
122 | 86 | var compacted = new Processor().compact( |
123 | activeCtx, null, expanded, options); | |
124 | 86 | cleanup(null, compacted, activeCtx, options); |
125 | } | |
126 | catch(ex) { | |
127 | 0 | callback(ex); |
128 | } | |
129 | }); | |
130 | }); | |
131 | ||
132 | // performs clean up after compaction | |
133 | 86 | function cleanup(err, compacted, activeCtx, options) { |
134 | 86 | if(err) { |
135 | 0 | return callback(err); |
136 | } | |
137 | ||
138 | 86 | if(options.compactArrays && !options.graph && _isArray(compacted)) { |
139 | // simplify to a single item | |
140 | 8 | if(compacted.length === 1) { |
141 | 0 | compacted = compacted[0]; |
142 | } | |
143 | // simplify to an empty object | |
144 | 8 | else if(compacted.length === 0) { |
145 | 2 | compacted = {}; |
146 | } | |
147 | } | |
148 | // always use array if graph option is on | |
149 | 78 | else if(options.graph && _isObject(compacted)) { |
150 | 13 | compacted = [compacted]; |
151 | } | |
152 | ||
153 | // follow @context key | |
154 | 86 | if(_isObject(ctx) && '@context' in ctx) { |
155 | 59 | ctx = ctx['@context']; |
156 | } | |
157 | ||
158 | // build output context | |
159 | 86 | ctx = _clone(ctx); |
160 | 86 | if(!_isArray(ctx)) { |
161 | 85 | ctx = [ctx]; |
162 | } | |
163 | // remove empty contexts | |
164 | 86 | var tmp = ctx; |
165 | 86 | ctx = []; |
166 | 86 | for(var i in tmp) { |
167 | 87 | if(!_isObject(tmp[i]) || Object.keys(tmp[i]).length > 0) { |
168 | 79 | ctx.push(tmp[i]); |
169 | } | |
170 | } | |
171 | ||
172 | // remove array if only one context | |
173 | 86 | var hasContext = (ctx.length > 0); |
174 | 86 | if(ctx.length === 1) { |
175 | 77 | ctx = ctx[0]; |
176 | } | |
177 | ||
178 | // add context | |
179 | 86 | if(hasContext || options.graph) { |
180 | 80 | if(_isArray(compacted)) { |
181 | // use '@graph' keyword | |
182 | 26 | var kwgraph = _compactIri(activeCtx, '@graph'); |
183 | 26 | var graph = compacted; |
184 | 26 | compacted = {}; |
185 | 26 | if(hasContext) { |
186 | 24 | compacted['@context'] = ctx; |
187 | } | |
188 | 26 | compacted[kwgraph] = graph; |
189 | } | |
190 | 54 | else if(_isObject(compacted)) { |
191 | // reorder keys so @context is first | |
192 | 54 | var graph = compacted; |
193 | 54 | compacted = {'@context': ctx}; |
194 | 54 | for(var key in graph) { |
195 | 159 | compacted[key] = graph[key]; |
196 | } | |
197 | } | |
198 | } | |
199 | ||
200 | 86 | callback(null, compacted, activeCtx); |
201 | } | |
202 | }; | |
203 | ||
204 | /** | |
205 | * Performs JSON-LD expansion. | |
206 | * | |
207 | * @param input the JSON-LD input to expand. | |
208 | * @param [options] the options to use: | |
209 | * [base] the base IRI to use. | |
210 | * [keepFreeFloatingNodes] true to keep free-floating nodes, | |
211 | * false not to, defaults to false. | |
212 | * [loadContext(url, callback(err, url, result))] the context loader. | |
213 | * @param callback(err, expanded) called once the operation completes. | |
214 | */ | |
215 | 2 | jsonld.expand = function(input, options, callback) { |
216 | // get arguments | |
217 | 303 | if(typeof options === 'function') { |
218 | 0 | callback = options; |
219 | 0 | options = {}; |
220 | } | |
221 | 303 | options = options || {}; |
222 | ||
223 | // set default options | |
224 | 303 | if(!('base' in options)) { |
225 | 0 | options.base = ''; |
226 | } | |
227 | 303 | if(!('loadContext' in options)) { |
228 | 69 | options.loadContext = jsonld.loadContext; |
229 | } | |
230 | 303 | if(!('keepFreeFloatingNodes' in options)) { |
231 | 282 | options.keepFreeFloatingNodes = false; |
232 | } | |
233 | ||
234 | // retrieve all @context URLs in the input | |
235 | 303 | input = _clone(input); |
236 | 303 | _retrieveContextUrls(input, options, function(err, input) { |
237 | 303 | if(err) { |
238 | 0 | return callback(err); |
239 | } | |
240 | 303 | try { |
241 | // do expansion | |
242 | 303 | var activeCtx = _getInitialContext(options); |
243 | 303 | var expanded = new Processor().expand( |
244 | activeCtx, null, input, options, false); | |
245 | ||
246 | // optimize away @graph with no other properties | |
247 | 303 | if(_isObject(expanded) && ('@graph' in expanded) && |
248 | Object.keys(expanded).length === 1) { | |
249 | 63 | expanded = expanded['@graph']; |
250 | } | |
251 | 240 | else if(expanded === null) { |
252 | 11 | expanded = []; |
253 | } | |
254 | ||
255 | // normalize to an array | |
256 | 303 | if(!_isArray(expanded)) { |
257 | 181 | expanded = [expanded]; |
258 | } | |
259 | 303 | callback(null, expanded); |
260 | } | |
261 | catch(ex) { | |
262 | 0 | callback(ex); |
263 | } | |
264 | }); | |
265 | }; | |
266 | ||
267 | /** | |
268 | * Performs JSON-LD flattening. | |
269 | * | |
270 | * @param input the JSON-LD to flatten. | |
271 | * @param ctx the context to use to compact the flattened output, or null. | |
272 | * @param [options] the options to use: | |
273 | * [base] the base IRI to use. | |
274 | * [loadContext(url, callback(err, url, result))] the context loader. | |
275 | * @param callback(err, flattened) called once the operation completes. | |
276 | */ | |
277 | 2 | jsonld.flatten = function(input, ctx, options, callback) { |
278 | // get arguments | |
279 | 40 | if(typeof options === 'function') { |
280 | 0 | callback = options; |
281 | 0 | options = {}; |
282 | } | |
283 | 40 | options = options || {}; |
284 | ||
285 | // set default options | |
286 | 40 | if(!('base' in options)) { |
287 | 0 | options.base = ''; |
288 | } | |
289 | 40 | if(!('loadContext' in options)) { |
290 | 40 | options.loadContext = jsonld.loadContext; |
291 | } | |
292 | ||
293 | // expand input | |
294 | 40 | jsonld.expand(input, options, function(err, _input) { |
295 | 40 | if(err) { |
296 | 0 | return callback(new JsonLdError( |
297 | 'Could not expand input before flattening.', | |
298 | 'jsonld.FlattenError', {cause: err})); | |
299 | } | |
300 | ||
301 | 40 | try { |
302 | // do flattening | |
303 | 40 | var flattened = new Processor().flatten(_input); |
304 | } | |
305 | catch(ex) { | |
306 | 0 | return callback(ex); |
307 | } | |
308 | ||
309 | 40 | if(ctx === null) { |
310 | 40 | return callback(null, flattened); |
311 | } | |
312 | ||
313 | // compact result (force @graph option to true, skip expansion) | |
314 | 0 | options.graph = true; |
315 | 0 | options.skipExpansion = true; |
316 | 0 | jsonld.compact(flattened, ctx, options, function(err, compacted) { |
317 | 0 | if(err) { |
318 | 0 | return callback(new JsonLdError( |
319 | 'Could not compact flattened output.', | |
320 | 'jsonld.FlattenError', {cause: err})); | |
321 | } | |
322 | 0 | callback(null, compacted); |
323 | }); | |
324 | }); | |
325 | }; | |
326 | ||
327 | /** | |
328 | * Performs JSON-LD framing. | |
329 | * | |
330 | * @param input the JSON-LD input to frame. | |
331 | * @param frame the JSON-LD frame to use. | |
332 | * @param [options] the framing options. | |
333 | * [base] the base IRI to use. | |
334 | * [embed] default @embed flag (default: true). | |
335 | * [explicit] default @explicit flag (default: false). | |
336 | * [omitDefault] default @omitDefault flag (default: false). | |
337 | * [loadContext(url, callback(err, url, result))] the context loader. | |
338 | * @param callback(err, framed) called once the operation completes. | |
339 | */ | |
340 | 2 | jsonld.frame = function(input, frame, options, callback) { |
341 | // get arguments | |
342 | 21 | if(typeof options === 'function') { |
343 | 0 | callback = options; |
344 | 0 | options = {}; |
345 | } | |
346 | 21 | options = options || {}; |
347 | ||
348 | // set default options | |
349 | 21 | if(!('base' in options)) { |
350 | 0 | options.base = ''; |
351 | } | |
352 | 21 | if(!('loadContext' in options)) { |
353 | 21 | options.loadContext = jsonld.loadContext; |
354 | } | |
355 | 21 | if(!('embed' in options)) { |
356 | 21 | options.embed = true; |
357 | } | |
358 | 21 | options.explicit = options.explicit || false; |
359 | 21 | options.omitDefault = options.omitDefault || false; |
360 | ||
361 | // preserve frame context | |
362 | 21 | var ctx = frame['@context'] || {}; |
363 | ||
364 | // expand input | |
365 | 21 | jsonld.expand(input, options, function(err, expanded) { |
366 | 21 | if(err) { |
367 | 0 | return callback(new JsonLdError( |
368 | 'Could not expand input before framing.', | |
369 | 'jsonld.FrameError', {cause: err})); | |
370 | } | |
371 | ||
372 | // expand frame | |
373 | 21 | var opts = _clone(options); |
374 | 21 | opts.keepFreeFloatingNodes = true; |
375 | 21 | jsonld.expand(frame, opts, function(err, expandedFrame) { |
376 | 21 | if(err) { |
377 | 0 | return callback(new JsonLdError( |
378 | 'Could not expand frame before framing.', | |
379 | 'jsonld.FrameError', {cause: err})); | |
380 | } | |
381 | ||
382 | 21 | try { |
383 | // do framing | |
384 | 21 | var framed = new Processor().frame(expanded, expandedFrame, options); |
385 | } | |
386 | catch(ex) { | |
387 | 0 | return callback(ex); |
388 | } | |
389 | ||
390 | // compact result (force @graph option to true, skip expansion) | |
391 | 21 | opts.graph = true; |
392 | 21 | opts.skipExpansion = true; |
393 | 21 | jsonld.compact(framed, ctx, opts, function(err, compacted, ctx) { |
394 | 21 | if(err) { |
395 | 0 | return callback(new JsonLdError( |
396 | 'Could not compact framed output.', | |
397 | 'jsonld.FrameError', {cause: err})); | |
398 | } | |
399 | // get graph alias | |
400 | 21 | var graph = _compactIri(ctx, '@graph'); |
401 | // remove @preserve from results | |
402 | 21 | compacted[graph] = _removePreserve(ctx, compacted[graph], opts); |
403 | 21 | callback(null, compacted); |
404 | }); | |
405 | }); | |
406 | }); | |
407 | }; | |
408 | ||
409 | /** | |
410 | * Performs JSON-LD objectification. | |
411 | * | |
412 | * @param input the JSON-LD input to objectify. | |
413 | * @param ctx the JSON-LD context to apply. | |
414 | * @param [options] the framing options. | |
415 | * [base] the base IRI to use. | |
416 | * [loadContext(url, callback(err, url, result))] the context loader. | |
417 | * @param callback(err, objectified) called once the operation completes. | |
418 | */ | |
419 | 2 | jsonld.objectify = function(input, ctx, options, callback) { |
420 | // get arguments | |
421 | 0 | if(typeof options === 'function') { |
422 | 0 | callback = options; |
423 | 0 | options = {}; |
424 | } | |
425 | 0 | options = options || {}; |
426 | ||
427 | // set default options | |
428 | 0 | if(!('base' in options)) { |
429 | 0 | options.base = ''; |
430 | } | |
431 | 0 | if(!('loadContext' in options)) { |
432 | 0 | options.loadContext = jsonld.loadContext; |
433 | } | |
434 | ||
435 | // expand input | |
436 | 0 | jsonld.expand(input, options, function(err, _input) { |
437 | 0 | if(err) { |
438 | 0 | return callback(new JsonLdError( |
439 | 'Could not expand input before framing.', | |
440 | 'jsonld.FrameError', {cause: err})); | |
441 | } | |
442 | ||
443 | 0 | try { |
444 | // flatten the graph | |
445 | 0 | var flattened = new Processor().flatten(_input); |
446 | } | |
447 | catch(ex) { | |
448 | 0 | return callback(ex); |
449 | } | |
450 | ||
451 | // compact result (force @graph option to true, skip expansion) | |
452 | 0 | options.graph = true; |
453 | 0 | options.skipExpansion = true; |
454 | 0 | jsonld.compact(flattened, ctx, options, function(err, compacted, ctx) { |
455 | 0 | if(err) { |
456 | 0 | return callback(new JsonLdError( |
457 | 'Could not compact flattened output.', | |
458 | 'jsonld.FrameError', {cause: err})); | |
459 | } | |
460 | // get graph alias | |
461 | 0 | var graph = _compactIri(ctx, '@graph'); |
462 | // remove @preserve from results (named graphs?) | |
463 | 0 | compacted[graph] = _removePreserve(ctx, compacted[graph], options); |
464 | ||
465 | 0 | var top = compacted[graph][0]; |
466 | ||
467 | 0 | var recurse = function(subject) { |
468 | // can't replace just a string | |
469 | 0 | if(!_isObject(subject) && !_isArray(subject)) { |
470 | 0 | return; |
471 | } | |
472 | ||
473 | // bottom out recursion on re-visit | |
474 | 0 | if(_isObject(subject)) { |
475 | 0 | if(recurse.visited[subject['@id']]) { |
476 | 0 | return; |
477 | } | |
478 | 0 | recurse.visited[subject['@id']] = true; |
479 | } | |
480 | ||
481 | // each array element *or* object key | |
482 | 0 | for(var k in subject) { |
483 | 0 | var obj = subject[k]; |
484 | 0 | var isid = (jsonld.getContextValue(ctx, k, '@type') === '@id'); |
485 | ||
486 | // can't replace a non-object or non-array unless it's an @id | |
487 | 0 | if(!_isArray(obj) && !_isObject(obj) && !isid) { |
488 | 0 | continue; |
489 | } | |
490 | ||
491 | 0 | if(_isString(obj) && isid) { |
492 | 0 | subject[k] = obj = top[obj]; |
493 | 0 | recurse(obj); |
494 | } | |
495 | 0 | else if(_isArray(obj)) { |
496 | 0 | for(var i=0; i<obj.length; i++) { |
497 | 0 | if(_isString(obj[i]) && isid) { |
498 | 0 | obj[i] = top[obj[i]]; |
499 | } | |
500 | 0 | else if(_isObject(obj[i]) && '@id' in obj[i]) { |
501 | 0 | obj[i] = top[obj[i]['@id']]; |
502 | } | |
503 | 0 | recurse(obj[i]); |
504 | } | |
505 | } | |
506 | 0 | else if(_isObject(obj)) { |
507 | 0 | var sid = obj['@id']; |
508 | 0 | subject[k] = obj = top[sid]; |
509 | 0 | recurse(obj); |
510 | } | |
511 | } | |
512 | }; | |
513 | 0 | recurse.visited = {}; |
514 | 0 | recurse(top); |
515 | ||
516 | 0 | compacted.of_type = {}; |
517 | 0 | for(var s in top) { |
518 | 0 | if(!('@type' in top[s])) { |
519 | 0 | continue; |
520 | } | |
521 | 0 | var types = top[s]['@type']; |
522 | 0 | if(!_isArray(types)) { |
523 | 0 | types = [types]; |
524 | } | |
525 | 0 | for(var t in types) { |
526 | 0 | if(!(types[t] in compacted.of_type)) { |
527 | 0 | compacted.of_type[types[t]] = []; |
528 | } | |
529 | 0 | compacted.of_type[types[t]].push(top[s]); |
530 | } | |
531 | } | |
532 | 0 | callback(null, compacted); |
533 | }); | |
534 | }); | |
535 | }; | |
536 | ||
537 | /** | |
538 | * Performs RDF dataset normalization on the given JSON-LD input. The output | |
539 | * is an RDF dataset unless the 'format' option is used. | |
540 | * | |
541 | * @param input the JSON-LD input to normalize. | |
542 | * @param [options] the options to use: | |
543 | * [base] the base IRI to use. | |
544 | * [format] the format if output is a string: | |
545 | * 'application/nquads' for N-Quads. | |
546 | * [loadContext(url, callback(err, url, result))] the context loader. | |
547 | * @param callback(err, normalized) called once the operation completes. | |
548 | */ | |
549 | 2 | jsonld.normalize = function(input, options, callback) { |
550 | // get arguments | |
551 | 57 | if(typeof options === 'function') { |
552 | 0 | callback = options; |
553 | 0 | options = {}; |
554 | } | |
555 | 57 | options = options || {}; |
556 | ||
557 | // set default options | |
558 | 57 | if(!('base' in options)) { |
559 | 0 | options.base = ''; |
560 | } | |
561 | 57 | if(!('loadContext' in options)) { |
562 | 57 | options.loadContext = jsonld.loadContext; |
563 | } | |
564 | ||
565 | // convert to RDF dataset then do normalization | |
566 | 57 | var opts = _clone(options); |
567 | 57 | delete opts.format; |
568 | 57 | jsonld.toRDF(input, opts, function(err, dataset) { |
569 | 57 | if(err) { |
570 | 0 | return callback(new JsonLdError( |
571 | 'Could not convert input to RDF dataset before normalization.', | |
572 | 'jsonld.NormalizeError', {cause: err})); | |
573 | } | |
574 | ||
575 | // do normalization | |
576 | 57 | new Processor().normalize(dataset, options, callback); |
577 | }); | |
578 | }; | |
579 | ||
580 | /** | |
581 | * Converts an RDF dataset to JSON-LD. | |
582 | * | |
583 | * @param dataset a serialized string of RDF in a format specified by the | |
584 | * format option or an RDF dataset to convert. | |
585 | * @param [options] the options to use: | |
586 | * [format] the format if input is not an array: | |
587 | * 'application/nquads' for N-Quads (default). | |
588 | * [useRdfType] true to use rdf:type, false to use @type | |
589 | * (default: false). | |
590 | * [useNativeTypes] true to convert XSD types into native types | |
591 | * (boolean, integer, double), false not to (default: true). | |
592 | * | |
593 | * @param callback(err, output) called once the operation completes. | |
594 | */ | |
595 | 2 | jsonld.fromRDF = function(dataset, options, callback) { |
596 | // get arguments | |
597 | 7 | if(typeof options === 'function') { |
598 | 0 | callback = options; |
599 | 0 | options = {}; |
600 | } | |
601 | 7 | options = options || {}; |
602 | ||
603 | // set default options | |
604 | 7 | if(!('useRdfType' in options)) { |
605 | 7 | options.useRdfType = false; |
606 | } | |
607 | 7 | if(!('useNativeTypes' in options)) { |
608 | 7 | options.useNativeTypes = true; |
609 | } | |
610 | ||
611 | 7 | if(!('format' in options) && _isString(dataset)) { |
612 | // set default format to nquads | |
613 | 7 | if(!('format' in options)) { |
614 | 7 | options.format = 'application/nquads'; |
615 | } | |
616 | } | |
617 | ||
618 | // handle special format | |
619 | 7 | if(options.format) { |
620 | // supported formats | |
621 | 7 | if(options.format in _rdfParsers) { |
622 | 7 | dataset = _rdfParsers[options.format](dataset); |
623 | } | |
624 | else { | |
625 | 0 | throw new JsonLdError( |
626 | 'Unknown input format.', | |
627 | 'jsonld.UnknownFormat', {format: options.format}); | |
628 | } | |
629 | } | |
630 | ||
631 | // convert from RDF | |
632 | 7 | new Processor().fromRDF(dataset, options, callback); |
633 | }; | |
634 | ||
635 | /** | |
636 | * Outputs the RDF dataset found in the given JSON-LD object. | |
637 | * | |
638 | * @param input the JSON-LD input. | |
639 | * @param [options] the options to use: | |
640 | * [base] the base IRI to use. | |
641 | * [format] the format to use to output a string: | |
642 | * 'application/nquads' for N-Quads (default). | |
643 | * [loadContext(url, callback(err, url, result))] the context loader. | |
644 | * @param callback(err, dataset) called once the operation completes. | |
645 | */ | |
646 | 2 | jsonld.toRDF = function(input, options, callback) { |
647 | // get arguments | |
648 | 87 | if(typeof options === 'function') { |
649 | 0 | callback = options; |
650 | 0 | options = {}; |
651 | } | |
652 | 87 | options = options || {}; |
653 | ||
654 | // set default options | |
655 | 87 | if(!('base' in options)) { |
656 | 0 | options.base = ''; |
657 | } | |
658 | 87 | if(!('loadContext' in options)) { |
659 | 30 | options.loadContext = jsonld.loadContext; |
660 | } | |
661 | ||
662 | // expand input | |
663 | 87 | jsonld.expand(input, options, function(err, expanded) { |
664 | 87 | if(err) { |
665 | 0 | return callback(new JsonLdError( |
666 | 'Could not expand input before conversion to RDF.', | |
667 | 'jsonld.RdfError', {cause: err})); | |
668 | } | |
669 | ||
670 | // create node map for default graph (and any named graphs) | |
671 | 87 | var namer = new UniqueNamer('_:b'); |
672 | 87 | var nodeMap = {'@default': {}}; |
673 | 87 | _createNodeMap(expanded, nodeMap, '@default', namer); |
674 | ||
675 | 87 | try { |
676 | // output RDF dataset | |
677 | 87 | var dataset = Processor.prototype.toRDF(nodeMap); |
678 | 87 | if(options.format) { |
679 | 30 | if(options.format === 'application/nquads') { |
680 | 30 | return callback(null, _toNQuads(dataset)); |
681 | } | |
682 | 0 | throw new JsonLdError( |
683 | 'Unknown output format.', | |
684 | 'jsonld.UnknownFormat', {format: options.format}); | |
685 | } | |
686 | 57 | callback(null, dataset); |
687 | } | |
688 | catch(ex) { | |
689 | 0 | callback(ex); |
690 | } | |
691 | }); | |
692 | }; | |
693 | ||
694 | /** | |
695 | * Relabels all blank nodes in the given JSON-LD input. | |
696 | * | |
697 | * @param input the JSON-LD input. | |
698 | */ | |
699 | 2 | jsonld.relabelBlankNodes = function(input) { |
700 | 0 | _labelBlankNodes(new UniqueNamer('_:b', input)); |
701 | }; | |
702 | ||
703 | /** | |
704 | * The default context loader for external @context URLs. | |
705 | * | |
706 | * @param loadContext(url, callback(err, url, result)) the context loader. | |
707 | */ | |
708 | 2 | jsonld.loadContext = function(url, callback) { |
709 | 0 | return callback(new JsonLdError( |
710 | 'Could not retrieve @context URL. URL derefencing not implemented.', | |
711 | 'jsonld.ContextUrlError'), url); | |
712 | }; | |
713 | ||
714 | /* WebIDL API */ | |
715 | ||
716 | 4 | function JsonLdProcessor() {}; |
717 | // callback param order unconventional w/WebIDL API | |
718 | 2 | JsonLdProcessor.prototype.expand = function(input, callback) { |
719 | 0 | var options = {}; |
720 | 0 | if(arguments.length > 2) { |
721 | 0 | options = callback; |
722 | 0 | callback = arguments[2]; |
723 | } | |
724 | 0 | jsonld.expand(input, options, callback); |
725 | }; | |
726 | // callback param order unconventional w/WebIDL API | |
727 | 2 | JsonLdProcessor.prototype.compact = function(input, ctx, callback) { |
728 | 0 | var options = {}; |
729 | 0 | if(arguments.length > 3) { |
730 | 0 | options = callback; |
731 | 0 | callback = arguments[3]; |
732 | } | |
733 | 0 | jsonld.compact(input, ctx, options, callback); |
734 | }; | |
735 | // callback param order unconventional w/WebIDL API | |
736 | 2 | JsonLdProcessor.prototype.flatten = function(input, ctx, callback) { |
737 | 0 | var options = {}; |
738 | 0 | if(arguments.length > 3) { |
739 | 0 | options = callback; |
740 | 0 | callback = arguments[3]; |
741 | } | |
742 | 0 | jsonld.flatten(input, ctx, options, callback); |
743 | }; | |
744 | 2 | JsonLdProcessor.prototype.frame = jsonld.frame; |
745 | 2 | JsonLdProcessor.prototype.fromRDF = jsonld.fromRDF; |
746 | 2 | JsonLdProcessor.prototype.toRDF = jsonld.toRDF; |
747 | 2 | JsonLdProcessor.prototype.normalize = jsonld.normalize; |
748 | 2 | jsonld.JsonLdProcessor = JsonLdProcessor; |
749 | ||
750 | /* Utility API */ | |
751 | ||
752 | // define nextTick | |
753 | 2 | if(typeof process === 'undefined' || !process.nextTick) { |
754 | 0 | if(typeof setImmediate === 'function') { |
755 | 0 | jsonld.nextTick = function(callback) { |
756 | 0 | setImmediate(callback); |
757 | }; | |
758 | } | |
759 | else { | |
760 | 0 | jsonld.nextTick = function(callback) { |
761 | 0 | setTimeout(callback, 0); |
762 | }; | |
763 | } | |
764 | } | |
765 | else { | |
766 | 2 | jsonld.nextTick = process.nextTick; |
767 | } | |
768 | ||
769 | /** | |
770 | * Creates a simple context cache. | |
771 | * | |
772 | * @param size the maximum size of the cache. | |
773 | */ | |
774 | 2 | jsonld.ContextCache = function(size) { |
775 | 2 | this.order = []; |
776 | 2 | this.cache = {}; |
777 | 2 | this.size = size || 50; |
778 | 2 | this.expires = 30*60*1000; |
779 | }; | |
780 | 2 | jsonld.ContextCache.prototype.get = function(url) { |
781 | 0 | if(url in this.cache) { |
782 | 0 | var entry = this.cache[url]; |
783 | 0 | if(entry.expires >= +new Date()) { |
784 | 0 | return entry.ctx; |
785 | } | |
786 | 0 | delete this.cache[url]; |
787 | 0 | this.order.splice(this.order.indexOf(url), 1); |
788 | } | |
789 | 0 | return null; |
790 | }; | |
791 | 2 | jsonld.ContextCache.prototype.set = function(url, ctx) { |
792 | 0 | if(this.order.length === this.size) { |
793 | 0 | delete this.cache[this.order.shift()]; |
794 | } | |
795 | 0 | this.order.push(url); |
796 | 0 | this.cache[url] = {ctx: ctx, expires: (+new Date() + this.expires)}; |
797 | }; | |
798 | ||
799 | /** | |
800 | * Creates an active context cache. | |
801 | * | |
802 | * @param size the maximum size of the cache. | |
803 | */ | |
804 | 2 | jsonld.ActiveContextCache = function(size) { |
805 | 2 | this.order = []; |
806 | 2 | this.cache = {}; |
807 | 2 | this.size = size || 100; |
808 | }; | |
809 | 2 | jsonld.ActiveContextCache.prototype.get = function(activeCtx, localCtx) { |
810 | 326 | var key1 = JSON.stringify(activeCtx); |
811 | 326 | var key2 = JSON.stringify(localCtx); |
812 | 326 | var level1 = this.cache[key1]; |
813 | 326 | if(level1 && key2 in level1) { |
814 | 9 | return level1[key2]; |
815 | } | |
816 | 317 | return null; |
817 | }; | |
818 | 2 | jsonld.ActiveContextCache.prototype.set = function( |
819 | activeCtx, localCtx, result) { | |
820 | 317 | if(this.order.length === this.size) { |
821 | 217 | var entry = this.order.shift(); |
822 | 217 | delete this.cache[entry.activeCtx][entry.localCtx]; |
823 | } | |
824 | 317 | var key1 = JSON.stringify(activeCtx); |
825 | 317 | var key2 = JSON.stringify(localCtx); |
826 | 317 | this.order.push({activeCtx: key1, localCtx: key2}); |
827 | 317 | if(!(key1 in this.cache)) { |
828 | 269 | this.cache[key1] = {}; |
829 | } | |
830 | 317 | this.cache[key1][key2] = result; |
831 | }; | |
832 | ||
833 | /** | |
834 | * Default JSON-LD cache. | |
835 | */ | |
836 | 2 | jsonld.cache = { |
837 | activeCtx: new jsonld.ActiveContextCache() | |
838 | }; | |
839 | ||
840 | /** | |
841 | * Context loaders. | |
842 | */ | |
843 | 2 | jsonld.contextLoaders = {}; |
844 | ||
845 | /** | |
846 | * The built-in jquery context loader. | |
847 | * | |
848 | * @param $ the jquery instance to use. | |
849 | * @param options the options to use: | |
850 | * secure: require all URLs to use HTTPS. | |
851 | * | |
852 | * @return the jquery context loader. | |
853 | */ | |
854 | 2 | jsonld.contextLoaders['jquery'] = function($, options) { |
855 | 0 | options = options || {}; |
856 | 0 | var cache = new jsonld.ContextCache(); |
857 | 0 | return function(url, callback) { |
858 | 0 | if(options.secure && url.indexOf('https') !== 0) { |
859 | 0 | return callback(new JsonLdError( |
860 | 'URL could not be dereferenced; secure mode is enabled and ' + | |
861 | 'the URL\'s scheme is not "https".', | |
862 | 'jsonld.InvalidUrl', {url: url}), url); | |
863 | } | |
864 | 0 | var ctx = cache.get(url); |
865 | 0 | if(ctx !== null) { |
866 | 0 | return callback(null, url, ctx); |
867 | } | |
868 | 0 | $.ajax({ |
869 | url: url, | |
870 | dataType: 'json', | |
871 | crossDomain: true, | |
872 | success: function(data, textStatus, jqXHR) { | |
873 | 0 | cache.set(url, data); |
874 | 0 | callback(null, url, data); |
875 | }, | |
876 | error: function(jqXHR, textStatus, err) { | |
877 | 0 | callback(new JsonLdError( |
878 | 'URL could not be dereferenced, an error occurred.', | |
879 | 'jsonld.LoadContextError', {url: url, cause: err}), url); | |
880 | } | |
881 | }); | |
882 | }; | |
883 | }; | |
884 | ||
885 | /** | |
886 | * The built-in node context loader. | |
887 | * | |
888 | * @param options the options to use: | |
889 | * secure: require all URLs to use HTTPS. | |
890 | * maxRedirects: the maximum number of redirects to permit, none by | |
891 | * default. | |
892 | * | |
893 | * @return the node context loader. | |
894 | */ | |
895 | 2 | jsonld.contextLoaders['node'] = function(options) { |
896 | 2 | options = options || {}; |
897 | 2 | var maxRedirects = ('maxRedirects' in options) ? options.maxRedirects : -1; |
898 | 2 | var request = require('request'); |
899 | 2 | var http = require('http'); |
900 | 2 | var cache = new jsonld.ContextCache(); |
901 | 2 | function loadContext(url, redirects, callback) { |
902 | 0 | if(options.secure && url.indexOf('https') !== 0) { |
903 | 0 | return callback(new JsonLdError( |
904 | 'URL could not be dereferenced; secure mode is enabled and ' + | |
905 | 'the URL\'s scheme is not "https".', | |
906 | 'jsonld.InvalidUrl', {url: url}), url); | |
907 | } | |
908 | 0 | var ctx = cache.get(url); |
909 | 0 | if(ctx !== null) { |
910 | 0 | return callback(null, url, ctx); |
911 | } | |
912 | 0 | request({ |
913 | url: url, | |
914 | strictSSL: true, | |
915 | followRedirect: false | |
916 | }, function(err, res, body) { | |
917 | // handle error | |
918 | 0 | if(err) { |
919 | 0 | return callback(new JsonLdError( |
920 | 'URL could not be dereferenced, an error occurred.', | |
921 | 'jsonld.LoadContextError', {url: url, cause: err}), url); | |
922 | } | |
923 | 0 | var statusText = http.STATUS_CODES[res.statusCode]; |
924 | 0 | if(res.statusCode >= 400) { |
925 | 0 | return callback(new JsonLdError( |
926 | 'URL could not be dereferenced: ' + statusText, | |
927 | 'jsonld.InvalidUrl', {url: url, httpStatusCode: res.statusCode}), | |
928 | url); | |
929 | } | |
930 | // handle redirect | |
931 | 0 | if(res.statusCode >= 300 && res.statusCode < 400 && |
932 | res.headers.location) { | |
933 | 0 | if(redirects.length === maxRedirects) { |
934 | 0 | return callback(new JsonLdError( |
935 | 'URL could not be dereferenced; there were too many redirects.', | |
936 | 'jsonld.TooManyRedirects', | |
937 | {url: url, httpStatusCode: res.statusCode, redirects: redirects}), | |
938 | url); | |
939 | } | |
940 | 0 | if(redirects.indexOf(url) !== -1) { |
941 | 0 | return callback(new JsonLdError( |
942 | 'URL could not be dereferenced; infinite redirection was detected.', | |
943 | 'jsonld.InfiniteRedirectDetected', | |
944 | {url: url, httpStatusCode: res.statusCode, redirects: redirects}), | |
945 | url); | |
946 | } | |
947 | 0 | redirects.push(url); |
948 | 0 | return loadContext(res.headers.location, redirects, callback); |
949 | } | |
950 | // cache for each redirected URL | |
951 | 0 | redirects.push(url); |
952 | 0 | for(var i = 0; i < redirects.length; ++i) { |
953 | 0 | cache.set(redirects[i], body); |
954 | } | |
955 | 0 | callback(err, url, body); |
956 | }); | |
957 | } | |
958 | ||
959 | 2 | return function(url, callback) { |
960 | 0 | loadContext(url, [], callback); |
961 | }; | |
962 | }; | |
963 | ||
964 | /** | |
965 | * Assigns the default context loader for external @context URLs to a built-in | |
966 | * default. Supported types currently include: 'jquery' and 'node'. | |
967 | * | |
968 | * To use the jquery context loader, the 'data' parameter must be a reference | |
969 | * to the main jquery object. | |
970 | * | |
971 | * @param type the type to set. | |
972 | * @param [params] the parameters required to use the context loader. | |
973 | */ | |
974 | 2 | jsonld.useContextLoader = function(type) { |
975 | 2 | if(!(type in jsonld.contextLoaders)) { |
976 | 0 | throw new JsonLdError( |
977 | 'Unknown @context loader type: "' + type + '"', | |
978 | 'jsonld.UnknownContextLoader', | |
979 | {type: type}); | |
980 | } | |
981 | ||
982 | // set context loader | |
983 | 2 | jsonld.loadContext = jsonld.contextLoaders[type].apply( |
984 | jsonld, Array.prototype.slice.call(arguments, 1)); | |
985 | }; | |
986 | ||
987 | /** | |
988 | * Processes a local context, resolving any URLs as necessary, and returns a | |
989 | * new active context in its callback. | |
990 | * | |
991 | * @param activeCtx the current active context. | |
992 | * @param localCtx the local context to process. | |
993 | * @param [options] the options to use: | |
994 | * [loadContext(url, callback(err, url, result))] the context loader. | |
995 | * @param callback(err, ctx) called once the operation completes. | |
996 | */ | |
997 | 2 | jsonld.processContext = function(activeCtx, localCtx) { |
998 | // get arguments | |
999 | 86 | var options = {}; |
1000 | 86 | var callbackArg = 2; |
1001 | 86 | if(arguments.length > 3) { |
1002 | 86 | options = arguments[2] || {}; |
1003 | 86 | callbackArg += 1; |
1004 | } | |
1005 | 86 | var callback = arguments[callbackArg]; |
1006 | ||
1007 | // set default options | |
1008 | 86 | if(!('base' in options)) { |
1009 | 0 | options.base = ''; |
1010 | } | |
1011 | 86 | if(!('loadContext' in options)) { |
1012 | 0 | options.loadContext = jsonld.loadContext; |
1013 | } | |
1014 | ||
1015 | // return initial context early for null context | |
1016 | 86 | if(localCtx === null) { |
1017 | 0 | return callback(null, _getInitialContext(options)); |
1018 | } | |
1019 | ||
1020 | // retrieve URLs in localCtx | |
1021 | 86 | localCtx = _clone(localCtx); |
1022 | 86 | if(_isString(localCtx) || |
1023 | (_isObject(localCtx) && !('@context' in localCtx))) { | |
1024 | 27 | localCtx = {'@context': localCtx}; |
1025 | } | |
1026 | 86 | _retrieveContextUrls(localCtx, options, function(err, ctx) { |
1027 | 86 | if(err) { |
1028 | 0 | return callback(err); |
1029 | } | |
1030 | 86 | try { |
1031 | // process context | |
1032 | 86 | ctx = new Processor().processContext(activeCtx, ctx, options); |
1033 | 86 | callback(null, ctx); |
1034 | } | |
1035 | catch(ex) { | |
1036 | 0 | callback(ex); |
1037 | } | |
1038 | }); | |
1039 | }; | |
1040 | ||
1041 | /** | |
1042 | * Returns true if the given subject has the given property. | |
1043 | * | |
1044 | * @param subject the subject to check. | |
1045 | * @param property the property to look for. | |
1046 | * | |
1047 | * @return true if the subject has the given property, false if not. | |
1048 | */ | |
1049 | 2 | jsonld.hasProperty = function(subject, property) { |
1050 | 410 | var rval = false; |
1051 | 410 | if(property in subject) { |
1052 | 292 | var value = subject[property]; |
1053 | 292 | rval = (!_isArray(value) || value.length > 0); |
1054 | } | |
1055 | 410 | return rval; |
1056 | }; | |
1057 | ||
1058 | /** | |
1059 | * Determines if the given value is a property of the given subject. | |
1060 | * | |
1061 | * @param subject the subject to check. | |
1062 | * @param property the property to check. | |
1063 | * @param value the value to check. | |
1064 | * | |
1065 | * @return true if the value exists, false if not. | |
1066 | */ | |
1067 | 2 | jsonld.hasValue = function(subject, property, value) { |
1068 | 410 | var rval = false; |
1069 | 410 | if(jsonld.hasProperty(subject, property)) { |
1070 | 292 | var val = subject[property]; |
1071 | 292 | var isList = _isList(val); |
1072 | 292 | if(_isArray(val) || isList) { |
1073 | 292 | if(isList) { |
1074 | 0 | val = val['@list']; |
1075 | } | |
1076 | 292 | for(var i in val) { |
1077 | 631 | if(jsonld.compareValues(value, val[i])) { |
1078 | 41 | rval = true; |
1079 | 41 | break; |
1080 | } | |
1081 | } | |
1082 | } | |
1083 | // avoid matching the set of values with an array value parameter | |
1084 | 0 | else if(!_isArray(value)) { |
1085 | 0 | rval = jsonld.compareValues(value, val); |
1086 | } | |
1087 | } | |
1088 | 410 | return rval; |
1089 | }; | |
1090 | ||
1091 | /** | |
1092 | * Adds a value to a subject. If the value is an array, all values in the | |
1093 | * array will be added. | |
1094 | * | |
1095 | * @param subject the subject to add the value to. | |
1096 | * @param property the property that relates the value to the subject. | |
1097 | * @param value the value to add. | |
1098 | * @param [options] the options to use: | |
1099 | * [propertyIsArray] true if the property is always an array, false | |
1100 | * if not (default: false). | |
1101 | * [allowDuplicate] true to allow duplicates, false not to (uses a | |
1102 | * simple shallow comparison of subject ID or value) (default: true). | |
1103 | */ | |
1104 | 2 | jsonld.addValue = function(subject, property, value, options) { |
1105 | 4992 | options = options || {}; |
1106 | 4992 | if(!('propertyIsArray' in options)) { |
1107 | 46 | options.propertyIsArray = false; |
1108 | } | |
1109 | 4992 | if(!('allowDuplicate' in options)) { |
1110 | 3077 | options.allowDuplicate = true; |
1111 | } | |
1112 | ||
1113 | 4992 | if(_isArray(value)) { |
1114 | 553 | if(value.length === 0 && options.propertyIsArray && |
1115 | !(property in subject)) { | |
1116 | 87 | subject[property] = []; |
1117 | } | |
1118 | 553 | for(var i in value) { |
1119 | 1148 | jsonld.addValue(subject, property, value[i], options); |
1120 | } | |
1121 | } | |
1122 | 4439 | else if(property in subject) { |
1123 | // check if subject already has value if duplicates not allowed | |
1124 | 992 | var hasValue = (!options.allowDuplicate && |
1125 | jsonld.hasValue(subject, property, value)); | |
1126 | ||
1127 | // make property an array if value not present or always an array | |
1128 | 992 | if(!_isArray(subject[property]) && |
1129 | (!hasValue || options.propertyIsArray)) { | |
1130 | 45 | subject[property] = [subject[property]]; |
1131 | } | |
1132 | ||
1133 | // add new value | |
1134 | 992 | if(!hasValue) { |
1135 | 984 | subject[property].push(value); |
1136 | } | |
1137 | } | |
1138 | else { | |
1139 | // add new value as set or single value | |
1140 | 3447 | subject[property] = options.propertyIsArray ? [value] : value; |
1141 | } | |
1142 | }; | |
1143 | ||
1144 | /** | |
1145 | * Gets all of the values for a subject's property as an array. | |
1146 | * | |
1147 | * @param subject the subject. | |
1148 | * @param property the property. | |
1149 | * | |
1150 | * @return all of the values for a subject's property as an array. | |
1151 | */ | |
1152 | 2 | jsonld.getValues = function(subject, property) { |
1153 | 0 | var rval = subject[property] || []; |
1154 | 0 | if(!_isArray(rval)) { |
1155 | 0 | rval = [rval]; |
1156 | } | |
1157 | 0 | return rval; |
1158 | }; | |
1159 | ||
1160 | /** | |
1161 | * Removes a property from a subject. | |
1162 | * | |
1163 | * @param subject the subject. | |
1164 | * @param property the property. | |
1165 | */ | |
1166 | 2 | jsonld.removeProperty = function(subject, property) { |
1167 | 0 | delete subject[property]; |
1168 | }; | |
1169 | ||
1170 | /** | |
1171 | * Removes a value from a subject. | |
1172 | * | |
1173 | * @param subject the subject. | |
1174 | * @param property the property that relates the value to the subject. | |
1175 | * @param value the value to remove. | |
1176 | * @param [options] the options to use: | |
1177 | * [propertyIsArray] true if the property is always an array, false | |
1178 | * if not (default: false). | |
1179 | */ | |
1180 | 2 | jsonld.removeValue = function(subject, property, value, options) { |
1181 | 0 | options = options || {}; |
1182 | 0 | if(!('propertyIsArray' in options)) { |
1183 | 0 | options.propertyIsArray = false; |
1184 | } | |
1185 | ||
1186 | // filter out value | |
1187 | 0 | var values = jsonld.getValues(subject, property).filter(function(e) { |
1188 | 0 | return !jsonld.compareValues(e, value); |
1189 | }); | |
1190 | ||
1191 | 0 | if(values.length === 0) { |
1192 | 0 | jsonld.removeProperty(subject, property); |
1193 | } | |
1194 | 0 | else if(values.length === 1 && !options.propertyIsArray) { |
1195 | 0 | subject[property] = values[0]; |
1196 | } | |
1197 | else { | |
1198 | 0 | subject[property] = values; |
1199 | } | |
1200 | }; | |
1201 | ||
1202 | /** | |
1203 | * Compares two JSON-LD values for equality. Two JSON-LD values will be | |
1204 | * considered equal if: | |
1205 | * | |
1206 | * 1. They are both primitives of the same type and value. | |
1207 | * 2. They are both @values with the same @value, @type, @language, | |
1208 | * and @index, OR | |
1209 | * 3. They both have @ids they are the same. | |
1210 | * | |
1211 | * @param v1 the first value. | |
1212 | * @param v2 the second value. | |
1213 | * | |
1214 | * @return true if v1 and v2 are considered equal, false if not. | |
1215 | */ | |
1216 | 2 | jsonld.compareValues = function(v1, v2) { |
1217 | // 1. equal primitives | |
1218 | 631 | if(v1 === v2) { |
1219 | 35 | return true; |
1220 | } | |
1221 | ||
1222 | // 2. equal @values | |
1223 | 596 | if(_isValue(v1) && _isValue(v2) && |
1224 | v1['@value'] === v2['@value'] && | |
1225 | v1['@type'] === v2['@type'] && | |
1226 | v1['@language'] === v2['@language'] && | |
1227 | v1['@index'] === v2['@index']) { | |
1228 | 2 | return true; |
1229 | } | |
1230 | ||
1231 | // 3. equal @ids | |
1232 | 594 | if(_isObject(v1) && ('@id' in v1) && _isObject(v2) && ('@id' in v2)) { |
1233 | 152 | return v1['@id'] === v2['@id']; |
1234 | } | |
1235 | ||
1236 | 442 | return false; |
1237 | }; | |
1238 | ||
1239 | /** | |
1240 | * Gets the value for the given active context key and type, null if none is | |
1241 | * set. | |
1242 | * | |
1243 | * @param ctx the active context. | |
1244 | * @param key the context key. | |
1245 | * @param [type] the type of value to get (eg: '@id', '@type'), if not | |
1246 | * specified gets the entire entry for a key, null if not found. | |
1247 | * | |
1248 | * @return the value. | |
1249 | */ | |
1250 | 2 | jsonld.getContextValue = function(ctx, key, type) { |
1251 | 5451 | var rval = null; |
1252 | ||
1253 | // return null for invalid key | |
1254 | 5451 | if(key === null) { |
1255 | 79 | return rval; |
1256 | } | |
1257 | ||
1258 | // get default language | |
1259 | 5372 | if(type === '@language' && (type in ctx)) { |
1260 | 73 | rval = ctx[type]; |
1261 | } | |
1262 | ||
1263 | // get specific entry information | |
1264 | 5372 | if(ctx.mappings[key]) { |
1265 | 2184 | var entry = ctx.mappings[key]; |
1266 | ||
1267 | // return whole entry | |
1268 | 2184 | if(_isUndefined(type)) { |
1269 | 0 | rval = entry; |
1270 | } | |
1271 | // return entry value for type | |
1272 | 2184 | else if(type in entry) { |
1273 | 755 | rval = entry[type]; |
1274 | } | |
1275 | } | |
1276 | ||
1277 | 5372 | return rval; |
1278 | }; | |
1279 | ||
1280 | /** Registered RDF dataset parsers hashed by content-type. */ | |
1281 | 2 | var _rdfParsers = {}; |
1282 | ||
1283 | /** | |
1284 | * Registers an RDF dataset parser by content-type, for use with | |
1285 | * jsonld.fromRDF. | |
1286 | * | |
1287 | * @param contentType the content-type for the parser. | |
1288 | * @param parser(input) the parser function (takes a string as a parameter | |
1289 | * and returns an RDF dataset). | |
1290 | */ | |
1291 | 2 | jsonld.registerRDFParser = function(contentType, parser) { |
1292 | 4 | _rdfParsers[contentType] = parser; |
1293 | }; | |
1294 | ||
1295 | /** | |
1296 | * Unregisters an RDF dataset parser by content-type. | |
1297 | * | |
1298 | * @param contentType the content-type for the parser. | |
1299 | */ | |
1300 | 2 | jsonld.unregisterRDFParser = function(contentType) { |
1301 | 0 | delete _rdfParsers[contentType]; |
1302 | }; | |
1303 | ||
1304 | 2 | if(_nodejs) { |
1305 | // needed for serialization of XML literals | |
1306 | 2 | if(typeof XMLSerializer === 'undefined') { |
1307 | 2 | var XMLSerializer = null; |
1308 | } | |
1309 | 2 | if(typeof Node === 'undefined') { |
1310 | 2 | var Node = { |
1311 | ELEMENT_NODE: 1, | |
1312 | ATTRIBUTE_NODE: 2, | |
1313 | TEXT_NODE: 3, | |
1314 | CDATA_SECTION_NODE: 4, | |
1315 | ENTITY_REFERENCE_NODE: 5, | |
1316 | ENTITY_NODE: 6, | |
1317 | PROCESSING_INSTRUCTION_NODE: 7, | |
1318 | COMMENT_NODE: 8, | |
1319 | DOCUMENT_NODE: 9, | |
1320 | DOCUMENT_TYPE_NODE: 10, | |
1321 | DOCUMENT_FRAGMENT_NODE: 11, | |
1322 | NOTATION_NODE:12 | |
1323 | }; | |
1324 | } | |
1325 | } | |
1326 | ||
1327 | // constants | |
1328 | 2 | var XSD_BOOLEAN = 'http://www.w3.org/2001/XMLSchema#boolean'; |
1329 | 2 | var XSD_DOUBLE = 'http://www.w3.org/2001/XMLSchema#double'; |
1330 | 2 | var XSD_INTEGER = 'http://www.w3.org/2001/XMLSchema#integer'; |
1331 | 2 | var XSD_STRING = 'http://www.w3.org/2001/XMLSchema#string'; |
1332 | ||
1333 | 2 | var RDF = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#'; |
1334 | 2 | var RDF_FIRST = RDF + 'first'; |
1335 | 2 | var RDF_REST = RDF + 'rest'; |
1336 | 2 | var RDF_NIL = RDF + 'nil'; |
1337 | 2 | var RDF_TYPE = RDF + 'type'; |
1338 | 2 | var RDF_PLAIN_LITERAL = RDF + 'PlainLiteral'; |
1339 | 2 | var RDF_XML_LITERAL = RDF + 'XMLLiteral'; |
1340 | 2 | var RDF_OBJECT = RDF + 'object'; |
1341 | 2 | var RDF_LANGSTRING = RDF + 'langString'; |
1342 | ||
1343 | 2 | var MAX_CONTEXT_URLS = 10; |
1344 | ||
1345 | /** | |
1346 | * A JSON-LD Error. | |
1347 | * | |
1348 | * @param msg the error message. | |
1349 | * @param type the error type. | |
1350 | * @param details the error details. | |
1351 | */ | |
1352 | 2 | var JsonLdError = function(msg, type, details) { |
1353 | 0 | if(_nodejs) { |
1354 | 0 | Error.call(this); |
1355 | 0 | Error.captureStackTrace(this, this.constructor); |
1356 | } | |
1357 | 0 | this.name = type || 'jsonld.Error'; |
1358 | 0 | this.message = msg || 'An unspecified JSON-LD error occurred.'; |
1359 | 0 | this.details = details || {}; |
1360 | }; | |
1361 | 2 | if(_nodejs) { |
1362 | 2 | require('util').inherits(JsonLdError, Error); |
1363 | } | |
1364 | ||
1365 | /** | |
1366 | * Constructs a new JSON-LD Processor. | |
1367 | */ | |
1368 | 2 | var Processor = function() {}; |
1369 | ||
1370 | /** | |
1371 | * Recursively compacts an element using the given active context. All values | |
1372 | * must be in expanded form before this method is called. | |
1373 | * | |
1374 | * @param activeCtx the active context to use. | |
1375 | * @param activeProperty the compacted property associated with the element | |
1376 | * to compact, null for none. | |
1377 | * @param element the element to compact. | |
1378 | * @param options the compaction options. | |
1379 | * | |
1380 | * @return the compacted value. | |
1381 | */ | |
1382 | 2 | Processor.prototype.compact = function( |
1383 | activeCtx, activeProperty, element, options) { | |
1384 | // recursively compact array | |
1385 | 677 | if(_isArray(element)) { |
1386 | 115 | var rval = []; |
1387 | 115 | for(var i in element) { |
1388 | // compact, dropping any null values | |
1389 | 204 | var compacted = this.compact( |
1390 | activeCtx, activeProperty, element[i], options); | |
1391 | 204 | if(compacted !== null) { |
1392 | 204 | rval.push(compacted); |
1393 | } | |
1394 | } | |
1395 | 115 | if(options.compactArrays && rval.length === 1) { |
1396 | // use single element if no container is specified | |
1397 | 76 | var container = jsonld.getContextValue( |
1398 | activeCtx, activeProperty, '@container'); | |
1399 | 76 | if(container === null) { |
1400 | 76 | rval = rval[0]; |
1401 | } | |
1402 | } | |
1403 | 115 | return rval; |
1404 | } | |
1405 | ||
1406 | // recursively compact object | |
1407 | 562 | if(_isObject(element)) { |
1408 | // do value compaction on @values and subject references | |
1409 | 555 | if(_isValue(element) || _isSubjectReference(element)) { |
1410 | 361 | return _compactValue(activeCtx, activeProperty, element); |
1411 | } | |
1412 | ||
1413 | // FIXME: avoid misuse of active property as an expanded property? | |
1414 | 194 | var insideReverse = (activeProperty === '@reverse'); |
1415 | ||
1416 | // process element keys in order | |
1417 | 194 | var keys = Object.keys(element).sort(); |
1418 | 194 | var rval = {}; |
1419 | 194 | for(var ki = 0; ki < keys.length; ++ki) { |
1420 | 549 | var expandedProperty = keys[ki]; |
1421 | 549 | var expandedValue = element[expandedProperty]; |
1422 | ||
1423 | // compact @id and @type(s) | |
1424 | 549 | if(expandedProperty === '@id' || expandedProperty === '@type') { |
1425 | 231 | var compactedValue; |
1426 | ||
1427 | // compact single @id | |
1428 | 231 | if(_isString(expandedValue)) { |
1429 | 158 | compactedValue = _compactIri( |
1430 | activeCtx, expandedValue, null, | |
1431 | {vocab: (expandedProperty === '@type')}); | |
1432 | } | |
1433 | // expanded value must be a @type array | |
1434 | else { | |
1435 | 73 | compactedValue = []; |
1436 | 73 | for(var vi = 0; vi < expandedValue.length; ++vi) { |
1437 | 87 | compactedValue.push(_compactIri( |
1438 | activeCtx, expandedValue[vi], null, {vocab: true})); | |
1439 | } | |
1440 | } | |
1441 | ||
1442 | // use keyword alias and add value | |
1443 | 231 | var alias = _compactIri(activeCtx, expandedProperty); |
1444 | 231 | var isArray = (_isArray(compactedValue) && expandedValue.length === 0); |
1445 | 231 | jsonld.addValue( |
1446 | rval, alias, compactedValue, {propertyIsArray: isArray}); | |
1447 | 231 | continue; |
1448 | } | |
1449 | ||
1450 | // handle @reverse | |
1451 | 318 | if(expandedProperty === '@reverse') { |
1452 | // recursively compact expanded value | |
1453 | 8 | var compactedValue = this.compact( |
1454 | activeCtx, '@reverse', expandedValue, options); | |
1455 | ||
1456 | // handle double-reversed properties | |
1457 | 8 | for(var compactedProperty in compactedValue) { |
1458 | 10 | if(activeCtx.mappings[compactedProperty] && |
1459 | activeCtx.mappings[compactedProperty].reverse) { | |
1460 | 4 | if(!(compactedProperty in rval) && !options.compactArrays) { |
1461 | 0 | rval[compactedProperty] = []; |
1462 | } | |
1463 | 4 | jsonld.addValue( |
1464 | rval, compactedProperty, compactedValue[compactedProperty]); | |
1465 | 4 | delete compactedValue[compactedProperty]; |
1466 | } | |
1467 | } | |
1468 | ||
1469 | 8 | if(Object.keys(compactedValue).length > 0) { |
1470 | // use keyword alias and add value | |
1471 | 4 | var alias = _compactIri(activeCtx, expandedProperty); |
1472 | 4 | jsonld.addValue(rval, alias, compactedValue); |
1473 | } | |
1474 | ||
1475 | 8 | continue; |
1476 | } | |
1477 | ||
1478 | // handle @index property | |
1479 | 310 | if(expandedProperty === '@index') { |
1480 | // drop @index if inside an @index container | |
1481 | 15 | var container = jsonld.getContextValue( |
1482 | activeCtx, activeProperty, '@container'); | |
1483 | 15 | if(container === '@index') { |
1484 | 14 | continue; |
1485 | } | |
1486 | ||
1487 | // use keyword alias and add value | |
1488 | 1 | var alias = _compactIri(activeCtx, expandedProperty); |
1489 | 1 | jsonld.addValue(rval, alias, expandedValue); |
1490 | 1 | continue; |
1491 | } | |
1492 | ||
1493 | // Note: expanded value must be an array due to expansion algorithm. | |
1494 | ||
1495 | // preserve empty arrays | |
1496 | 295 | if(expandedValue.length === 0) { |
1497 | 5 | var itemActiveProperty = _compactIri( |
1498 | activeCtx, expandedProperty, expandedValue, {vocab: true}, | |
1499 | insideReverse); | |
1500 | 5 | jsonld.addValue( |
1501 | rval, itemActiveProperty, expandedValue, {propertyIsArray: true}); | |
1502 | } | |
1503 | ||
1504 | // recusively process array values | |
1505 | 295 | for(var vi = 0; vi < expandedValue.length; ++vi) { |
1506 | 379 | var expandedItem = expandedValue[vi]; |
1507 | ||
1508 | // compact property and get container type | |
1509 | 379 | var itemActiveProperty = _compactIri( |
1510 | activeCtx, expandedProperty, expandedItem, {vocab: true}, | |
1511 | insideReverse); | |
1512 | 379 | var container = jsonld.getContextValue( |
1513 | activeCtx, itemActiveProperty, '@container'); | |
1514 | ||
1515 | // get @list value if appropriate | |
1516 | 379 | var isList = _isList(expandedItem); |
1517 | 379 | var list = null; |
1518 | 379 | if(isList) { |
1519 | 29 | list = expandedItem['@list']; |
1520 | } | |
1521 | ||
1522 | // recursively compact expanded item | |
1523 | 379 | var compactedItem = this.compact( |
1524 | activeCtx, itemActiveProperty, isList ? list : expandedItem, options); | |
1525 | ||
1526 | // handle @list | |
1527 | 379 | if(isList) { |
1528 | // ensure @list value is an array | |
1529 | 29 | if(!_isArray(compactedItem)) { |
1530 | 6 | compactedItem = [compactedItem]; |
1531 | } | |
1532 | ||
1533 | 29 | if(container !== '@list') { |
1534 | // wrap using @list alias | |
1535 | 9 | var wrapper = {}; |
1536 | 9 | wrapper[_compactIri(activeCtx, '@list')] = compactedItem; |
1537 | 9 | compactedItem = wrapper; |
1538 | ||
1539 | // include @index from expanded @list, if any | |
1540 | 9 | if('@index' in expandedItem) { |
1541 | 2 | compactedItem[_compactIri(activeCtx, '@index')] = |
1542 | expandedItem['@index']; | |
1543 | } | |
1544 | } | |
1545 | // can't use @list container for more than 1 list | |
1546 | 20 | else if(itemActiveProperty in rval) { |
1547 | 0 | throw new JsonLdError( |
1548 | 'JSON-LD compact error; property has a "@list" @container ' + | |
1549 | 'rule but there is more than a single @list that matches ' + | |
1550 | 'the compacted term in the document. Compaction might mix ' + | |
1551 | 'unwanted items into the list.', | |
1552 | 'jsonld.SyntaxError'); | |
1553 | } | |
1554 | } | |
1555 | ||
1556 | // handle language and index maps | |
1557 | 379 | if(container === '@language' || container === '@index') { |
1558 | // get or create the map object | |
1559 | 37 | var mapObject; |
1560 | 37 | if(itemActiveProperty in rval) { |
1561 | 28 | mapObject = rval[itemActiveProperty]; |
1562 | } | |
1563 | else { | |
1564 | 9 | rval[itemActiveProperty] = mapObject = {}; |
1565 | } | |
1566 | ||
1567 | // if container is a language map, simplify compacted value to | |
1568 | // a simple string | |
1569 | 37 | if(container === '@language' && _isValue(compactedItem)) { |
1570 | 7 | compactedItem = compactedItem['@value']; |
1571 | } | |
1572 | ||
1573 | // add compact value to map object using key from expanded value | |
1574 | // based on the container type | |
1575 | 37 | jsonld.addValue(mapObject, expandedItem[container], compactedItem); |
1576 | } | |
1577 | else { | |
1578 | // use an array if: compactArrays flag is false, | |
1579 | // @container is @set or @list , value is an empty | |
1580 | // array, or key is @graph | |
1581 | 342 | var isArray = (!options.compactArrays || container === '@set' || |
1582 | container === '@list' || | |
1583 | (_isArray(compactedItem) && compactedItem.length === 0) || | |
1584 | expandedProperty === '@list' || expandedProperty === '@graph'); | |
1585 | ||
1586 | // add compact value | |
1587 | 342 | jsonld.addValue( |
1588 | rval, itemActiveProperty, compactedItem, | |
1589 | {propertyIsArray: isArray}); | |
1590 | } | |
1591 | } | |
1592 | } | |
1593 | ||
1594 | 194 | return rval; |
1595 | } | |
1596 | ||
1597 | // only primitives remain which are already compact | |
1598 | 7 | return element; |
1599 | }; | |
1600 | ||
1601 | /** | |
1602 | * Recursively expands an element using the given context. Any context in | |
1603 | * the element will be removed. All context URLs must have been retrieved | |
1604 | * before calling this method. | |
1605 | * | |
1606 | * @param activeCtx the context to use. | |
1607 | * @param activeProperty the property for the element, null for none. | |
1608 | * @param element the element to expand. | |
1609 | * @param options the expansion options. | |
1610 | * @param insideList true if the element is a list, false if not. | |
1611 | * | |
1612 | * @return the expanded value. | |
1613 | */ | |
1614 | 2 | Processor.prototype.expand = function( |
1615 | activeCtx, activeProperty, element, options, insideList) { | |
1616 | 3705 | var self = this; |
1617 | ||
1618 | 3705 | if(typeof element === 'undefined') { |
1619 | 0 | throw new JsonLdError( |
1620 | 'Invalid JSON-LD syntax; undefined element.', | |
1621 | 'jsonld.SyntaxError'); | |
1622 | } | |
1623 | ||
1624 | // nothing to expand | |
1625 | 3705 | if(element === null) { |
1626 | 36 | return null; |
1627 | } | |
1628 | ||
1629 | // recursively expand array | |
1630 | 3669 | if(_isArray(element)) { |
1631 | 494 | var rval = []; |
1632 | 494 | for(var i in element) { |
1633 | // expand element | |
1634 | 1160 | var e = self.expand( |
1635 | activeCtx, activeProperty, element[i], options, insideList); | |
1636 | 1160 | if(insideList && (_isArray(e) || _isList(e))) { |
1637 | // lists of lists are illegal | |
1638 | 0 | throw new JsonLdError( |
1639 | 'Invalid JSON-LD syntax; lists of lists are not permitted.', | |
1640 | 'jsonld.SyntaxError'); | |
1641 | } | |
1642 | // drop null values | |
1643 | 1160 | else if(e !== null) { |
1644 | 1103 | if(_isArray(e)) { |
1645 | 27 | rval = rval.concat(e); |
1646 | } | |
1647 | else { | |
1648 | 1076 | rval.push(e); |
1649 | } | |
1650 | } | |
1651 | } | |
1652 | 494 | return rval; |
1653 | } | |
1654 | ||
1655 | // recursively expand object | |
1656 | 3175 | if(_isObject(element)) { |
1657 | // if element has a context, process it | |
1658 | 1109 | if('@context' in element) { |
1659 | 240 | activeCtx = self.processContext(activeCtx, element['@context'], options); |
1660 | } | |
1661 | ||
1662 | // expand the active property | |
1663 | 1109 | var expandedActiveProperty = _expandIri( |
1664 | activeCtx, activeProperty, {vocab: true}); | |
1665 | ||
1666 | 1109 | var rval = {}; |
1667 | 1109 | var keys = Object.keys(element).sort(); |
1668 | 1109 | for(var ki = 0; ki < keys.length; ++ki) { |
1669 | 2509 | var key = keys[ki]; |
1670 | 2509 | var value = element[key]; |
1671 | 2509 | var expandedValue; |
1672 | ||
1673 | // skip @context | |
1674 | 2509 | if(key === '@context') { |
1675 | 240 | continue; |
1676 | } | |
1677 | ||
1678 | // expand key to IRI | |
1679 | 2269 | var expandedProperty = _expandIri(activeCtx, key, {vocab: true}); |
1680 | ||
1681 | // drop non-absolute IRI keys that aren't keywords | |
1682 | 2269 | if(expandedProperty === null || |
1683 | !(_isAbsoluteIri(expandedProperty) || _isKeyword(expandedProperty))) { | |
1684 | 30 | continue; |
1685 | } | |
1686 | ||
1687 | 2239 | if(_isKeyword(expandedProperty) && |
1688 | expandedActiveProperty === '@reverse') { | |
1689 | 0 | throw new JsonLdError( |
1690 | 'Invalid JSON-LD syntax; a keyword cannot be used as a @reverse ' + | |
1691 | 'property.', | |
1692 | 'jsonld.SyntaxError', {value: value}); | |
1693 | } | |
1694 | ||
1695 | // syntax error if @id is not a string | |
1696 | 2239 | if(expandedProperty === '@id' && !_isString(value)) { |
1697 | 0 | throw new JsonLdError( |
1698 | 'Invalid JSON-LD syntax; "@id" value must a string.', | |
1699 | 'jsonld.SyntaxError', {value: value}); | |
1700 | } | |
1701 | ||
1702 | // validate @type value | |
1703 | 2239 | if(expandedProperty === '@type') { |
1704 | 206 | _validateTypeValue(value); |
1705 | } | |
1706 | ||
1707 | // @graph must be an array or an object | |
1708 | 2239 | if(expandedProperty === '@graph' && |
1709 | !(_isObject(value) || _isArray(value))) { | |
1710 | 0 | throw new JsonLdError( |
1711 | 'Invalid JSON-LD syntax; "@value" value must not be an ' + | |
1712 | 'object or an array.', | |
1713 | 'jsonld.SyntaxError', {value: value}); | |
1714 | } | |
1715 | ||
1716 | // @value must not be an object or an array | |
1717 | 2239 | if(expandedProperty === '@value' && |
1718 | (_isObject(value) || _isArray(value))) { | |
1719 | 0 | throw new JsonLdError( |
1720 | 'Invalid JSON-LD syntax; "@value" value must not be an ' + | |
1721 | 'object or an array.', | |
1722 | 'jsonld.SyntaxError', {value: value}); | |
1723 | } | |
1724 | ||
1725 | // @language must be a string | |
1726 | 2239 | if(expandedProperty === '@language') { |
1727 | 60 | if(!_isString(value)) { |
1728 | 0 | throw new JsonLdError( |
1729 | 'Invalid JSON-LD syntax; "@language" value must be a string.', | |
1730 | 'jsonld.SyntaxError', {value: value}); | |
1731 | } | |
1732 | // ensure language value is lowercase | |
1733 | 60 | value = value.toLowerCase(); |
1734 | } | |
1735 | ||
1736 | // @index must be a string | |
1737 | 2239 | if(expandedProperty === '@index') { |
1738 | 52 | if(!_isString(value)) { |
1739 | 0 | throw new JsonLdError( |
1740 | 'Invalid JSON-LD syntax; "@index" value must be a string.', | |
1741 | 'jsonld.SyntaxError', {value: value}); | |
1742 | } | |
1743 | } | |
1744 | ||
1745 | // @reverse must be an object | |
1746 | 2239 | if(expandedProperty === '@reverse') { |
1747 | 15 | if(!_isObject(value)) { |
1748 | 0 | throw new JsonLdError( |
1749 | 'Invalid JSON-LD syntax; "@reverse" value must be an object.', | |
1750 | 'jsonld.SyntaxError', {value: value}); | |
1751 | } | |
1752 | ||
1753 | 15 | expandedValue = self.expand( |
1754 | activeCtx, '@reverse', value, options, insideList); | |
1755 | ||
1756 | // properties double-reversed | |
1757 | 15 | if('@reverse' in expandedValue) { |
1758 | 1 | for(var property in expandedValue['@reverse']) { |
1759 | 1 | jsonld.addValue( |
1760 | rval, property, expandedValue['@reverse'][property], | |
1761 | {propertyIsArray: true}); | |
1762 | } | |
1763 | } | |
1764 | ||
1765 | // FIXME: can this be merged with code below to simplify? | |
1766 | // merge in all reversed properties | |
1767 | 15 | var reverseMap = rval['@reverse'] || null; |
1768 | 15 | for(var property in expandedValue) { |
1769 | 17 | if(property === '@reverse') { |
1770 | 1 | continue; |
1771 | } | |
1772 | 16 | if(reverseMap === null) { |
1773 | 14 | reverseMap = rval['@reverse'] = {}; |
1774 | } | |
1775 | 16 | jsonld.addValue(reverseMap, property, [], {propertyIsArray: true}); |
1776 | 16 | var items = expandedValue[property]; |
1777 | 16 | for(var ii = 0; ii < items.length; ++ii) { |
1778 | 22 | var item = items[ii]; |
1779 | 22 | if(_isValue(item) || _isList(item)) { |
1780 | 0 | throw new JsonLdError( |
1781 | 'Invalid JSON-LD syntax; "@reverse" value must not be a ' + | |
1782 | '@value or an @list.', | |
1783 | 'jsonld.SyntaxError', {value: expandedValue}); | |
1784 | } | |
1785 | 22 | jsonld.addValue( |
1786 | reverseMap, property, item, {propertyIsArray: true}); | |
1787 | } | |
1788 | } | |
1789 | ||
1790 | 15 | continue; |
1791 | } | |
1792 | ||
1793 | 2224 | var container = jsonld.getContextValue(activeCtx, key, '@container'); |
1794 | ||
1795 | // handle language map container (skip if value is not an object) | |
1796 | 2224 | if(container === '@language' && _isObject(value)) { |
1797 | 4 | expandedValue = _expandLanguageMap(value); |
1798 | } | |
1799 | // handle index container (skip if value is not an object) | |
1800 | 2220 | else if(container === '@index' && _isObject(value)) { |
1801 | 7 | expandedValue = (function _expandIndexMap(activeProperty) { |
1802 | 7 | var rval = []; |
1803 | 7 | var keys = Object.keys(value).sort(); |
1804 | 7 | for(var ki = 0; ki < keys.length; ++ki) { |
1805 | 14 | var key = keys[ki]; |
1806 | 14 | var val = value[key]; |
1807 | 14 | if(!_isArray(val)) { |
1808 | 5 | val = [val]; |
1809 | } | |
1810 | 14 | val = self.expand(activeCtx, activeProperty, val, options, false); |
1811 | 14 | for(var vi = 0; vi < val.length; ++vi) { |
1812 | 43 | var item = val[vi]; |
1813 | 43 | if(!('@index' in item)) { |
1814 | 39 | item['@index'] = key; |
1815 | } | |
1816 | 43 | rval.push(item); |
1817 | } | |
1818 | } | |
1819 | 7 | return rval; |
1820 | })(key); | |
1821 | } | |
1822 | else { | |
1823 | // recurse into @list or @set | |
1824 | 2213 | var isList = (expandedProperty === '@list'); |
1825 | 2213 | if(isList || expandedProperty === '@set') { |
1826 | 80 | var nextActiveProperty = activeProperty; |
1827 | 80 | if(isList && expandedActiveProperty === '@graph') { |
1828 | 2 | nextActiveProperty = null; |
1829 | } | |
1830 | 80 | expandedValue = self.expand( |
1831 | activeCtx, nextActiveProperty, value, options, isList); | |
1832 | 80 | if(isList && _isList(expandedValue)) { |
1833 | 0 | throw new JsonLdError( |
1834 | 'Invalid JSON-LD syntax; lists of lists are not permitted.', | |
1835 | 'jsonld.SyntaxError'); | |
1836 | } | |
1837 | } | |
1838 | else { | |
1839 | // recursively expand value with key as new active property | |
1840 | 2133 | expandedValue = self.expand(activeCtx, key, value, options, false); |
1841 | } | |
1842 | } | |
1843 | ||
1844 | // drop null values if property is not @value | |
1845 | 2224 | if(expandedValue === null && expandedProperty !== '@value') { |
1846 | 9 | continue; |
1847 | } | |
1848 | ||
1849 | // convert expanded value to @list if container specifies it | |
1850 | 2215 | if(expandedProperty !== '@list' && !_isList(expandedValue) && |
1851 | container === '@list') { | |
1852 | // ensure expanded value is an array | |
1853 | 20 | expandedValue = (_isArray(expandedValue) ? |
1854 | expandedValue : [expandedValue]); | |
1855 | 20 | expandedValue = {'@list': expandedValue}; |
1856 | } | |
1857 | ||
1858 | // FIXME: can this be merged with code above to simplify? | |
1859 | // merge in reverse properties | |
1860 | 2215 | if(activeCtx.mappings[key] && activeCtx.mappings[key].reverse) { |
1861 | 6 | var reverseMap = rval['@reverse'] = {}; |
1862 | 6 | if(!_isArray(expandedValue)) { |
1863 | 1 | expandedValue = [expandedValue]; |
1864 | } | |
1865 | 6 | for(var ii = 0; ii < expandedValue.length; ++ii) { |
1866 | 10 | var item = expandedValue[ii]; |
1867 | 10 | if(_isValue(item) || _isList(item)) { |
1868 | 0 | throw new JsonLdError( |
1869 | 'Invalid JSON-LD syntax; "@reverse" value must not be a ' + | |
1870 | '@value or an @list.', | |
1871 | 'jsonld.SyntaxError', {value: expandedValue}); | |
1872 | } | |
1873 | 10 | jsonld.addValue( |
1874 | reverseMap, expandedProperty, item, {propertyIsArray: true}); | |
1875 | } | |
1876 | 6 | continue; |
1877 | } | |
1878 | ||
1879 | // add value for property | |
1880 | // use an array except for certain keywords | |
1881 | 2209 | var useArray = |
1882 | ['@index', '@id', '@type', '@value', '@language'].indexOf( | |
1883 | expandedProperty) === -1; | |
1884 | 2209 | jsonld.addValue( |
1885 | rval, expandedProperty, expandedValue, {propertyIsArray: useArray}); | |
1886 | } | |
1887 | ||
1888 | // get property count on expanded output | |
1889 | 1109 | keys = Object.keys(rval); |
1890 | 1109 | var count = keys.length; |
1891 | ||
1892 | 1109 | if('@value' in rval) { |
1893 | // @value must only have @language or @type | |
1894 | 184 | if('@type' in rval && '@language' in rval) { |
1895 | 0 | throw new JsonLdError( |
1896 | 'Invalid JSON-LD syntax; an element containing "@value" may not ' + | |
1897 | 'contain both "@type" and "@language".', | |
1898 | 'jsonld.SyntaxError', {element: rval}); | |
1899 | } | |
1900 | 184 | var validCount = count - 1; |
1901 | 184 | if('@type' in rval) { |
1902 | 57 | validCount -= 1; |
1903 | } | |
1904 | 184 | if('@index' in rval) { |
1905 | 35 | validCount -= 1; |
1906 | } | |
1907 | 184 | if('@language' in rval) { |
1908 | 58 | validCount -= 1; |
1909 | } | |
1910 | 184 | if(validCount !== 0) { |
1911 | 0 | throw new JsonLdError( |
1912 | 'Invalid JSON-LD syntax; an element containing "@value" may only ' + | |
1913 | 'have an "@index" property and at most one other property ' + | |
1914 | 'which can be "@type" or "@language".', | |
1915 | 'jsonld.SyntaxError', {element: rval}); | |
1916 | } | |
1917 | // drop null @values | |
1918 | 184 | if(rval['@value'] === null) { |
1919 | 8 | rval = null; |
1920 | } | |
1921 | // drop @language if @value isn't a string | |
1922 | 176 | else if('@language' in rval && !_isString(rval['@value'])) { |
1923 | 0 | delete rval['@language']; |
1924 | } | |
1925 | } | |
1926 | // convert @type to an array | |
1927 | 925 | else if('@type' in rval && !_isArray(rval['@type'])) { |
1928 | 132 | rval['@type'] = [rval['@type']]; |
1929 | } | |
1930 | // handle @set and @list | |
1931 | 793 | else if('@set' in rval || '@list' in rval) { |
1932 | 80 | if(count > 1 && (count !== 2 && '@index' in rval)) { |
1933 | 0 | throw new JsonLdError( |
1934 | 'Invalid JSON-LD syntax; if an element has the property "@set" ' + | |
1935 | 'or "@list", then it can have at most one other property that is ' + | |
1936 | '"@index".', | |
1937 | 'jsonld.SyntaxError', {element: rval}); | |
1938 | } | |
1939 | // optimize away @set | |
1940 | 80 | if('@set' in rval) { |
1941 | 34 | rval = rval['@set']; |
1942 | 34 | keys = Object.keys(rval); |
1943 | 34 | count = keys.length; |
1944 | } | |
1945 | } | |
1946 | // drop objects with only @language | |
1947 | 713 | else if(count === 1 && '@language' in rval) { |
1948 | 2 | rval = null; |
1949 | } | |
1950 | ||
1951 | // drop certain top-level objects that do not occur in lists | |
1952 | 1109 | if(_isObject(rval) && |
1953 | !options.keepFreeFloatingNodes && !insideList && | |
1954 | (activeProperty === null || expandedActiveProperty === '@graph')) { | |
1955 | // drop empty object or top-level @value | |
1956 | 570 | if(count === 0 || ('@value' in rval)) { |
1957 | 6 | rval = null; |
1958 | } | |
1959 | else { | |
1960 | // drop nodes that generate no triples | |
1961 | 564 | var hasTriples = false; |
1962 | 564 | var ignore = ['@graph', '@type']; |
1963 | 564 | for(var ki = 0; !hasTriples && ki < keys.length; ++ki) { |
1964 | 990 | if(!_isKeyword(keys[ki]) || ignore.indexOf(keys[ki]) !== -1) { |
1965 | 538 | hasTriples = true; |
1966 | } | |
1967 | } | |
1968 | 564 | if(!hasTriples) { |
1969 | 26 | rval = null; |
1970 | } | |
1971 | } | |
1972 | } | |
1973 | ||
1974 | 1109 | return rval; |
1975 | } | |
1976 | ||
1977 | // drop top-level scalars that are not in lists | |
1978 | 2066 | if(!insideList && |
1979 | (activeProperty === null || | |
1980 | _expandIri(activeCtx, activeProperty, {vocab: true}) === '@graph')) { | |
1981 | 7 | return null; |
1982 | } | |
1983 | ||
1984 | // expand element according to value expansion rules | |
1985 | 2059 | return _expandValue(activeCtx, activeProperty, element); |
1986 | }; | |
1987 | ||
1988 | /** | |
1989 | * Performs JSON-LD flattening. | |
1990 | * | |
1991 | * @param input the expanded JSON-LD to flatten. | |
1992 | * | |
1993 | * @return the flattened output. | |
1994 | */ | |
1995 | 2 | Processor.prototype.flatten = function(input) { |
1996 | // produce a map of all subjects and name each bnode | |
1997 | 40 | var namer = new UniqueNamer('_:b'); |
1998 | 40 | var graphs = {'@default': {}}; |
1999 | 40 | _createNodeMap(input, graphs, '@default', namer); |
2000 | ||
2001 | // add all non-default graphs to default graph | |
2002 | 40 | var defaultGraph = graphs['@default']; |
2003 | 40 | var graphNames = Object.keys(graphs).sort(); |
2004 | 40 | for(var i = 0; i < graphNames.length; ++i) { |
2005 | 43 | var graphName = graphNames[i]; |
2006 | 43 | if(graphName === '@default') { |
2007 | 40 | continue; |
2008 | } | |
2009 | 3 | var nodeMap = graphs[graphName]; |
2010 | 3 | var subject = defaultGraph[graphName]; |
2011 | 3 | if(!subject) { |
2012 | 1 | defaultGraph[graphName] = subject = { |
2013 | '@id': graphName, | |
2014 | '@graph': [] | |
2015 | }; | |
2016 | } | |
2017 | 2 | else if(!('@graph' in subject)) { |
2018 | 2 | subject['@graph'] = []; |
2019 | } | |
2020 | 3 | var graph = subject['@graph']; |
2021 | 3 | var ids = Object.keys(nodeMap).sort(); |
2022 | 3 | for(var ii = 0; ii < ids.length; ++ii) { |
2023 | 11 | var id = ids[ii]; |
2024 | 11 | graph.push(nodeMap[id]); |
2025 | } | |
2026 | } | |
2027 | ||
2028 | // produce flattened output | |
2029 | 40 | var flattened = []; |
2030 | 40 | var keys = Object.keys(defaultGraph).sort(); |
2031 | 40 | for(var ki = 0; ki < keys.length; ++ki) { |
2032 | 122 | var key = keys[ki]; |
2033 | 122 | flattened.push(defaultGraph[key]); |
2034 | } | |
2035 | 40 | return flattened; |
2036 | }; | |
2037 | ||
2038 | /** | |
2039 | * Performs JSON-LD framing. | |
2040 | * | |
2041 | * @param input the expanded JSON-LD to frame. | |
2042 | * @param frame the expanded JSON-LD frame to use. | |
2043 | * @param options the framing options. | |
2044 | * | |
2045 | * @return the framed output. | |
2046 | */ | |
2047 | 2 | Processor.prototype.frame = function(input, frame, options) { |
2048 | // create framing state | |
2049 | 21 | var state = { |
2050 | options: options, | |
2051 | graphs: {'@default': {}, '@merged': {}} | |
2052 | }; | |
2053 | ||
2054 | // produce a map of all graphs and name each bnode | |
2055 | // FIXME: currently uses subjects from @merged graph only | |
2056 | 21 | namer = new UniqueNamer('_:b'); |
2057 | 21 | _createNodeMap(input, state.graphs, '@merged', namer); |
2058 | 21 | state.subjects = state.graphs['@merged']; |
2059 | ||
2060 | // frame the subjects | |
2061 | 21 | var framed = []; |
2062 | 21 | _frame(state, Object.keys(state.subjects).sort(), frame, framed, null); |
2063 | 21 | return framed; |
2064 | }; | |
2065 | ||
2066 | /** | |
2067 | * Performs normalization on the given RDF dataset. | |
2068 | * | |
2069 | * @param dataset the RDF dataset to normalize. | |
2070 | * @param options the normalization options. | |
2071 | * @param callback(err, normalized) called once the operation completes. | |
2072 | */ | |
2073 | 2 | Processor.prototype.normalize = function(dataset, options, callback) { |
2074 | // create quads and map bnodes to their associated quads | |
2075 | 57 | var quads = []; |
2076 | 57 | var bnodes = {}; |
2077 | 57 | for(var graphName in dataset) { |
2078 | 58 | var triples = dataset[graphName]; |
2079 | 58 | if(graphName === '@default') { |
2080 | 57 | graphName = null; |
2081 | } | |
2082 | 58 | for(var ti = 0; ti < triples.length; ++ti) { |
2083 | 306 | var quad = triples[ti]; |
2084 | 306 | if(graphName !== null) { |
2085 | 2 | if(graphName.indexOf('_:') === 0) { |
2086 | 2 | quad.name = {type: 'blank node', value: graphName}; |
2087 | } | |
2088 | else { | |
2089 | 0 | quad.name = {type: 'IRI', value: graphName}; |
2090 | } | |
2091 | } | |
2092 | 306 | quads.push(quad); |
2093 | ||
2094 | 306 | var attrs = ['subject', 'object', 'name']; |
2095 | 306 | for(var ai = 0; ai < attrs.length; ++ai) { |
2096 | 918 | var attr = attrs[ai]; |
2097 | 918 | if(quad[attr] && quad[attr].type === 'blank node') { |
2098 | 491 | var id = quad[attr].value; |
2099 | 491 | if(id in bnodes) { |
2100 | 325 | bnodes[id].quads.push(quad); |
2101 | } | |
2102 | else { | |
2103 | 166 | bnodes[id] = {quads: [quad]}; |
2104 | } | |
2105 | } | |
2106 | } | |
2107 | } | |
2108 | } | |
2109 | ||
2110 | // mapping complete, start canonical naming | |
2111 | 57 | var namer = new UniqueNamer('_:c14n'); |
2112 | 57 | return hashBlankNodes(Object.keys(bnodes)); |
2113 | ||
2114 | // generates unique and duplicate hashes for bnodes | |
2115 | 0 | function hashBlankNodes(unnamed) { |
2116 | 77 | var nextUnnamed = []; |
2117 | 77 | var duplicates = {}; |
2118 | 77 | var unique = {}; |
2119 | ||
2120 | // hash quads for each unnamed bnode | |
2121 | 154 | jsonld.nextTick(function() {hashUnnamed(0);}); |
2122 | 77 | function hashUnnamed(i) { |
2123 | 269 | if(i === unnamed.length) { |
2124 | // done, name blank nodes | |
2125 | 77 | return nameBlankNodes(unique, duplicates, nextUnnamed); |
2126 | } | |
2127 | ||
2128 | // hash unnamed bnode | |
2129 | 192 | var bnode = unnamed[i]; |
2130 | 192 | var hash = _hashQuads(bnode, bnodes, namer); |
2131 | ||
2132 | // store hash as unique or a duplicate | |
2133 | 192 | if(hash in duplicates) { |
2134 | 57 | duplicates[hash].push(bnode); |
2135 | 57 | nextUnnamed.push(bnode); |
2136 | } | |
2137 | 135 | else if(hash in unique) { |
2138 | 48 | duplicates[hash] = [unique[hash], bnode]; |
2139 | 48 | nextUnnamed.push(unique[hash]); |
2140 | 48 | nextUnnamed.push(bnode); |
2141 | 48 | delete unique[hash]; |
2142 | } | |
2143 | else { | |
2144 | 87 | unique[hash] = bnode; |
2145 | } | |
2146 | ||
2147 | // hash next unnamed bnode | |
2148 | 384 | jsonld.nextTick(function() {hashUnnamed(i + 1);}); |
2149 | } | |
2150 | } | |
2151 | ||
2152 | // names unique hash bnodes | |
2153 | 0 | function nameBlankNodes(unique, duplicates, unnamed) { |
2154 | // name unique bnodes in sorted hash order | |
2155 | 77 | var named = false; |
2156 | 77 | var hashes = Object.keys(unique).sort(); |
2157 | 77 | for(var i = 0; i < hashes.length; ++i) { |
2158 | 39 | var bnode = unique[hashes[i]]; |
2159 | 39 | namer.getName(bnode); |
2160 | 39 | named = true; |
2161 | } | |
2162 | ||
2163 | // continue to hash bnodes if a bnode was assigned a name | |
2164 | 77 | if(named) { |
2165 | 20 | hashBlankNodes(unnamed); |
2166 | } | |
2167 | // name the duplicate hash bnodes | |
2168 | else { | |
2169 | 57 | nameDuplicates(duplicates); |
2170 | } | |
2171 | } | |
2172 | ||
2173 | // names duplicate hash bnodes | |
2174 | 0 | function nameDuplicates(duplicates) { |
2175 | // enumerate duplicate hash groups in sorted order | |
2176 | 57 | var hashes = Object.keys(duplicates).sort(); |
2177 | ||
2178 | // process each group | |
2179 | 57 | processGroup(0); |
2180 | 57 | function processGroup(i) { |
2181 | 97 | if(i === hashes.length) { |
2182 | // done, create JSON-LD array | |
2183 | 57 | return createArray(); |
2184 | } | |
2185 | ||
2186 | // name each group member | |
2187 | 40 | var group = duplicates[hashes[i]]; |
2188 | 40 | var results = []; |
2189 | 40 | nameGroupMember(group, 0); |
2190 | 40 | function nameGroupMember(group, n) { |
2191 | 167 | if(n === group.length) { |
2192 | // name bnodes in hash order | |
2193 | 40 | results.sort(function(a, b) { |
2194 | 79 | a = a.hash; |
2195 | 79 | b = b.hash; |
2196 | 79 | return (a < b) ? -1 : ((a > b) ? 1 : 0); |
2197 | }); | |
2198 | 40 | for(var r in results) { |
2199 | // name all bnodes in path namer in key-entry order | |
2200 | // Note: key-order is preserved in javascript | |
2201 | 90 | for(var key in results[r].pathNamer.existing) { |
2202 | 353 | namer.getName(key); |
2203 | } | |
2204 | } | |
2205 | 40 | return processGroup(i + 1); |
2206 | } | |
2207 | ||
2208 | // skip already-named bnodes | |
2209 | 127 | var bnode = group[n]; |
2210 | 127 | if(namer.isNamed(bnode)) { |
2211 | 37 | return nameGroupMember(group, n + 1); |
2212 | } | |
2213 | ||
2214 | // hash bnode paths | |
2215 | 90 | var pathNamer = new UniqueNamer('_:b'); |
2216 | 90 | pathNamer.getName(bnode); |
2217 | 90 | _hashPaths(bnode, bnodes, namer, pathNamer, |
2218 | function(err, result) { | |
2219 | 90 | if(err) { |
2220 | 0 | return callback(err); |
2221 | } | |
2222 | 90 | results.push(result); |
2223 | 90 | nameGroupMember(group, n + 1); |
2224 | }); | |
2225 | } | |
2226 | } | |
2227 | } | |
2228 | ||
2229 | // creates the sorted array of RDF quads | |
2230 | 0 | function createArray() { |
2231 | 57 | var normalized = []; |
2232 | ||
2233 | /* Note: At this point all bnodes in the set of RDF quads have been | |
2234 | assigned canonical names, which have been stored in the 'namer' object. | |
2235 | Here each quad is updated by assigning each of its bnodes its new name | |
2236 | via the 'namer' object. */ | |
2237 | ||
2238 | // update bnode names in each quad and serialize | |
2239 | 57 | for(var i = 0; i < quads.length; ++i) { |
2240 | 306 | var quad = quads[i]; |
2241 | 306 | var attrs = ['subject', 'object', 'name']; |
2242 | 306 | for(var ai = 0; ai < attrs.length; ++ai) { |
2243 | 918 | var attr = attrs[ai]; |
2244 | 918 | if(quad[attr] && quad[attr].type === 'blank node' && |
2245 | quad[attr].value.indexOf('_:c14n') !== 0) { | |
2246 | 479 | quad[attr].value = namer.getName(quad[attr].value); |
2247 | } | |
2248 | } | |
2249 | 306 | normalized.push(_toNQuad(quad, quad.name ? quad.name.value : null)); |
2250 | } | |
2251 | ||
2252 | // sort normalized output | |
2253 | 57 | normalized.sort(); |
2254 | ||
2255 | // handle output format | |
2256 | 57 | if(options.format) { |
2257 | 57 | if(options.format === 'application/nquads') { |
2258 | 57 | return callback(null, normalized.join('')); |
2259 | } | |
2260 | 0 | return callback(new JsonLdError( |
2261 | 'Unknown output format.', | |
2262 | 'jsonld.UnknownFormat', {format: options.format})); | |
2263 | } | |
2264 | ||
2265 | // output RDF dataset | |
2266 | 0 | callback(null, _parseNQuads(normalized.join(''))); |
2267 | } | |
2268 | }; | |
2269 | ||
2270 | /** | |
2271 | * Converts an RDF dataset to JSON-LD. | |
2272 | * | |
2273 | * @param dataset the RDF dataset. | |
2274 | * @param options the RDF conversion options. | |
2275 | * @param callback(err, output) called once the operation completes. | |
2276 | */ | |
2277 | 2 | Processor.prototype.fromRDF = function(dataset, options, callback) { |
2278 | // prepare graph map (maps graph name => subjects, lists) | |
2279 | 7 | var defaultGraph = {subjects: {}, listMap: {}}; |
2280 | 7 | var graphs = {'@default': defaultGraph}; |
2281 | ||
2282 | 7 | for(var graphName in dataset) { |
2283 | 11 | var triples = dataset[graphName]; |
2284 | 11 | for(var ti = 0; ti < triples.length; ++ti) { |
2285 | 54 | var triple = triples[ti]; |
2286 | ||
2287 | // get subject, predicate, object | |
2288 | 54 | var s = triple.subject.value; |
2289 | 54 | var p = triple.predicate.value; |
2290 | 54 | var o = triple.object; |
2291 | ||
2292 | // create a graph entry as needed | |
2293 | 54 | var graph; |
2294 | 54 | if(!(graphName in graphs)) { |
2295 | 5 | graph = graphs[graphName] = {subjects: {}, listMap: {}}; |
2296 | } | |
2297 | else { | |
2298 | 49 | graph = graphs[graphName]; |
2299 | } | |
2300 | ||
2301 | // handle element in @list | |
2302 | 54 | if(p === RDF_FIRST) { |
2303 | // create list entry as needed | |
2304 | 9 | var listMap = graph.listMap; |
2305 | 9 | var entry; |
2306 | 9 | if(!(s in listMap)) { |
2307 | 7 | entry = listMap[s] = {}; |
2308 | } | |
2309 | else { | |
2310 | 2 | entry = listMap[s]; |
2311 | } | |
2312 | // set object value | |
2313 | 9 | entry.first = _RDFToObject(o, options.useNativeTypes); |
2314 | 9 | continue; |
2315 | } | |
2316 | ||
2317 | // handle other element in @list | |
2318 | 45 | if(p === RDF_REST) { |
2319 | // set next in list | |
2320 | 9 | if(o.type === 'blank node') { |
2321 | // create list entry as needed | |
2322 | 4 | var listMap = graph.listMap; |
2323 | 4 | var entry; |
2324 | 4 | if(!(s in listMap)) { |
2325 | 0 | entry = listMap[s] = {}; |
2326 | } | |
2327 | else { | |
2328 | 4 | entry = listMap[s]; |
2329 | } | |
2330 | 4 | entry.rest = o.value; |
2331 | } | |
2332 | 9 | continue; |
2333 | } | |
2334 | ||
2335 | // add graph subject to default graph as needed | |
2336 | 36 | if(graphName !== '@default' && !(graphName in defaultGraph.subjects)) { |
2337 | 4 | defaultGraph.subjects[graphName] = {'@id': graphName}; |
2338 | } | |
2339 | ||
2340 | // add subject to graph as needed | |
2341 | 36 | var subjects = graph.subjects; |
2342 | 36 | var value; |
2343 | 36 | if(!(s in subjects)) { |
2344 | 12 | value = subjects[s] = {'@id': s}; |
2345 | } | |
2346 | // use existing subject value | |
2347 | else { | |
2348 | 24 | value = subjects[s]; |
2349 | } | |
2350 | ||
2351 | // convert to @type unless options indicate to treat rdf:type as property | |
2352 | 36 | if(p === RDF_TYPE && !options.useRdfType) { |
2353 | // add value of object as @type | |
2354 | 11 | jsonld.addValue(value, '@type', o.value, {propertyIsArray: true}); |
2355 | } | |
2356 | else { | |
2357 | // add property to value as needed | |
2358 | 25 | var object = _RDFToObject(o, options.useNativeTypes); |
2359 | 25 | jsonld.addValue(value, p, object, {propertyIsArray: true}); |
2360 | ||
2361 | // a bnode might be the beginning of a list, so add it to the list map | |
2362 | 25 | if(o.type === 'blank node') { |
2363 | 6 | var id = object['@id']; |
2364 | 6 | var listMap = graph.listMap; |
2365 | 6 | var entry; |
2366 | 6 | if(!(id in listMap)) { |
2367 | 3 | entry = listMap[id] = {}; |
2368 | } | |
2369 | else { | |
2370 | 3 | entry = listMap[id]; |
2371 | } | |
2372 | 6 | entry.head = object; |
2373 | } | |
2374 | } | |
2375 | } | |
2376 | } | |
2377 | ||
2378 | // build @lists | |
2379 | 7 | for(var graphName in graphs) { |
2380 | 12 | var graph = graphs[graphName]; |
2381 | ||
2382 | // find list head | |
2383 | 12 | var listMap = graph.listMap; |
2384 | 12 | for(var subject in listMap) { |
2385 | 10 | var entry = listMap[subject]; |
2386 | ||
2387 | // head found, build lists | |
2388 | 10 | if('head' in entry && 'first' in entry) { |
2389 | // replace bnode @id with @list | |
2390 | 5 | delete entry.head['@id']; |
2391 | 5 | var list = entry.head['@list'] = [entry.first]; |
2392 | 5 | while('rest' in entry) { |
2393 | 4 | var rest = entry.rest; |
2394 | 4 | entry = listMap[rest]; |
2395 | 4 | if(!('first' in entry)) { |
2396 | 0 | throw new JsonLdError( |
2397 | 'Invalid RDF list entry.', | |
2398 | 'jsonld.RdfError', {bnode: rest}); | |
2399 | } | |
2400 | 4 | list.push(entry.first); |
2401 | } | |
2402 | } | |
2403 | } | |
2404 | } | |
2405 | ||
2406 | // build default graph in subject @id order | |
2407 | 7 | var output = []; |
2408 | 7 | var subjects = defaultGraph.subjects; |
2409 | 7 | var ids = Object.keys(subjects).sort(); |
2410 | 7 | for(var i = 0; i < ids.length; ++i) { |
2411 | 11 | var id = ids[i]; |
2412 | ||
2413 | // add subject to default graph | |
2414 | 11 | var subject = subjects[id]; |
2415 | 11 | output.push(subject); |
2416 | ||
2417 | // output named graph in subject @id order | |
2418 | 11 | if(id in graphs) { |
2419 | 5 | var graph = subject['@graph'] = []; |
2420 | 5 | var subjects_ = graphs[id].subjects; |
2421 | 5 | var ids_ = Object.keys(subjects_).sort(); |
2422 | 5 | for(var i_ = 0; i_ < ids_.length; ++i_) { |
2423 | 5 | graph.push(subjects_[ids_[i_]]); |
2424 | } | |
2425 | } | |
2426 | } | |
2427 | 7 | callback(null, output); |
2428 | }; | |
2429 | ||
2430 | /** | |
2431 | * Adds RDF triples for each graph in the given node map to an RDF dataset. | |
2432 | * | |
2433 | * @param nodeMap the node map. | |
2434 | * | |
2435 | * @return the RDF dataset. | |
2436 | */ | |
2437 | 2 | Processor.prototype.toRDF = function(nodeMap) { |
2438 | 87 | var namer = new UniqueNamer('_:b'); |
2439 | 87 | var dataset = {}; |
2440 | 87 | for(var graphName in nodeMap) { |
2441 | 94 | var graph = nodeMap[graphName]; |
2442 | 94 | if(graphName.indexOf('_:') === 0) { |
2443 | 1 | graphName = namer.getName(graphName); |
2444 | } | |
2445 | 94 | dataset[graphName] = _graphToRDF(graph, namer); |
2446 | } | |
2447 | 87 | return dataset; |
2448 | }; | |
2449 | ||
2450 | /** | |
2451 | * Processes a local context and returns a new active context. | |
2452 | * | |
2453 | * @param activeCtx the current active context. | |
2454 | * @param localCtx the local context to process. | |
2455 | * @param options the context processing options. | |
2456 | * | |
2457 | * @return the new active context. | |
2458 | */ | |
2459 | 2 | Processor.prototype.processContext = function(activeCtx, localCtx, options) { |
2460 | 326 | var rval = null; |
2461 | ||
2462 | // get context from cache if available | |
2463 | 326 | if(jsonld.cache.activeCtx) { |
2464 | 326 | rval = jsonld.cache.activeCtx.get(activeCtx, localCtx); |
2465 | 326 | if(rval) { |
2466 | 9 | return rval; |
2467 | } | |
2468 | } | |
2469 | ||
2470 | // initialize the resulting context | |
2471 | 317 | rval = activeCtx.clone(); |
2472 | ||
2473 | // normalize local context to an array of @context objects | |
2474 | 317 | if(_isObject(localCtx) && '@context' in localCtx && |
2475 | _isArray(localCtx['@context'])) { | |
2476 | 1 | localCtx = localCtx['@context']; |
2477 | } | |
2478 | 317 | var ctxs = _isArray(localCtx) ? localCtx : [localCtx]; |
2479 | ||
2480 | // process each context in order | |
2481 | 317 | for(var i in ctxs) { |
2482 | 321 | var ctx = ctxs[i]; |
2483 | ||
2484 | // reset to initial context, keeping namer | |
2485 | 321 | if(ctx === null) { |
2486 | 3 | rval = _getInitialContext(options); |
2487 | 3 | continue; |
2488 | } | |
2489 | ||
2490 | // dereference @context key if present | |
2491 | 318 | if(_isObject(ctx) && '@context' in ctx) { |
2492 | 85 | ctx = ctx['@context']; |
2493 | } | |
2494 | ||
2495 | // context must be an object by now, all URLs retrieved before this call | |
2496 | 318 | if(!_isObject(ctx)) { |
2497 | 0 | throw new JsonLdError( |
2498 | 'Invalid JSON-LD syntax; @context must be an object.', | |
2499 | 'jsonld.SyntaxError', {context: ctx}); | |
2500 | } | |
2501 | ||
2502 | // define context mappings for keys in local context | |
2503 | 318 | var defined = {}; |
2504 | ||
2505 | // handle @base | |
2506 | 318 | if('@base' in ctx) { |
2507 | 3 | var base = ctx['@base']; |
2508 | ||
2509 | // reset base | |
2510 | 3 | if(base === null) { |
2511 | 1 | base = options.base; |
2512 | } | |
2513 | 2 | else if(!_isString(base)) { |
2514 | 0 | throw new JsonLdError( |
2515 | 'Invalid JSON-LD syntax; the value of "@base" in a ' + | |
2516 | '@context must be a string or null.', | |
2517 | 'jsonld.SyntaxError', {context: ctx}); | |
2518 | } | |
2519 | 2 | else if(base !== '' && !_isAbsoluteIri(base)) { |
2520 | 0 | throw new JsonLdError( |
2521 | 'Invalid JSON-LD syntax; the value of "@base" in a ' + | |
2522 | '@context must be an absolute IRI or the empty string.', | |
2523 | 'jsonld.SyntaxError', {context: ctx}); | |
2524 | } | |
2525 | ||
2526 | 3 | base = jsonld.url.parse(base || ''); |
2527 | 3 | rval['@base'] = base; |
2528 | 3 | defined['@base'] = true; |
2529 | } | |
2530 | ||
2531 | // handle @vocab | |
2532 | 318 | if('@vocab' in ctx) { |
2533 | 24 | var value = ctx['@vocab']; |
2534 | 24 | if(value === null) { |
2535 | 1 | delete rval['@vocab']; |
2536 | } | |
2537 | 23 | else if(!_isString(value)) { |
2538 | 0 | throw new JsonLdError( |
2539 | 'Invalid JSON-LD syntax; the value of "@vocab" in a ' + | |
2540 | '@context must be a string or null.', | |
2541 | 'jsonld.SyntaxError', {context: ctx}); | |
2542 | } | |
2543 | 23 | else if(!_isAbsoluteIri(value)) { |
2544 | 0 | throw new JsonLdError( |
2545 | 'Invalid JSON-LD syntax; the value of "@vocab" in a ' + | |
2546 | '@context must be an absolute IRI.', | |
2547 | 'jsonld.SyntaxError', {context: ctx}); | |
2548 | } | |
2549 | else { | |
2550 | 23 | rval['@vocab'] = value; |
2551 | } | |
2552 | 24 | defined['@vocab'] = true; |
2553 | } | |
2554 | ||
2555 | // handle @language | |
2556 | 318 | if('@language' in ctx) { |
2557 | 13 | var value = ctx['@language']; |
2558 | 13 | if(value === null) { |
2559 | 1 | delete rval['@language']; |
2560 | } | |
2561 | 12 | else if(!_isString(value)) { |
2562 | 0 | throw new JsonLdError( |
2563 | 'Invalid JSON-LD syntax; the value of "@language" in a ' + | |
2564 | '@context must be a string or null.', | |
2565 | 'jsonld.SyntaxError', {context: ctx}); | |
2566 | } | |
2567 | else { | |
2568 | 12 | rval['@language'] = value.toLowerCase(); |
2569 | } | |
2570 | 13 | defined['@language'] = true; |
2571 | } | |
2572 | ||
2573 | // process all other keys | |
2574 | 318 | for(var key in ctx) { |
2575 | 972 | _createTermDefinition(rval, ctx, key, defined); |
2576 | } | |
2577 | } | |
2578 | ||
2579 | // cache result | |
2580 | 317 | if(jsonld.cache.activeCtx) { |
2581 | 317 | jsonld.cache.activeCtx.set(activeCtx, localCtx, rval); |
2582 | } | |
2583 | ||
2584 | 317 | return rval; |
2585 | }; | |
2586 | ||
2587 | /** | |
2588 | * Expands a language map. | |
2589 | * | |
2590 | * @param languageMap the language map to expand. | |
2591 | * | |
2592 | * @return the expanded language map. | |
2593 | */ | |
2594 | 2 | function _expandLanguageMap(languageMap) { |
2595 | 4 | var rval = []; |
2596 | 4 | var keys = Object.keys(languageMap).sort(); |
2597 | 4 | for(var ki = 0; ki < keys.length; ++ki) { |
2598 | 8 | var key = keys[ki]; |
2599 | 8 | var val = languageMap[key]; |
2600 | 8 | if(!_isArray(val)) { |
2601 | 4 | val = [val]; |
2602 | } | |
2603 | 8 | for(var vi = 0; vi < val.length; ++vi) { |
2604 | 12 | var item = val[vi]; |
2605 | 12 | if(!_isString(item)) { |
2606 | 0 | throw new JsonLdError( |
2607 | 'Invalid JSON-LD syntax; language map values must be strings.', | |
2608 | 'jsonld.SyntaxError', {languageMap: languageMap}); | |
2609 | } | |
2610 | 12 | rval.push({ |
2611 | '@value': item, | |
2612 | '@language': key.toLowerCase() | |
2613 | }); | |
2614 | } | |
2615 | } | |
2616 | 4 | return rval; |
2617 | } | |
2618 | ||
2619 | /** | |
2620 | * Labels the blank nodes in the given value using the given UniqueNamer. | |
2621 | * | |
2622 | * @param namer the UniqueNamer to use. | |
2623 | * @param element the element with blank nodes to rename. | |
2624 | * | |
2625 | * @return the element. | |
2626 | */ | |
2627 | 2 | function _labelBlankNodes(namer, element) { |
2628 | 0 | if(_isArray(element)) { |
2629 | 0 | for(var i = 0; i < element.length; ++i) { |
2630 | 0 | element[i] = _labelBlankNodes(namer, element[i]); |
2631 | } | |
2632 | } | |
2633 | 0 | else if(_isList(element)) { |
2634 | 0 | element['@list'] = _labelBlankNodes(namer, element['@list']); |
2635 | } | |
2636 | 0 | else if(_isObject(element)) { |
2637 | // rename blank node | |
2638 | 0 | if(_isBlankNode(element)) { |
2639 | 0 | element['@id'] = namer.getName(element['@id']); |
2640 | } | |
2641 | ||
2642 | // recursively apply to all keys | |
2643 | 0 | var keys = Object.keys(element).sort(); |
2644 | 0 | for(var ki = 0; ki < keys.length; ++ki) { |
2645 | 0 | var key = keys[ki]; |
2646 | 0 | if(key !== '@id') { |
2647 | 0 | element[key] = _labelBlankNodes(namer, element[key]); |
2648 | } | |
2649 | } | |
2650 | } | |
2651 | ||
2652 | 0 | return element; |
2653 | } | |
2654 | ||
2655 | /** | |
2656 | * Expands the given value by using the coercion and keyword rules in the | |
2657 | * given context. | |
2658 | * | |
2659 | * @param activeCtx the active context to use. | |
2660 | * @param activeProperty the active property the value is associated with. | |
2661 | * @param value the value to expand. | |
2662 | * | |
2663 | * @return the expanded value. | |
2664 | */ | |
2665 | 2 | function _expandValue(activeCtx, activeProperty, value) { |
2666 | // nothing to expand | |
2667 | 2059 | if(value === null) { |
2668 | 0 | return null; |
2669 | } | |
2670 | ||
2671 | // special-case expand @id and @type (skips '@id' expansion) | |
2672 | 2059 | var expandedProperty = _expandIri(activeCtx, activeProperty, {vocab: true}); |
2673 | 2059 | if(expandedProperty === '@id') { |
2674 | 631 | return _expandIri(activeCtx, value, {base: true}); |
2675 | } | |
2676 | 1428 | else if(expandedProperty === '@type') { |
2677 | 270 | return _expandIri(activeCtx, value, {vocab: true, base: true}); |
2678 | } | |
2679 | ||
2680 | // get type definition from context | |
2681 | 1158 | var type = jsonld.getContextValue(activeCtx, activeProperty, '@type'); |
2682 | ||
2683 | // do @id expansion (automatic for @graph) | |
2684 | 1158 | if(type === '@id' || (expandedProperty === '@graph' && _isString(value))) { |
2685 | 339 | return {'@id': _expandIri(activeCtx, value, {base: true})}; |
2686 | } | |
2687 | // do @id expansion w/vocab | |
2688 | 819 | if(type === '@vocab') { |
2689 | 10 | return {'@id': _expandIri(activeCtx, value, {vocab: true, base: true})}; |
2690 | } | |
2691 | ||
2692 | // do not expand keyword values | |
2693 | 809 | if(_isKeyword(expandedProperty)) { |
2694 | 302 | return value; |
2695 | } | |
2696 | ||
2697 | 507 | rval = {}; |
2698 | ||
2699 | // other type | |
2700 | 507 | if(type !== null) { |
2701 | 38 | rval['@type'] = type; |
2702 | } | |
2703 | // check for language tagging for strings | |
2704 | 469 | else if(_isString(value)) { |
2705 | 369 | var language = jsonld.getContextValue( |
2706 | activeCtx, activeProperty, '@language'); | |
2707 | 369 | if(language !== null) { |
2708 | 11 | rval['@language'] = language; |
2709 | } | |
2710 | } | |
2711 | 507 | rval['@value'] = value; |
2712 | ||
2713 | 507 | return rval; |
2714 | } | |
2715 | ||
2716 | /** | |
2717 | * Creates an array of RDF triples for the given graph. | |
2718 | * | |
2719 | * @param graph the graph to create RDF triples for. | |
2720 | * @param namer a UniqueNamer for assigning blank node names. | |
2721 | * | |
2722 | * @return the array of RDF triples for the given graph. | |
2723 | */ | |
2724 | 2 | function _graphToRDF(graph, namer) { |
2725 | 94 | var rval = []; |
2726 | ||
2727 | 94 | for(var id in graph) { |
2728 | 274 | var node = graph[id]; |
2729 | 274 | for(var property in node) { |
2730 | 537 | var items = node[property]; |
2731 | 537 | if(property === '@type') { |
2732 | 21 | property = RDF_TYPE; |
2733 | } | |
2734 | 516 | else if(_isKeyword(property)) { |
2735 | 274 | continue; |
2736 | } | |
2737 | ||
2738 | 263 | for(var i = 0; i < items.length; ++i) { |
2739 | 352 | var item = items[i]; |
2740 | ||
2741 | // RDF subject | |
2742 | 352 | var subject = {}; |
2743 | 352 | if(id.indexOf('_:') === 0) { |
2744 | 256 | subject.type = 'blank node'; |
2745 | 256 | subject.value = namer.getName(id); |
2746 | } | |
2747 | else { | |
2748 | 96 | subject.type = 'IRI'; |
2749 | 96 | subject.value = id; |
2750 | } | |
2751 | ||
2752 | // RDF predicate | |
2753 | 352 | var predicate = {type: 'IRI'}; |
2754 | 352 | predicate.value = property; |
2755 | ||
2756 | // convert @list to triples | |
2757 | 352 | if(_isList(item)) { |
2758 | 6 | _listToRDF(item['@list'], namer, subject, predicate, rval); |
2759 | } | |
2760 | // convert value or node object to triple | |
2761 | else { | |
2762 | 346 | var object = _objectToRDF(item, namer); |
2763 | 346 | rval.push({subject: subject, predicate: predicate, object: object}); |
2764 | } | |
2765 | } | |
2766 | } | |
2767 | } | |
2768 | ||
2769 | 94 | return rval; |
2770 | } | |
2771 | ||
2772 | /** | |
2773 | * Converts a @list value into linked list of blank node RDF triples | |
2774 | * (an RDF collection). | |
2775 | * | |
2776 | * @param list the @list value. | |
2777 | * @param namer a UniqueNamer for assigning blank node names. | |
2778 | * @param subject the subject for the head of the list. | |
2779 | * @param predicate the predicate for the head of the list. | |
2780 | * @param triples the array of triples to append to. | |
2781 | */ | |
2782 | 2 | function _listToRDF(list, namer, subject, predicate, triples) { |
2783 | 6 | var first = {type: 'IRI', value: RDF_FIRST}; |
2784 | 6 | var rest = {type: 'IRI', value: RDF_REST}; |
2785 | 6 | var nil = {type: 'IRI', value: RDF_NIL}; |
2786 | ||
2787 | 6 | for(var i = 0; i < list.length; ++i) { |
2788 | 10 | var item = list[i]; |
2789 | ||
2790 | 10 | var blankNode = {type: 'blank node', value: namer.getName()}; |
2791 | 10 | triples.push({subject: subject, predicate: predicate, object: blankNode}); |
2792 | ||
2793 | 10 | subject = blankNode; |
2794 | 10 | predicate = first; |
2795 | 10 | var object = _objectToRDF(item, namer); |
2796 | 10 | triples.push({subject: subject, predicate: predicate, object: object}); |
2797 | ||
2798 | 10 | predicate = rest; |
2799 | } | |
2800 | ||
2801 | 6 | triples.push({subject: subject, predicate: predicate, object: nil}); |
2802 | } | |
2803 | ||
2804 | /** | |
2805 | * Converts a JSON-LD value object to an RDF literal or a JSON-LD string or | |
2806 | * node object to an RDF resource. | |
2807 | * | |
2808 | * @param item the JSON-LD value or node object. | |
2809 | * @param namer the UniqueNamer to use to assign blank node names. | |
2810 | * | |
2811 | * @return the RDF literal or RDF resource. | |
2812 | */ | |
2813 | 2 | function _objectToRDF(item, namer) { |
2814 | 356 | var object = {}; |
2815 | ||
2816 | // convert value object to RDF | |
2817 | 356 | if(_isValue(item)) { |
2818 | 77 | object.type = 'literal'; |
2819 | 77 | var value = item['@value']; |
2820 | 77 | var datatype = item['@type'] || null; |
2821 | ||
2822 | // convert to XSD datatypes as appropriate | |
2823 | 77 | if(_isBoolean(value)) { |
2824 | 2 | object.value = value.toString(); |
2825 | 2 | object.datatype = datatype || XSD_BOOLEAN; |
2826 | } | |
2827 | 75 | else if(_isDouble(value)) { |
2828 | // canonical double representation | |
2829 | 2 | object.value = value.toExponential(15).replace(/(\d)0*e\+?/, '$1E'); |
2830 | 2 | object.datatype = datatype || XSD_DOUBLE; |
2831 | } | |
2832 | 73 | else if(_isNumber(value)) { |
2833 | 4 | object.value = value.toFixed(0); |
2834 | 4 | object.datatype = datatype || XSD_INTEGER; |
2835 | } | |
2836 | 69 | else if('@language' in item) { |
2837 | 3 | object.value = value; |
2838 | 3 | object.datatype = datatype || RDF_LANGSTRING; |
2839 | 3 | object.language = item['@language']; |
2840 | } | |
2841 | else { | |
2842 | 66 | object.value = value; |
2843 | 66 | object.datatype = datatype || XSD_STRING; |
2844 | } | |
2845 | } | |
2846 | // convert string/node object to RDF | |
2847 | else { | |
2848 | 279 | var id = _isObject(item) ? item['@id'] : item; |
2849 | 279 | if(id.indexOf('_:') === 0) { |
2850 | 228 | object.type = 'blank node'; |
2851 | 228 | object.value = namer.getName(id); |
2852 | } | |
2853 | else { | |
2854 | 51 | object.type = 'IRI'; |
2855 | 51 | object.value = id; |
2856 | } | |
2857 | } | |
2858 | ||
2859 | 356 | return object; |
2860 | } | |
2861 | ||
2862 | /** | |
2863 | * Converts an RDF triple object to a JSON-LD object. | |
2864 | * | |
2865 | * @param o the RDF triple object to convert. | |
2866 | * @param useNativeTypes true to output native types, false not to. | |
2867 | * | |
2868 | * @return the JSON-LD object. | |
2869 | */ | |
2870 | 2 | function _RDFToObject(o, useNativeTypes) { |
2871 | // convert empty list | |
2872 | 34 | if(o.type === 'IRI' && o.value === RDF_NIL) { |
2873 | 1 | return {'@list': []}; |
2874 | } | |
2875 | ||
2876 | // convert IRI/blank node object to JSON-LD | |
2877 | 33 | if(o.type === 'IRI' || o.type === 'blank node') { |
2878 | 13 | return {'@id': o.value}; |
2879 | } | |
2880 | ||
2881 | // convert literal to JSON-LD | |
2882 | 20 | var rval = {'@value': o.value}; |
2883 | ||
2884 | // add language | |
2885 | 20 | if('language' in o) { |
2886 | 1 | rval['@language'] = o.language; |
2887 | } | |
2888 | // add datatype | |
2889 | else { | |
2890 | 19 | var type = o.datatype; |
2891 | // use native types for certain xsd types | |
2892 | 19 | if(useNativeTypes) { |
2893 | 19 | if(type === XSD_BOOLEAN) { |
2894 | 2 | if(rval['@value'] === 'true') { |
2895 | 1 | rval['@value'] = true; |
2896 | } | |
2897 | 1 | else if(rval['@value'] === 'false') { |
2898 | 1 | rval['@value'] = false; |
2899 | } | |
2900 | } | |
2901 | 17 | else if(_isNumeric(rval['@value'])) { |
2902 | 4 | if(type === XSD_INTEGER) { |
2903 | 2 | var i = parseInt(rval['@value']); |
2904 | 2 | if(i.toFixed(0) === rval['@value']) { |
2905 | 2 | rval['@value'] = i; |
2906 | } | |
2907 | } | |
2908 | 2 | else if(type === XSD_DOUBLE) { |
2909 | 1 | rval['@value'] = parseFloat(rval['@value']); |
2910 | } | |
2911 | } | |
2912 | // do not add native type | |
2913 | 19 | if([XSD_BOOLEAN, XSD_INTEGER, XSD_DOUBLE, XSD_STRING] |
2914 | .indexOf(type) === -1) { | |
2915 | 2 | rval['@type'] = type; |
2916 | } | |
2917 | } | |
2918 | else { | |
2919 | 0 | rval['@type'] = type; |
2920 | } | |
2921 | } | |
2922 | ||
2923 | 20 | return rval; |
2924 | } | |
2925 | ||
2926 | /** | |
2927 | * Compares two RDF triples for equality. | |
2928 | * | |
2929 | * @param t1 the first triple. | |
2930 | * @param t2 the second triple. | |
2931 | * | |
2932 | * @return true if the triples are the same, false if not. | |
2933 | */ | |
2934 | 2 | function _compareRDFTriples(t1, t2) { |
2935 | 146 | var attrs = ['subject', 'predicate', 'object']; |
2936 | 146 | for(var i = 0; i < attrs.length; ++i) { |
2937 | 211 | var attr = attrs[i]; |
2938 | 211 | if(t1[attr].type !== t2[attr].type || t1[attr].value !== t2[attr].value) { |
2939 | 146 | return false; |
2940 | } | |
2941 | } | |
2942 | 0 | if(t1.object.language !== t2.object.language) { |
2943 | 0 | return false; |
2944 | } | |
2945 | 0 | if(t1.object.datatype !== t2.object.datatype) { |
2946 | 0 | return false; |
2947 | } | |
2948 | 0 | return true; |
2949 | } | |
2950 | ||
2951 | /** | |
2952 | * Hashes all of the quads about a blank node. | |
2953 | * | |
2954 | * @param id the ID of the bnode to hash quads for. | |
2955 | * @param bnodes the mapping of bnodes to quads. | |
2956 | * @param namer the canonical bnode namer. | |
2957 | * | |
2958 | * @return the new hash. | |
2959 | */ | |
2960 | 2 | function _hashQuads(id, bnodes, namer) { |
2961 | // return cached hash | |
2962 | 1438 | if('hash' in bnodes[id]) { |
2963 | 1272 | return bnodes[id].hash; |
2964 | } | |
2965 | ||
2966 | // serialize all of bnode's quads | |
2967 | 166 | var quads = bnodes[id].quads; |
2968 | 166 | var nquads = []; |
2969 | 166 | for(var i = 0; i < quads.length; ++i) { |
2970 | 491 | nquads.push(_toNQuad( |
2971 | quads[i], quads[i].name ? quads[i].name.value : null, id)); | |
2972 | } | |
2973 | // sort serialized quads | |
2974 | 166 | nquads.sort(); |
2975 | // return hashed quads | |
2976 | 166 | var hash = bnodes[id].hash = sha1.hash(nquads); |
2977 | 166 | return hash; |
2978 | } | |
2979 | ||
2980 | /** | |
2981 | * Produces a hash for the paths of adjacent bnodes for a bnode, | |
2982 | * incorporating all information about its subgraph of bnodes. This | |
2983 | * method will recursively pick adjacent bnode permutations that produce the | |
2984 | * lexicographically-least 'path' serializations. | |
2985 | * | |
2986 | * @param id the ID of the bnode to hash paths for. | |
2987 | * @param bnodes the map of bnode quads. | |
2988 | * @param namer the canonical bnode namer. | |
2989 | * @param pathNamer the namer used to assign names to adjacent bnodes. | |
2990 | * @param callback(err, result) called once the operation completes. | |
2991 | */ | |
2992 | 2 | function _hashPaths(id, bnodes, namer, pathNamer, callback) { |
2993 | // create SHA-1 digest | |
2994 | 1541 | var md = sha1.create(); |
2995 | ||
2996 | // group adjacent bnodes by hash, keep properties and references separate | |
2997 | 1541 | var groups = {}; |
2998 | 1541 | var groupHashes; |
2999 | 1541 | var quads = bnodes[id].quads; |
3000 | 3082 | jsonld.nextTick(function() {groupNodes(0);}); |
3001 | 1541 | function groupNodes(i) { |
3002 | 10319 | if(i === quads.length) { |
3003 | // done, hash groups | |
3004 | 1541 | groupHashes = Object.keys(groups).sort(); |
3005 | 1541 | return hashGroup(0); |
3006 | } | |
3007 | ||
3008 | // get adjacent bnode | |
3009 | 8778 | var quad = quads[i]; |
3010 | 8778 | var bnode = _getAdjacentBlankNodeName(quad.subject, id); |
3011 | 8778 | var direction = null; |
3012 | 8778 | if(bnode !== null) { |
3013 | // normal property | |
3014 | 4385 | direction = 'p'; |
3015 | } | |
3016 | else { | |
3017 | 4393 | bnode = _getAdjacentBlankNodeName(quad.object, id); |
3018 | 4393 | if(bnode !== null) { |
3019 | // reverse property | |
3020 | 4383 | direction = 'r'; |
3021 | } | |
3022 | } | |
3023 | ||
3024 | 8778 | if(bnode !== null) { |
3025 | // get bnode name (try canonical, path, then hash) | |
3026 | 8768 | var name; |
3027 | 8768 | if(namer.isNamed(bnode)) { |
3028 | 12 | name = namer.getName(bnode); |
3029 | } | |
3030 | 8756 | else if(pathNamer.isNamed(bnode)) { |
3031 | 7510 | name = pathNamer.getName(bnode); |
3032 | } | |
3033 | else { | |
3034 | 1246 | name = _hashQuads(bnode, bnodes, namer); |
3035 | } | |
3036 | ||
3037 | // hash direction, property, and bnode name/hash | |
3038 | 8768 | var md = sha1.create(); |
3039 | 8768 | md.update(direction); |
3040 | 8768 | md.update(quad.predicate.value); |
3041 | 8768 | md.update(name); |
3042 | 8768 | var groupHash = md.digest(); |
3043 | ||
3044 | // add bnode to hash group | |
3045 | 8768 | if(groupHash in groups) { |
3046 | 432 | groups[groupHash].push(bnode); |
3047 | } | |
3048 | else { | |
3049 | 8336 | groups[groupHash] = [bnode]; |
3050 | } | |
3051 | } | |
3052 | ||
3053 | 17556 | jsonld.nextTick(function() {groupNodes(i + 1);}); |
3054 | } | |
3055 | ||
3056 | // hashes a group of adjacent bnodes | |
3057 | 1541 | function hashGroup(i) { |
3058 | 9877 | if(i === groupHashes.length) { |
3059 | // done, return SHA-1 digest and path namer | |
3060 | 1541 | return callback(null, {hash: md.digest(), pathNamer: pathNamer}); |
3061 | } | |
3062 | ||
3063 | // digest group hash | |
3064 | 8336 | var groupHash = groupHashes[i]; |
3065 | 8336 | md.update(groupHash); |
3066 | ||
3067 | // choose a path and namer from the permutations | |
3068 | 8336 | var chosenPath = null; |
3069 | 8336 | var chosenNamer = null; |
3070 | 8336 | var permutator = new Permutator(groups[groupHash]); |
3071 | 16672 | jsonld.nextTick(function() {permutate();}); |
3072 | 8336 | function permutate() { |
3073 | 8984 | var permutation = permutator.next(); |
3074 | 8984 | var pathNamerCopy = pathNamer.clone(); |
3075 | ||
3076 | // build adjacent path | |
3077 | 8984 | var path = ''; |
3078 | 8984 | var recurse = []; |
3079 | 8984 | for(var n in permutation) { |
3080 | 10424 | var bnode = permutation[n]; |
3081 | ||
3082 | // use canonical name if available | |
3083 | 10424 | if(namer.isNamed(bnode)) { |
3084 | 12 | path += namer.getName(bnode); |
3085 | } | |
3086 | else { | |
3087 | // recurse if bnode isn't named in the path yet | |
3088 | 10412 | if(!pathNamerCopy.isNamed(bnode)) { |
3089 | 1451 | recurse.push(bnode); |
3090 | } | |
3091 | 10412 | path += pathNamerCopy.getName(bnode); |
3092 | } | |
3093 | ||
3094 | // skip permutation if path is already >= chosen path | |
3095 | 10424 | if(chosenPath !== null && path.length >= chosenPath.length && |
3096 | path > chosenPath) { | |
3097 | 282 | return nextPermutation(true); |
3098 | } | |
3099 | } | |
3100 | ||
3101 | // does the next recursion | |
3102 | 8702 | nextRecursion(0); |
3103 | 8702 | function nextRecursion(n) { |
3104 | 10081 | if(n === recurse.length) { |
3105 | // done, do next permutation | |
3106 | 8630 | return nextPermutation(false); |
3107 | } | |
3108 | ||
3109 | // do recursion | |
3110 | 1451 | var bnode = recurse[n]; |
3111 | 1451 | _hashPaths(bnode, bnodes, namer, pathNamerCopy, |
3112 | function(err, result) { | |
3113 | 1451 | if(err) { |
3114 | 0 | return callback(err); |
3115 | } | |
3116 | 1451 | path += pathNamerCopy.getName(bnode) + '<' + result.hash + '>'; |
3117 | 1451 | pathNamerCopy = result.pathNamer; |
3118 | ||
3119 | // skip permutation if path is already >= chosen path | |
3120 | 1451 | if(chosenPath !== null && path.length >= chosenPath.length && |
3121 | path > chosenPath) { | |
3122 | 72 | return nextPermutation(true); |
3123 | } | |
3124 | ||
3125 | // do next recursion | |
3126 | 1379 | nextRecursion(n + 1); |
3127 | }); | |
3128 | } | |
3129 | ||
3130 | // stores the results of this permutation and runs the next | |
3131 | 8702 | function nextPermutation(skipped) { |
3132 | 8984 | if(!skipped && (chosenPath === null || path < chosenPath)) { |
3133 | 8408 | chosenPath = path; |
3134 | 8408 | chosenNamer = pathNamerCopy; |
3135 | } | |
3136 | ||
3137 | // do next permutation | |
3138 | 8984 | if(permutator.hasNext()) { |
3139 | 1296 | jsonld.nextTick(function() {permutate();}); |
3140 | } | |
3141 | else { | |
3142 | // digest chosen path and update namer | |
3143 | 8336 | md.update(chosenPath); |
3144 | 8336 | pathNamer = chosenNamer; |
3145 | ||
3146 | // hash the next group | |
3147 | 8336 | hashGroup(i + 1); |
3148 | } | |
3149 | } | |
3150 | } | |
3151 | } | |
3152 | } | |
3153 | ||
3154 | /** | |
3155 | * A helper function that gets the blank node name from an RDF quad node | |
3156 | * (subject or object). If the node is a blank node and its value | |
3157 | * does not match the given blank node ID, it will be returned. | |
3158 | * | |
3159 | * @param node the RDF quad node. | |
3160 | * @param id the ID of the blank node to look next to. | |
3161 | * | |
3162 | * @return the adjacent blank node name or null if none was found. | |
3163 | */ | |
3164 | 2 | function _getAdjacentBlankNodeName(node, id) { |
3165 | 13171 | return (node.type === 'blank node' && node.value !== id ? node.value : null); |
3166 | } | |
3167 | ||
3168 | /** | |
3169 | * Recursively flattens the subjects in the given JSON-LD expanded input | |
3170 | * into a node map. | |
3171 | * | |
3172 | * @param input the JSON-LD expanded input. | |
3173 | * @param graphs a map of graph name to subject map. | |
3174 | * @param graph the name of the current graph. | |
3175 | * @param namer the blank node namer. | |
3176 | * @param name the name assigned to the current input if it is a bnode. | |
3177 | * @param list the list to append to, null for none. | |
3178 | */ | |
3179 | 2 | function _createNodeMap(input, graphs, graph, namer, name, list) { |
3180 | // recurse through array | |
3181 | 1279 | if(_isArray(input)) { |
3182 | 179 | for(var i in input) { |
3183 | 354 | _createNodeMap(input[i], graphs, graph, namer, undefined, list); |
3184 | } | |
3185 | 179 | return; |
3186 | } | |
3187 | ||
3188 | // add non-object to list | |
3189 | 1100 | if(!_isObject(input)) { |
3190 | 94 | if(list) { |
3191 | 0 | list.push(input); |
3192 | } | |
3193 | 94 | return; |
3194 | } | |
3195 | ||
3196 | // add values to list | |
3197 | 1006 | if(_isValue(input)) { |
3198 | 316 | if('@type' in input) { |
3199 | 38 | var type = input['@type']; |
3200 | // rename @type blank node | |
3201 | 38 | if(type.indexOf('_:') === 0) { |
3202 | 7 | input['@type'] = type = namer.getName(type); |
3203 | } | |
3204 | 38 | if(!(type in graphs[graph])) { |
3205 | 20 | graphs[graph][type] = {'@id': type}; |
3206 | } | |
3207 | } | |
3208 | 316 | if(list) { |
3209 | 27 | list.push(input); |
3210 | } | |
3211 | 316 | return; |
3212 | } | |
3213 | ||
3214 | // Note: At this point, input must be a subject. | |
3215 | ||
3216 | // get name for subject | |
3217 | 690 | if(_isUndefined(name)) { |
3218 | 332 | name = _isBlankNode(input) ? namer.getName(input['@id']) : input['@id']; |
3219 | } | |
3220 | ||
3221 | // add subject reference to list | |
3222 | 690 | if(list) { |
3223 | 13 | list.push({'@id': name}); |
3224 | } | |
3225 | ||
3226 | // create new subject or merge into existing one | |
3227 | 690 | var subjects = graphs[graph]; |
3228 | 690 | var subject = subjects[name] = subjects[name] || {}; |
3229 | 690 | subject['@id'] = name; |
3230 | 690 | var properties = Object.keys(input).sort(); |
3231 | 690 | for(var pi = 0; pi < properties.length; ++pi) { |
3232 | 1258 | var property = properties[pi]; |
3233 | ||
3234 | // skip @id | |
3235 | 1258 | if(property === '@id') { |
3236 | 652 | continue; |
3237 | } | |
3238 | ||
3239 | // handle reverse properties | |
3240 | 606 | if(property === '@reverse') { |
3241 | 3 | var referencedNode = {'@id': name}; |
3242 | 3 | var reverseMap = input['@reverse']; |
3243 | 3 | for(var reverseProperty in reverseMap) { |
3244 | 3 | var items = reverseMap[reverseProperty]; |
3245 | 3 | for(var ii = 0; ii < items.length; ++ii) { |
3246 | 5 | var item = items[ii]; |
3247 | 5 | jsonld.addValue( |
3248 | item, reverseProperty, referencedNode, | |
3249 | {propertyIsArray: true, allowDuplicate: false}); | |
3250 | 5 | _createNodeMap(item, graphs, graph, namer); |
3251 | } | |
3252 | } | |
3253 | 3 | continue; |
3254 | } | |
3255 | ||
3256 | // recurse into graph | |
3257 | 603 | if(property === '@graph') { |
3258 | // add graph subjects map entry | |
3259 | 10 | if(!(name in graphs)) { |
3260 | 10 | graphs[name] = {}; |
3261 | } | |
3262 | 10 | var g = (graph === '@merged') ? graph : name; |
3263 | 10 | _createNodeMap(input[property], graphs, g, namer); |
3264 | 10 | continue; |
3265 | } | |
3266 | ||
3267 | // copy non-@type keywords | |
3268 | 593 | if(property !== '@type' && _isKeyword(property)) { |
3269 | 5 | if(property === '@index' && '@index' in subject) { |
3270 | 0 | throw new JsonLdError( |
3271 | 'Invalid JSON-LD syntax; conflicting @index property detected.', | |
3272 | 'jsonld.SyntaxError', {subject: subject}); | |
3273 | } | |
3274 | 5 | subject[property] = input[property]; |
3275 | 5 | continue; |
3276 | } | |
3277 | ||
3278 | // iterate over objects | |
3279 | 588 | var objects = input[property]; |
3280 | ||
3281 | // if property is a bnode, assign it a new id | |
3282 | 588 | if(property.indexOf('_:') === 0) { |
3283 | 5 | property = namer.getName(property); |
3284 | } | |
3285 | ||
3286 | // ensure property is added for empty arrays | |
3287 | 588 | if(objects.length === 0) { |
3288 | 9 | jsonld.addValue(subject, property, [], {propertyIsArray: true}); |
3289 | 9 | continue; |
3290 | } | |
3291 | 579 | for(var oi = 0; oi < objects.length; ++oi) { |
3292 | 762 | var o = objects[oi]; |
3293 | ||
3294 | 762 | if(property === '@type') { |
3295 | // rename @type blank nodes | |
3296 | 94 | o = (o.indexOf('_:') === 0) ? namer.getName(o) : o; |
3297 | 94 | if(!(o in graphs[graph])) { |
3298 | 86 | graphs[graph][o] = {'@id': o}; |
3299 | } | |
3300 | } | |
3301 | ||
3302 | // handle embedded subject or subject reference | |
3303 | 762 | if(_isSubject(o) || _isSubjectReference(o)) { |
3304 | // rename blank node @id | |
3305 | 358 | var id = _isBlankNode(o) ? namer.getName(o['@id']) : o['@id']; |
3306 | ||
3307 | // add reference and recurse | |
3308 | 358 | jsonld.addValue( |
3309 | subject, property, {'@id': id}, | |
3310 | {propertyIsArray: true, allowDuplicate: false}); | |
3311 | 358 | _createNodeMap(o, graphs, graph, namer, id); |
3312 | } | |
3313 | // handle @list | |
3314 | 404 | else if(_isList(o)) { |
3315 | 21 | var _list = []; |
3316 | 21 | _createNodeMap(o['@list'], graphs, graph, namer, name, _list); |
3317 | 21 | o = {'@list': _list}; |
3318 | 21 | jsonld.addValue( |
3319 | subject, property, o, | |
3320 | {propertyIsArray: true, allowDuplicate: false}); | |
3321 | } | |
3322 | // handle @value | |
3323 | else { | |
3324 | 383 | _createNodeMap(o, graphs, graph, namer, name); |
3325 | 383 | jsonld.addValue( |
3326 | subject, property, o, {propertyIsArray: true, allowDuplicate: false}); | |
3327 | } | |
3328 | } | |
3329 | } | |
3330 | } | |
3331 | ||
3332 | /** | |
3333 | * Frames subjects according to the given frame. | |
3334 | * | |
3335 | * @param state the current framing state. | |
3336 | * @param subjects the subjects to filter. | |
3337 | * @param frame the frame. | |
3338 | * @param parent the parent subject or top-level array. | |
3339 | * @param property the parent property, initialized to null. | |
3340 | */ | |
3341 | 2 | function _frame(state, subjects, frame, parent, property) { |
3342 | // validate the frame | |
3343 | 44 | _validateFrame(state, frame); |
3344 | 44 | frame = frame[0]; |
3345 | ||
3346 | // filter out subjects that match the frame | |
3347 | 44 | var matches = _filterSubjects(state, subjects, frame); |
3348 | ||
3349 | // get flags for current frame | |
3350 | 44 | var options = state.options; |
3351 | 44 | var embedOn = _getFrameFlag(frame, options, 'embed'); |
3352 | 44 | var explicitOn = _getFrameFlag(frame, options, 'explicit'); |
3353 | ||
3354 | // add matches to output | |
3355 | 44 | var ids = Object.keys(matches).sort(); |
3356 | 44 | for(var idx in ids) { |
3357 | 60 | var id = ids[idx]; |
3358 | ||
3359 | /* Note: In order to treat each top-level match as a compartmentalized | |
3360 | result, create an independent copy of the embedded subjects map when the | |
3361 | property is null, which only occurs at the top-level. */ | |
3362 | 60 | if(property === null) { |
3363 | 37 | state.embeds = {}; |
3364 | } | |
3365 | ||
3366 | // start output | |
3367 | 60 | var output = {}; |
3368 | 60 | output['@id'] = id; |
3369 | ||
3370 | // prepare embed meta info | |
3371 | 60 | var embed = {parent: parent, property: property}; |
3372 | ||
3373 | // if embed is on and there is an existing embed | |
3374 | 60 | if(embedOn && (id in state.embeds)) { |
3375 | // only overwrite an existing embed if it has already been added to its | |
3376 | // parent -- otherwise its parent is somewhere up the tree from this | |
3377 | // embed and the embed would occur twice once the tree is added | |
3378 | 0 | embedOn = false; |
3379 | ||
3380 | // existing embed's parent is an array | |
3381 | 0 | var existing = state.embeds[id]; |
3382 | 0 | if(_isArray(existing.parent)) { |
3383 | 0 | for(var i in existing.parent) { |
3384 | 0 | if(jsonld.compareValues(output, existing.parent[i])) { |
3385 | 0 | embedOn = true; |
3386 | 0 | break; |
3387 | } | |
3388 | } | |
3389 | } | |
3390 | // existing embed's parent is an object | |
3391 | 0 | else if(jsonld.hasValue(existing.parent, existing.property, output)) { |
3392 | 0 | embedOn = true; |
3393 | } | |
3394 | ||
3395 | // existing embed has already been added, so allow an overwrite | |
3396 | 0 | if(embedOn) { |
3397 | 0 | _removeEmbed(state, id); |
3398 | } | |
3399 | } | |
3400 | ||
3401 | // not embedding, add output without any other properties | |
3402 | 60 | if(!embedOn) { |
3403 | 6 | _addFrameOutput(state, parent, property, output); |
3404 | } | |
3405 | else { | |
3406 | // add embed meta info | |
3407 | 54 | state.embeds[id] = embed; |
3408 | ||
3409 | // iterate over subject properties | |
3410 | 54 | var subject = matches[id]; |
3411 | 54 | var props = Object.keys(subject).sort(); |
3412 | 54 | for(var i in props) { |
3413 | 180 | var prop = props[i]; |
3414 | ||
3415 | // copy keywords to output | |
3416 | 180 | if(_isKeyword(prop)) { |
3417 | 91 | output[prop] = _clone(subject[prop]); |
3418 | 91 | continue; |
3419 | } | |
3420 | ||
3421 | // if property isn't in the frame | |
3422 | 89 | if(!(prop in frame)) { |
3423 | // if explicit is off, embed values | |
3424 | 64 | if(!explicitOn) { |
3425 | 62 | _embedValues(state, subject, prop, output); |
3426 | } | |
3427 | 64 | continue; |
3428 | } | |
3429 | ||
3430 | // add objects | |
3431 | 25 | var objects = subject[prop]; |
3432 | 25 | for(var i in objects) { |
3433 | 31 | var o = objects[i]; |
3434 | ||
3435 | // recurse into list | |
3436 | 31 | if(_isList(o)) { |
3437 | // add empty list | |
3438 | 0 | var list = {'@list': []}; |
3439 | 0 | _addFrameOutput(state, output, prop, list); |
3440 | ||
3441 | // add list objects | |
3442 | 0 | var src = o['@list']; |
3443 | 0 | for(var n in src) { |
3444 | 0 | o = src[n]; |
3445 | // recurse into subject reference | |
3446 | 0 | if(_isSubjectReference(o)) { |
3447 | 0 | _frame(state, [o['@id']], frame[prop], list, '@list'); |
3448 | } | |
3449 | // include other values automatically | |
3450 | else { | |
3451 | 0 | _addFrameOutput(state, list, '@list', _clone(o)); |
3452 | } | |
3453 | } | |
3454 | 0 | continue; |
3455 | } | |
3456 | ||
3457 | // recurse into subject reference | |
3458 | 31 | if(_isSubjectReference(o)) { |
3459 | 23 | _frame(state, [o['@id']], frame[prop], output, prop); |
3460 | } | |
3461 | // include other values automatically | |
3462 | else { | |
3463 | 8 | _addFrameOutput(state, output, prop, _clone(o)); |
3464 | } | |
3465 | } | |
3466 | } | |
3467 | ||
3468 | // handle defaults | |
3469 | 54 | var props = Object.keys(frame).sort(); |
3470 | 54 | for(var i in props) { |
3471 | 74 | var prop = props[i]; |
3472 | ||
3473 | // skip keywords | |
3474 | 74 | if(_isKeyword(prop)) { |
3475 | 39 | continue; |
3476 | } | |
3477 | ||
3478 | // if omit default is off, then include default values for properties | |
3479 | // that appear in the next frame but are not in the matching subject | |
3480 | 35 | var next = frame[prop][0]; |
3481 | 35 | var omitDefaultOn = _getFrameFlag(next, options, 'omitDefault'); |
3482 | 35 | if(!omitDefaultOn && !(prop in output)) { |
3483 | 7 | var preserve = '@null'; |
3484 | 7 | if('@default' in next) { |
3485 | 3 | preserve = _clone(next['@default']); |
3486 | } | |
3487 | 7 | if(!_isArray(preserve)) { |
3488 | 4 | preserve = [preserve]; |
3489 | } | |
3490 | 7 | output[prop] = [{'@preserve': preserve}]; |
3491 | } | |
3492 | } | |
3493 | ||
3494 | // add output to parent | |
3495 | 54 | _addFrameOutput(state, parent, property, output); |
3496 | } | |
3497 | } | |
3498 | } | |
3499 | ||
3500 | /** | |
3501 | * Gets the frame flag value for the given flag name. | |
3502 | * | |
3503 | * @param frame the frame. | |
3504 | * @param options the framing options. | |
3505 | * @param name the flag name. | |
3506 | * | |
3507 | * @return the flag value. | |
3508 | */ | |
3509 | 2 | function _getFrameFlag(frame, options, name) { |
3510 | 123 | var flag = '@' + name; |
3511 | 123 | return (flag in frame) ? frame[flag][0] : options[name]; |
3512 | } | |
3513 | ||
3514 | /** | |
3515 | * Validates a JSON-LD frame, throwing an exception if the frame is invalid. | |
3516 | * | |
3517 | * @param state the current frame state. | |
3518 | * @param frame the frame to validate. | |
3519 | */ | |
3520 | 2 | function _validateFrame(state, frame) { |
3521 | 44 | if(!_isArray(frame) || frame.length !== 1 || !_isObject(frame[0])) { |
3522 | 0 | throw new JsonLdError( |
3523 | 'Invalid JSON-LD syntax; a JSON-LD frame must be a single object.', | |
3524 | 'jsonld.SyntaxError', {frame: frame}); | |
3525 | } | |
3526 | } | |
3527 | ||
3528 | /** | |
3529 | * Returns a map of all of the subjects that match a parsed frame. | |
3530 | * | |
3531 | * @param state the current framing state. | |
3532 | * @param subjects the set of subjects to filter. | |
3533 | * @param frame the parsed frame. | |
3534 | * | |
3535 | * @return all of the matched subjects. | |
3536 | */ | |
3537 | 2 | function _filterSubjects(state, subjects, frame) { |
3538 | // filter subjects in @id order | |
3539 | 44 | var rval = {}; |
3540 | 44 | for(var i in subjects) { |
3541 | 133 | var id = subjects[i]; |
3542 | 133 | var subject = state.subjects[id]; |
3543 | 133 | if(_filterSubject(subject, frame)) { |
3544 | 60 | rval[id] = subject; |
3545 | } | |
3546 | } | |
3547 | 44 | return rval; |
3548 | } | |
3549 | ||
3550 | /** | |
3551 | * Returns true if the given subject matches the given frame. | |
3552 | * | |
3553 | * @param subject the subject to check. | |
3554 | * @param frame the frame to check. | |
3555 | * | |
3556 | * @return true if the subject matches, false if not. | |
3557 | */ | |
3558 | 2 | function _filterSubject(subject, frame) { |
3559 | // check @type (object value means 'any' type, fall through to ducktyping) | |
3560 | 133 | if('@type' in frame && |
3561 | !(frame['@type'].length === 1 && _isObject(frame['@type'][0]))) { | |
3562 | 104 | var types = frame['@type']; |
3563 | 104 | for(var i in types) { |
3564 | // any matching @type is a match | |
3565 | 221 | if(jsonld.hasValue(subject, '@type', types[i])) { |
3566 | 33 | return true; |
3567 | } | |
3568 | } | |
3569 | 71 | return false; |
3570 | } | |
3571 | ||
3572 | // check ducktype | |
3573 | 29 | for(var key in frame) { |
3574 | // only not a duck if @id or non-keyword isn't in subject | |
3575 | 15 | if((key === '@id' || !_isKeyword(key)) && !(key in subject)) { |
3576 | 2 | return false; |
3577 | } | |
3578 | } | |
3579 | 27 | return true; |
3580 | } | |
3581 | ||
3582 | /** | |
3583 | * Embeds values for the given subject and property into the given output | |
3584 | * during the framing algorithm. | |
3585 | * | |
3586 | * @param state the current framing state. | |
3587 | * @param subject the subject. | |
3588 | * @param property the property. | |
3589 | * @param output the output. | |
3590 | */ | |
3591 | 2 | function _embedValues(state, subject, property, output) { |
3592 | // embed subject properties in output | |
3593 | 112 | var objects = subject[property]; |
3594 | 112 | for(var i in objects) { |
3595 | 140 | var o = objects[i]; |
3596 | ||
3597 | // recurse into @list | |
3598 | 140 | if(_isList(o)) { |
3599 | 3 | var list = {'@list': []}; |
3600 | 3 | _addFrameOutput(state, output, property, list); |
3601 | 3 | return _embedValues(state, o, '@list', list['@list']); |
3602 | } | |
3603 | ||
3604 | // handle subject reference | |
3605 | 137 | if(_isSubjectReference(o)) { |
3606 | 32 | var id = o['@id']; |
3607 | ||
3608 | // embed full subject if isn't already embedded | |
3609 | 32 | if(!(id in state.embeds)) { |
3610 | // add embed | |
3611 | 28 | var embed = {parent: output, property: property}; |
3612 | 28 | state.embeds[id] = embed; |
3613 | ||
3614 | // recurse into subject | |
3615 | 28 | o = {}; |
3616 | 28 | var s = state.subjects[id]; |
3617 | 28 | for(var prop in s) { |
3618 | // copy keywords | |
3619 | 91 | if(_isKeyword(prop)) { |
3620 | 44 | o[prop] = _clone(s[prop]); |
3621 | 44 | continue; |
3622 | } | |
3623 | 47 | _embedValues(state, s, prop, o); |
3624 | } | |
3625 | } | |
3626 | 32 | _addFrameOutput(state, output, property, o); |
3627 | } | |
3628 | // copy non-subject value | |
3629 | else { | |
3630 | 105 | _addFrameOutput(state, output, property, _clone(o)); |
3631 | } | |
3632 | } | |
3633 | } | |
3634 | ||
3635 | /** | |
3636 | * Removes an existing embed. | |
3637 | * | |
3638 | * @param state the current framing state. | |
3639 | * @param id the @id of the embed to remove. | |
3640 | */ | |
3641 | 2 | function _removeEmbed(state, id) { |
3642 | // get existing embed | |
3643 | 0 | var embeds = state.embeds; |
3644 | 0 | var embed = embeds[id]; |
3645 | 0 | var parent = embed.parent; |
3646 | 0 | var property = embed.property; |
3647 | ||
3648 | // create reference to replace embed | |
3649 | 0 | var subject = {'@id': id}; |
3650 | ||
3651 | // remove existing embed | |
3652 | 0 | if(_isArray(parent)) { |
3653 | // replace subject with reference | |
3654 | 0 | for(var i in parent) { |
3655 | 0 | if(jsonld.compareValues(parent[i], subject)) { |
3656 | 0 | parent[i] = subject; |
3657 | 0 | break; |
3658 | } | |
3659 | } | |
3660 | } | |
3661 | else { | |
3662 | // replace subject with reference | |
3663 | 0 | var useArray = _isArray(parent[property]); |
3664 | 0 | jsonld.removeValue(parent, property, subject, {propertyIsArray: useArray}); |
3665 | 0 | jsonld.addValue(parent, property, subject, {propertyIsArray: useArray}); |
3666 | } | |
3667 | ||
3668 | // recursively remove dependent dangling embeds | |
3669 | 0 | var removeDependents = function(id) { |
3670 | // get embed keys as a separate array to enable deleting keys in map | |
3671 | 0 | var ids = Object.keys(embeds); |
3672 | 0 | for(var i in ids) { |
3673 | 0 | var next = ids[i]; |
3674 | 0 | if(next in embeds && _isObject(embeds[next].parent) && |
3675 | embeds[next].parent['@id'] === id) { | |
3676 | 0 | delete embeds[next]; |
3677 | 0 | removeDependents(next); |
3678 | } | |
3679 | } | |
3680 | }; | |
3681 | 0 | removeDependents(id); |
3682 | } | |
3683 | ||
3684 | /** | |
3685 | * Adds framing output to the given parent. | |
3686 | * | |
3687 | * @param state the current framing state. | |
3688 | * @param parent the parent to add to. | |
3689 | * @param property the parent property. | |
3690 | * @param output the output to add. | |
3691 | */ | |
3692 | 2 | function _addFrameOutput(state, parent, property, output) { |
3693 | 208 | if(_isObject(parent)) { |
3694 | 150 | jsonld.addValue(parent, property, output, {propertyIsArray: true}); |
3695 | } | |
3696 | else { | |
3697 | 58 | parent.push(output); |
3698 | } | |
3699 | } | |
3700 | ||
3701 | /** | |
3702 | * Removes the @preserve keywords as the last step of the framing algorithm. | |
3703 | * | |
3704 | * @param ctx the active context used to compact the input. | |
3705 | * @param input the framed, compacted output. | |
3706 | * @param options the compaction options used. | |
3707 | * | |
3708 | * @return the resulting output. | |
3709 | */ | |
3710 | 2 | function _removePreserve(ctx, input, options) { |
3711 | // recurse through arrays | |
3712 | 388 | if(_isArray(input)) { |
3713 | 34 | var output = []; |
3714 | 34 | for(var i in input) { |
3715 | 86 | var result = _removePreserve(ctx, input[i], options); |
3716 | // drop nulls from arrays | |
3717 | 86 | if(result !== null) { |
3718 | 84 | output.push(result); |
3719 | } | |
3720 | } | |
3721 | 34 | input = output; |
3722 | } | |
3723 | 354 | else if(_isObject(input)) { |
3724 | // remove @preserve | |
3725 | 105 | if('@preserve' in input) { |
3726 | 7 | if(input['@preserve'] === '@null') { |
3727 | 4 | return null; |
3728 | } | |
3729 | 3 | return input['@preserve']; |
3730 | } | |
3731 | ||
3732 | // skip @values | |
3733 | 98 | if(_isValue(input)) { |
3734 | 10 | return input; |
3735 | } | |
3736 | ||
3737 | // recurse through @lists | |
3738 | 88 | if(_isList(input)) { |
3739 | 0 | input['@list'] = _removePreserve(ctx, input['@list'], options); |
3740 | 0 | return input; |
3741 | } | |
3742 | ||
3743 | // recurse through properties | |
3744 | 88 | for(var prop in input) { |
3745 | 281 | var result = _removePreserve(ctx, input[prop], options); |
3746 | 281 | var container = jsonld.getContextValue(ctx, prop, '@container'); |
3747 | 281 | if(options.compactArrays && _isArray(result) && result.length === 1 && |
3748 | container === null) { | |
3749 | 1 | result = result[0]; |
3750 | } | |
3751 | 281 | input[prop] = result; |
3752 | } | |
3753 | } | |
3754 | 371 | return input; |
3755 | } | |
3756 | ||
3757 | /** | |
3758 | * Compares two strings first based on length and then lexicographically. | |
3759 | * | |
3760 | * @param a the first string. | |
3761 | * @param b the second string. | |
3762 | * | |
3763 | * @return -1 if a < b, 1 if a > b, 0 if a == b. | |
3764 | */ | |
3765 | 2 | function _compareShortestLeast(a, b) { |
3766 | 625 | if(a.length < b.length) { |
3767 | 196 | return -1; |
3768 | } | |
3769 | 429 | else if(b.length < a.length) { |
3770 | 236 | return 1; |
3771 | } | |
3772 | 193 | else if(a === b) { |
3773 | 0 | return 0; |
3774 | } | |
3775 | 193 | return (a < b) ? -1 : 1; |
3776 | } | |
3777 | ||
3778 | /** | |
3779 | * Picks the preferred compaction term from the given inverse context entry. | |
3780 | * | |
3781 | * @param activeCtx the active context. | |
3782 | * @param iri the IRI to pick the term for. | |
3783 | * @param value the value to pick the term for. | |
3784 | * @param containers the preferred containers. | |
3785 | * @param typeOrLanguage either '@type' or '@language'. | |
3786 | * @param typeOrLanguageValue the preferred value for '@type' or '@language'. | |
3787 | * | |
3788 | * @return the preferred term. | |
3789 | */ | |
3790 | function _selectTerm( | |
3791 | 2 | activeCtx, iri, value, containers, typeOrLanguage, typeOrLanguageValue) { |
3792 | 240 | if(typeOrLanguageValue === null) { |
3793 | 0 | typeOrLanguageValue = '@null'; |
3794 | } | |
3795 | ||
3796 | // preferences for the value of @type or @language | |
3797 | 240 | var prefs = []; |
3798 | ||
3799 | // determine prefs for @id based on whether or not value compacts to a term | |
3800 | 240 | if((typeOrLanguageValue === '@id' || typeOrLanguageValue === '@reverse') && |
3801 | _isSubjectReference(value)) { | |
3802 | // prefer @reverse first | |
3803 | 37 | if(typeOrLanguageValue === '@reverse') { |
3804 | 4 | prefs.push('@reverse'); |
3805 | } | |
3806 | // try to compact value to a term | |
3807 | 37 | var term = _compactIri(activeCtx, value['@id'], null, {vocab: true}); |
3808 | 37 | if(term in activeCtx.mappings && |
3809 | activeCtx.mappings[term] && | |
3810 | activeCtx.mappings[term]['@id'] === value['@id']) { | |
3811 | // prefer @vocab | |
3812 | 8 | prefs.push.apply(prefs, ['@vocab', '@id']); |
3813 | } | |
3814 | else { | |
3815 | // prefer @id | |
3816 | 29 | prefs.push.apply(prefs, ['@id', '@vocab']); |
3817 | } | |
3818 | } | |
3819 | else { | |
3820 | 203 | prefs.push(typeOrLanguageValue); |
3821 | } | |
3822 | 240 | prefs.push('@none'); |
3823 | ||
3824 | 240 | var containerMap = activeCtx.inverse[iri]; |
3825 | 240 | for(var ci = 0; ci < containers.length; ++ci) { |
3826 | // if container not available in the map, continue | |
3827 | 422 | var container = containers[ci]; |
3828 | 422 | if(!(container in containerMap)) { |
3829 | 185 | continue; |
3830 | } | |
3831 | ||
3832 | 237 | var typeOrLanguageValueMap = containerMap[container][typeOrLanguage]; |
3833 | 237 | for(var pi = 0; pi < prefs.length; ++pi) { |
3834 | // if type/language option not available in the map, continue | |
3835 | 409 | var pref = prefs[pi]; |
3836 | 409 | if(!(pref in typeOrLanguageValueMap)) { |
3837 | 177 | continue; |
3838 | } | |
3839 | ||
3840 | // select term | |
3841 | 232 | return typeOrLanguageValueMap[pref]; |
3842 | } | |
3843 | } | |
3844 | ||
3845 | 8 | return null; |
3846 | } | |
3847 | ||
3848 | /** | |
3849 | * Compacts an IRI or keyword into a term or prefix if it can be. If the | |
3850 | * IRI has an associated value it may be passed. | |
3851 | * | |
3852 | * @param activeCtx the active context to use. | |
3853 | * @param iri the IRI to compact. | |
3854 | * @param value the value to check or null. | |
3855 | * @param relativeTo options for how to compact IRIs: | |
3856 | * vocab: true to split after @vocab, false not to. | |
3857 | * @param reverse true if a reverse property is being compacted, false if not. | |
3858 | * | |
3859 | * @return the compacted term, prefix, keyword alias, or the original IRI. | |
3860 | */ | |
3861 | 2 | function _compactIri(activeCtx, iri, value, relativeTo, reverse) { |
3862 | // can't compact null | |
3863 | 1166 | if(iri === null) { |
3864 | 0 | return iri; |
3865 | } | |
3866 | ||
3867 | // default value and parent to null | |
3868 | 1166 | if(_isUndefined(value)) { |
3869 | 414 | value = null; |
3870 | } | |
3871 | // default reverse to false | |
3872 | 1166 | if(_isUndefined(reverse)) { |
3873 | 782 | reverse = false; |
3874 | } | |
3875 | 1166 | relativeTo = relativeTo || {}; |
3876 | ||
3877 | // if term is a keyword, default vocab to true | |
3878 | 1166 | if(_isKeyword(iri)) { |
3879 | 424 | relativeTo.vocab = true; |
3880 | } | |
3881 | ||
3882 | // use inverse context to pick a term if iri is relative to vocab | |
3883 | 1166 | if(relativeTo.vocab && iri in activeCtx.getInverse()) { |
3884 | 240 | var defaultLanguage = activeCtx['@language'] || '@none'; |
3885 | ||
3886 | // prefer @index if available in value | |
3887 | 240 | var containers = []; |
3888 | 240 | if(_isObject(value) && '@index' in value) { |
3889 | 39 | containers.push('@index'); |
3890 | } | |
3891 | ||
3892 | // defaults for term selection based on type/language | |
3893 | 240 | var typeOrLanguage = '@language'; |
3894 | 240 | var typeOrLanguageValue = '@null'; |
3895 | ||
3896 | 240 | if(reverse) { |
3897 | 11 | typeOrLanguage = '@type'; |
3898 | 11 | typeOrLanguageValue = '@reverse'; |
3899 | 11 | containers.push('@set'); |
3900 | } | |
3901 | // choose the most specific term that works for all elements in @list | |
3902 | 229 | else if(_isList(value)) { |
3903 | // only select @list containers if @index is NOT in value | |
3904 | 24 | if(!('@index' in value)) { |
3905 | 23 | containers.push('@list'); |
3906 | } | |
3907 | 24 | var list = value['@list']; |
3908 | 24 | var commonLanguage = (list.length === 0) ? defaultLanguage : null; |
3909 | 24 | var commonType = null; |
3910 | 24 | for(var i = 0; i < list.length; ++i) { |
3911 | 87 | var item = list[i]; |
3912 | 87 | var itemLanguage = '@none'; |
3913 | 87 | var itemType = '@none'; |
3914 | 87 | if(_isValue(item)) { |
3915 | 70 | if('@language' in item) { |
3916 | 12 | itemLanguage = item['@language']; |
3917 | } | |
3918 | 58 | else if('@type' in item) { |
3919 | 18 | itemType = item['@type']; |
3920 | } | |
3921 | // plain literal | |
3922 | else { | |
3923 | 40 | itemLanguage = '@null'; |
3924 | } | |
3925 | } | |
3926 | else { | |
3927 | 17 | itemType = '@id'; |
3928 | } | |
3929 | 87 | if(commonLanguage === null) { |
3930 | 23 | commonLanguage = itemLanguage; |
3931 | } | |
3932 | 64 | else if(itemLanguage !== commonLanguage && _isValue(item)) { |
3933 | 1 | commonLanguage = '@none'; |
3934 | } | |
3935 | 87 | if(commonType === null) { |
3936 | 23 | commonType = itemType; |
3937 | } | |
3938 | 64 | else if(itemType !== commonType) { |
3939 | 1 | commonType = '@none'; |
3940 | } | |
3941 | // there are different languages and types in the list, so choose | |
3942 | // the most generic term, no need to keep iterating the list | |
3943 | 87 | if(commonLanguage === '@none' && commonType === '@none') { |
3944 | 2 | break; |
3945 | } | |
3946 | } | |
3947 | 24 | commonLanguage = commonLanguage || '@none'; |
3948 | 24 | commonType = commonType || '@none'; |
3949 | 24 | if(commonType !== '@none') { |
3950 | 7 | typeOrLanguage = '@type'; |
3951 | 7 | typeOrLanguageValue = commonType; |
3952 | } | |
3953 | else { | |
3954 | 17 | typeOrLanguageValue = commonLanguage; |
3955 | } | |
3956 | } | |
3957 | else { | |
3958 | 205 | if(_isValue(value)) { |
3959 | 102 | if('@language' in value && !('@index' in value)) { |
3960 | 20 | containers.push('@language'); |
3961 | 20 | typeOrLanguageValue = value['@language']; |
3962 | } | |
3963 | 82 | else if('@type' in value) { |
3964 | 10 | typeOrLanguage = '@type'; |
3965 | 10 | typeOrLanguageValue = value['@type']; |
3966 | } | |
3967 | } | |
3968 | else { | |
3969 | 103 | typeOrLanguage = '@type'; |
3970 | 103 | typeOrLanguageValue = '@id'; |
3971 | } | |
3972 | 205 | containers.push('@set'); |
3973 | } | |
3974 | ||
3975 | // do term selection | |
3976 | 240 | containers.push('@none'); |
3977 | 240 | var term = _selectTerm( |
3978 | activeCtx, iri, value, containers, typeOrLanguage, typeOrLanguageValue); | |
3979 | 240 | if(term !== null) { |
3980 | 232 | return term; |
3981 | } | |
3982 | } | |
3983 | ||
3984 | // no term match, use @vocab if available | |
3985 | 934 | if(relativeTo.vocab) { |
3986 | 720 | if('@vocab' in activeCtx) { |
3987 | // determine if vocab is a prefix of the iri | |
3988 | 39 | var vocab = activeCtx['@vocab']; |
3989 | 39 | if(iri.indexOf(vocab) === 0 && iri !== vocab) { |
3990 | // use suffix as relative iri if it is not a term in the active context | |
3991 | 11 | var suffix = iri.substr(vocab.length); |
3992 | 11 | if(!(suffix in activeCtx.mappings)) { |
3993 | 10 | return suffix; |
3994 | } | |
3995 | } | |
3996 | } | |
3997 | } | |
3998 | ||
3999 | // no term or @vocab match, check for possible CURIEs | |
4000 | 924 | var choice = null; |
4001 | 924 | for(var term in activeCtx.mappings) { |
4002 | // skip terms with colons, they can't be prefixes | |
4003 | 6125 | if(term.indexOf(':') !== -1) { |
4004 | 3965 | continue; |
4005 | } | |
4006 | // skip entries with @ids that are not partial matches | |
4007 | 2160 | var definition = activeCtx.mappings[term]; |
4008 | 2160 | if(!definition || |
4009 | definition['@id'] === iri || iri.indexOf(definition['@id']) !== 0) { | |
4010 | 1909 | continue; |
4011 | } | |
4012 | ||
4013 | // a CURIE is usable if: | |
4014 | // 1. it has no mapping, OR | |
4015 | // 2. value is null, which means we're not compacting an @value, AND | |
4016 | // the mapping matches the IRI) | |
4017 | 251 | var curie = term + ':' + iri.substr(definition['@id'].length); |
4018 | 251 | var isUsableCurie = (!(curie in activeCtx.mappings) || |
4019 | (value === null && activeCtx.mappings[curie] && | |
4020 | activeCtx.mappings[curie]['@id'] === iri)); | |
4021 | ||
4022 | // select curie if it is shorter or the same length but lexicographically | |
4023 | // less than the current choice | |
4024 | 251 | if(isUsableCurie && (choice === null || |
4025 | _compareShortestLeast(curie, choice) < 0)) { | |
4026 | 250 | choice = curie; |
4027 | } | |
4028 | } | |
4029 | ||
4030 | // return chosen curie | |
4031 | 924 | if(choice !== null) { |
4032 | 230 | return choice; |
4033 | } | |
4034 | ||
4035 | // compact IRI relative to base | |
4036 | 694 | if(!relativeTo.vocab) { |
4037 | 174 | return _removeBase(activeCtx['@base'], iri); |
4038 | } | |
4039 | ||
4040 | // return IRI as is | |
4041 | 520 | return iri; |
4042 | } | |
4043 | ||
4044 | /** | |
4045 | * Performs value compaction on an object with '@value' or '@id' as the only | |
4046 | * property. | |
4047 | * | |
4048 | * @param activeCtx the active context. | |
4049 | * @param activeProperty the active property that points to the value. | |
4050 | * @param value the value to compact. | |
4051 | * | |
4052 | * @return the compaction result. | |
4053 | */ | |
4054 | 2 | function _compactValue(activeCtx, activeProperty, value) { |
4055 | // value is a @value | |
4056 | 361 | if(_isValue(value)) { |
4057 | // get context rules | |
4058 | 294 | var type = jsonld.getContextValue(activeCtx, activeProperty, '@type'); |
4059 | 294 | var language = jsonld.getContextValue( |
4060 | activeCtx, activeProperty, '@language'); | |
4061 | 294 | var container = jsonld.getContextValue( |
4062 | activeCtx, activeProperty, '@container'); | |
4063 | ||
4064 | // whether or not the value has an @index that must be preserved | |
4065 | 294 | var preserveIndex = (('@index' in value) && |
4066 | container !== '@index'); | |
4067 | ||
4068 | // if there's no @index to preserve ... | |
4069 | 294 | if(!preserveIndex) { |
4070 | // matching @type or @language specified in context, compact value | |
4071 | 286 | if(value['@type'] === type || value['@language'] === language) { |
4072 | 37 | return value['@value']; |
4073 | } | |
4074 | } | |
4075 | ||
4076 | // return just the value of @value if all are true: | |
4077 | // 1. @value is the only key or @index isn't being preserved | |
4078 | // 2. there is no default language or @value is not a string or | |
4079 | // the key has a mapping with a null @language | |
4080 | 257 | var keyCount = Object.keys(value).length; |
4081 | 257 | var isValueOnlyKey = (keyCount === 1 || |
4082 | (keyCount === 2 && ('@index' in value) && !preserveIndex)); | |
4083 | 257 | var hasDefaultLanguage = ('@language' in activeCtx); |
4084 | 257 | var isValueString = _isString(value['@value']); |
4085 | 257 | var hasNullMapping = (activeCtx.mappings[activeProperty] && |
4086 | activeCtx.mappings[activeProperty]['@language'] === null); | |
4087 | 257 | if(isValueOnlyKey && |
4088 | (!hasDefaultLanguage || !isValueString || hasNullMapping)) { | |
4089 | 208 | return value['@value']; |
4090 | } | |
4091 | ||
4092 | 49 | var rval = {}; |
4093 | ||
4094 | // preserve @index | |
4095 | 49 | if(preserveIndex) { |
4096 | 8 | rval[_compactIri(activeCtx, '@index')] = value['@index']; |
4097 | } | |
4098 | ||
4099 | // compact @type IRI | |
4100 | 49 | if('@type' in value) { |
4101 | 19 | rval[_compactIri(activeCtx, '@type')] = _compactIri( |
4102 | activeCtx, value['@type'], null, {vocab: true}); | |
4103 | } | |
4104 | // alias @language | |
4105 | 30 | else if('@language' in value) { |
4106 | 24 | rval[_compactIri(activeCtx, '@language')] = value['@language']; |
4107 | } | |
4108 | ||
4109 | // alias @value | |
4110 | 49 | rval[_compactIri(activeCtx, '@value')] = value['@value']; |
4111 | ||
4112 | 49 | return rval; |
4113 | } | |
4114 | ||
4115 | // value is a subject reference | |
4116 | 67 | var expandedProperty = _expandIri(activeCtx, activeProperty, {vocab: true}); |
4117 | 67 | var type = jsonld.getContextValue(activeCtx, activeProperty, '@type'); |
4118 | 67 | var compacted = _compactIri( |
4119 | activeCtx, value['@id'], null, {vocab: type === '@vocab'}); | |
4120 | ||
4121 | // compact to scalar | |
4122 | 67 | if(type === '@id' || type === '@vocab' || expandedProperty === '@graph') { |
4123 | 47 | return compacted; |
4124 | } | |
4125 | ||
4126 | 20 | var rval = {}; |
4127 | 20 | rval[_compactIri(activeCtx, '@id')] = compacted; |
4128 | 20 | return rval; |
4129 | } | |
4130 | ||
4131 | /** | |
4132 | * Creates a term definition during context processing. | |
4133 | * | |
4134 | * @param activeCtx the current active context. | |
4135 | * @param localCtx the local context being processed. | |
4136 | * @param term the term in the local context to define the mapping for. | |
4137 | * @param defined a map of defining/defined keys to detect cycles and prevent | |
4138 | * double definitions. | |
4139 | */ | |
4140 | 2 | function _createTermDefinition(activeCtx, localCtx, term, defined) { |
4141 | 1271 | if(term in defined) { |
4142 | // term already defined | |
4143 | 339 | if(defined[term]) { |
4144 | 339 | return; |
4145 | } | |
4146 | // cycle detected | |
4147 | 0 | throw new JsonLdError( |
4148 | 'Cyclical context definition detected.', | |
4149 | 'jsonld.CyclicalContext', {context: localCtx, term: term}); | |
4150 | } | |
4151 | ||
4152 | // now defining term | |
4153 | 932 | defined[term] = false; |
4154 | ||
4155 | 932 | if(_isKeyword(term)) { |
4156 | 0 | throw new JsonLdError( |
4157 | 'Invalid JSON-LD syntax; keywords cannot be overridden.', | |
4158 | 'jsonld.SyntaxError', {context: localCtx}); | |
4159 | } | |
4160 | ||
4161 | // remove old mapping | |
4162 | 932 | if(activeCtx.mappings[term]) { |
4163 | 1 | delete activeCtx.mappings[term]; |
4164 | } | |
4165 | ||
4166 | // get context term value | |
4167 | 932 | var value = localCtx[term]; |
4168 | ||
4169 | // clear context entry | |
4170 | 932 | if(value === null || (_isObject(value) && value['@id'] === null)) { |
4171 | 5 | activeCtx.mappings[term] = null; |
4172 | 5 | defined[term] = true; |
4173 | 5 | return; |
4174 | } | |
4175 | ||
4176 | 927 | if(_isString(value)) { |
4177 | // expand value to a full IRI | |
4178 | 451 | var id = _expandIri( |
4179 | activeCtx, value, {vocab: true, base: true}, localCtx, defined); | |
4180 | ||
4181 | 451 | if(_isKeyword(id)) { |
4182 | // disallow aliasing @context and @preserve | |
4183 | 29 | if(id === '@context' || id === '@preserve') { |
4184 | 0 | throw new JsonLdError( |
4185 | 'Invalid JSON-LD syntax; @context and @preserve cannot be aliased.', | |
4186 | 'jsonld.SyntaxError'); | |
4187 | } | |
4188 | } | |
4189 | ||
4190 | // define term to expanded IRI/keyword | |
4191 | 451 | activeCtx.mappings[term] = {'@id': id, reverse: false}; |
4192 | 451 | defined[term] = true; |
4193 | 451 | return; |
4194 | } | |
4195 | ||
4196 | 476 | if(!_isObject(value)) { |
4197 | 0 | throw new JsonLdError( |
4198 | 'Invalid JSON-LD syntax; @context property values must be ' + | |
4199 | 'strings or objects.', | |
4200 | 'jsonld.SyntaxError', {context: localCtx}); | |
4201 | } | |
4202 | ||
4203 | // create new mapping | |
4204 | 476 | var mapping = {}; |
4205 | 476 | mapping.reverse = false; |
4206 | ||
4207 | 476 | if('@reverse' in value) { |
4208 | 11 | if('@id' in value || '@type' in value || '@language' in value) { |
4209 | 0 | throw new JsonLdError( |
4210 | 'Invalid JSON-LD syntax; a @reverse term definition must not ' + | |
4211 | 'contain @id, @type, or @language.', | |
4212 | 'jsonld.SyntaxError', {context: localCtx}); | |
4213 | } | |
4214 | 11 | var reverse = value['@reverse']; |
4215 | 11 | if(!_isString(reverse)) { |
4216 | 0 | throw new JsonLdError( |
4217 | 'Invalid JSON-LD syntax; a @context @reverse value must be a string.', | |
4218 | 'jsonld.SyntaxError', {context: localCtx}); | |
4219 | } | |
4220 | ||
4221 | // expand and add @id mapping, set @type to @id | |
4222 | 11 | mapping['@id'] = _expandIri( |
4223 | activeCtx, reverse, {vocab: true, base: true}, localCtx, defined); | |
4224 | 11 | mapping['@type'] = '@id'; |
4225 | 11 | mapping.reverse = true; |
4226 | } | |
4227 | 465 | else if('@id' in value) { |
4228 | 200 | var id = value['@id']; |
4229 | 200 | if(!_isString(id)) { |
4230 | 0 | throw new JsonLdError( |
4231 | 'Invalid JSON-LD syntax; a @context @id value must be an array ' + | |
4232 | 'of strings or a string.', | |
4233 | 'jsonld.SyntaxError', {context: localCtx}); | |
4234 | } | |
4235 | // expand and add @id mapping | |
4236 | 200 | mapping['@id'] = _expandIri( |
4237 | activeCtx, id, {vocab: true, base: true}, localCtx, defined); | |
4238 | } | |
4239 | else { | |
4240 | // see if the term has a prefix | |
4241 | 265 | var colon = term.indexOf(':'); |
4242 | 265 | if(colon !== -1) { |
4243 | 253 | var prefix = term.substr(0, colon); |
4244 | 253 | if(prefix in localCtx) { |
4245 | // define parent prefix | |
4246 | 243 | _createTermDefinition(activeCtx, localCtx, prefix, defined); |
4247 | } | |
4248 | ||
4249 | // set @id based on prefix parent | |
4250 | 253 | if(activeCtx.mappings[prefix]) { |
4251 | 243 | var suffix = term.substr(colon + 1); |
4252 | 243 | mapping['@id'] = activeCtx.mappings[prefix]['@id'] + suffix; |
4253 | } | |
4254 | // term is an absolute IRI | |
4255 | else { | |
4256 | 10 | mapping['@id'] = term; |
4257 | } | |
4258 | } | |
4259 | else { | |
4260 | // non-IRIs *must* define @ids if @vocab is not available | |
4261 | 12 | if(!('@vocab' in activeCtx)) { |
4262 | 0 | throw new JsonLdError( |
4263 | 'Invalid JSON-LD syntax; @context terms must define an @id.', | |
4264 | 'jsonld.SyntaxError', {context: localCtx, term: term}); | |
4265 | } | |
4266 | // prepend vocab to term | |
4267 | 12 | mapping['@id'] = activeCtx['@vocab'] + term; |
4268 | } | |
4269 | } | |
4270 | ||
4271 | 476 | if('@type' in value) { |
4272 | 347 | var type = value['@type']; |
4273 | 347 | if(!_isString(type)) { |
4274 | 0 | throw new JsonLdError( |
4275 | 'Invalid JSON-LD syntax; @context @type values must be strings.', | |
4276 | 'jsonld.SyntaxError', {context: localCtx}); | |
4277 | } | |
4278 | ||
4279 | 347 | if(type !== '@id') { |
4280 | // expand @type to full IRI | |
4281 | 63 | type = _expandIri( |
4282 | activeCtx, type, {vocab: true, base: true}, localCtx, defined); | |
4283 | } | |
4284 | ||
4285 | // add @type to mapping | |
4286 | 347 | mapping['@type'] = type; |
4287 | } | |
4288 | ||
4289 | 476 | if('@container' in value) { |
4290 | 104 | var container = value['@container']; |
4291 | 104 | if(container !== '@list' && container !== '@set' && |
4292 | container !== '@index' && container !== '@language') { | |
4293 | 0 | throw new JsonLdError( |
4294 | 'Invalid JSON-LD syntax; @context @container value must be ' + | |
4295 | 'one of the following: @list, @set, @index, or @language.', | |
4296 | 'jsonld.SyntaxError', {context: localCtx}); | |
4297 | } | |
4298 | 104 | if(mapping.reverse && container !== '@index') { |
4299 | 0 | throw new JsonLdError( |
4300 | 'Invalid JSON-LD syntax; @context @container value for a @reverse ' + | |
4301 | 'type definition must be @index.', | |
4302 | 'jsonld.SyntaxError', {context: localCtx}); | |
4303 | } | |
4304 | ||
4305 | // add @container to mapping | |
4306 | 104 | mapping['@container'] = container; |
4307 | } | |
4308 | ||
4309 | 476 | if('@language' in value && !('@type' in value)) { |
4310 | 16 | var language = value['@language']; |
4311 | 16 | if(language !== null && !_isString(language)) { |
4312 | 0 | throw new JsonLdError( |
4313 | 'Invalid JSON-LD syntax; @context @language value must be ' + | |
4314 | 'a string or null.', | |
4315 | 'jsonld.SyntaxError', {context: localCtx}); | |
4316 | } | |
4317 | ||
4318 | // add @language to mapping | |
4319 | 16 | if(language !== null) { |
4320 | 10 | language = language.toLowerCase(); |
4321 | } | |
4322 | 16 | mapping['@language'] = language; |
4323 | } | |
4324 | ||
4325 | // define term mapping | |
4326 | 476 | activeCtx.mappings[term] = mapping; |
4327 | 476 | defined[term] = true; |
4328 | } | |
4329 | ||
4330 | /** | |
4331 | * Expands a string to a full IRI. The string may be a term, a prefix, a | |
4332 | * relative IRI, or an absolute IRI. The associated absolute IRI will be | |
4333 | * returned. | |
4334 | * | |
4335 | * @param activeCtx the current active context. | |
4336 | * @param value the string to expand. | |
4337 | * @param relativeTo options for how to resolve relative IRIs: | |
4338 | * base: true to resolve against the base IRI, false not to. | |
4339 | * vocab: true to concatenate after @vocab, false not to. | |
4340 | * @param localCtx the local context being processed (only given if called | |
4341 | * during context processing). | |
4342 | * @param defined a map for tracking cycles in context definitions (only given | |
4343 | * if called during context processing). | |
4344 | * | |
4345 | * @return the expanded value. | |
4346 | */ | |
4347 | 2 | function _expandIri(activeCtx, value, relativeTo, localCtx, defined) { |
4348 | // already expanded | |
4349 | 9504 | if(value === null || _isKeyword(value)) { |
4350 | 4270 | return value; |
4351 | } | |
4352 | ||
4353 | // define term dependency if not defined | |
4354 | 5234 | if(localCtx && value in localCtx && defined[value] !== true) { |
4355 | 1 | _createTermDefinition(activeCtx, localCtx, value, defined); |
4356 | } | |
4357 | ||
4358 | 5234 | relativeTo = relativeTo || {}; |
4359 | 5234 | if(relativeTo.vocab) { |
4360 | 4264 | var mapping = activeCtx.mappings[value]; |
4361 | ||
4362 | // value is explicitly ignored with a null mapping | |
4363 | 4264 | if(mapping === null) { |
4364 | 4 | return null; |
4365 | } | |
4366 | ||
4367 | 4260 | if(mapping) { |
4368 | // value is a term | |
4369 | 2167 | return mapping['@id']; |
4370 | } | |
4371 | } | |
4372 | ||
4373 | // split value into prefix:suffix | |
4374 | 3063 | var colon = value.indexOf(':'); |
4375 | 3063 | if(colon !== -1) { |
4376 | 2879 | var prefix = value.substr(0, colon); |
4377 | 2879 | var suffix = value.substr(colon + 1); |
4378 | ||
4379 | // do not expand blank nodes (prefix of '_') or already-absolute | |
4380 | // IRIs (suffix of '//') | |
4381 | 2879 | if(prefix === '_' || suffix.indexOf('//') === 0) { |
4382 | 2149 | return value; |
4383 | } | |
4384 | ||
4385 | // prefix dependency not defined, define it | |
4386 | 730 | if(localCtx && prefix in localCtx) { |
4387 | 55 | _createTermDefinition(activeCtx, localCtx, prefix, defined); |
4388 | } | |
4389 | ||
4390 | // use mapping if prefix is defined | |
4391 | 730 | var mapping = activeCtx.mappings[prefix]; |
4392 | 730 | if(mapping) { |
4393 | 728 | return mapping['@id'] + suffix; |
4394 | } | |
4395 | ||
4396 | // already absolute IRI | |
4397 | 2 | return value; |
4398 | } | |
4399 | ||
4400 | // prepend vocab | |
4401 | 184 | if(relativeTo.vocab && '@vocab' in activeCtx) { |
4402 | 49 | return activeCtx['@vocab'] + value; |
4403 | } | |
4404 | ||
4405 | // prepend base | |
4406 | 135 | var rval = value; |
4407 | 135 | if(relativeTo.base) { |
4408 | 105 | rval = _prependBase(activeCtx['@base'], rval); |
4409 | } | |
4410 | ||
4411 | 135 | if(localCtx) { |
4412 | // value must now be an absolute IRI | |
4413 | 0 | if(!_isAbsoluteIri(rval)) { |
4414 | 0 | throw new JsonLdError( |
4415 | 'Invalid JSON-LD syntax; a @context value does not expand to ' + | |
4416 | 'an absolute IRI.', | |
4417 | 'jsonld.SyntaxError', {context: localCtx, value: value}); | |
4418 | } | |
4419 | } | |
4420 | ||
4421 | 135 | return rval; |
4422 | } | |
4423 | ||
4424 | /** | |
4425 | * Prepends a base IRI to the given relative IRI. | |
4426 | * | |
4427 | * @param base the base IRI. | |
4428 | * @param iri the relative IRI. | |
4429 | * | |
4430 | * @return the absolute IRI. | |
4431 | */ | |
4432 | 2 | function _prependBase(base, iri) { |
4433 | // already an absolute IRI | |
4434 | 105 | if(iri.indexOf(':') !== -1) { |
4435 | 0 | return iri; |
4436 | } | |
4437 | ||
4438 | // parse base if it is a string | |
4439 | 105 | if(_isString(base)) { |
4440 | 0 | base = jsonld.url.parse(base || ''); |
4441 | } | |
4442 | ||
4443 | // parse given IRI | |
4444 | 105 | var rel = jsonld.url.parse(iri); |
4445 | ||
4446 | // start hierarchical part | |
4447 | 105 | var hierPart = (base.protocol || ''); |
4448 | 105 | if(rel.authority) { |
4449 | 8 | hierPart += '//' + rel.authority; |
4450 | } | |
4451 | 97 | else if(base.href !== '') { |
4452 | 97 | hierPart += '//' + base.authority; |
4453 | } | |
4454 | ||
4455 | // per RFC3986 normalize | |
4456 | 105 | var path; |
4457 | ||
4458 | // IRI represents an absolute path | |
4459 | 105 | if(rel.pathname.indexOf('/') === 0) { |
4460 | 16 | path = rel.pathname; |
4461 | } | |
4462 | else { | |
4463 | 89 | path = base.pathname; |
4464 | ||
4465 | // append relative path to the end of the last directory from base | |
4466 | 89 | if(rel.pathname !== '') { |
4467 | 69 | path = path.substr(0, path.lastIndexOf('/') + 1); |
4468 | 69 | if(path.length > 0 && path.substr(-1) !== '/') { |
4469 | 0 | path += '/'; |
4470 | } | |
4471 | 69 | path += rel.pathname; |
4472 | } | |
4473 | } | |
4474 | ||
4475 | // remove slashes and dots in path | |
4476 | 105 | path = _removeDotSegments(path, hierPart !== ''); |
4477 | ||
4478 | // add query and hash | |
4479 | 105 | if(rel.query) { |
4480 | 6 | path += '?' + rel.query; |
4481 | } | |
4482 | 105 | if(rel.hash) { |
4483 | 13 | path += rel.hash; |
4484 | } | |
4485 | ||
4486 | 105 | var rval = hierPart + path; |
4487 | ||
4488 | 105 | if(rval === '') { |
4489 | 0 | rval = './'; |
4490 | } | |
4491 | ||
4492 | 105 | return rval; |
4493 | } | |
4494 | ||
4495 | /** | |
4496 | * Removes a base IRI from the given absolute IRI. | |
4497 | * | |
4498 | * @param base the base IRI. | |
4499 | * @param iri the absolute IRI. | |
4500 | * | |
4501 | * @return the relative IRI if relative to base, otherwise the absolute IRI. | |
4502 | */ | |
4503 | 2 | function _removeBase(base, iri) { |
4504 | 174 | if(_isString(base)) { |
4505 | 0 | base = jsonld.url.parse(base || ''); |
4506 | } | |
4507 | ||
4508 | // establish base root | |
4509 | 174 | var root = ''; |
4510 | 174 | if(base.href !== '') { |
4511 | 174 | root += (base.protocol || '') + '//' + base.authority; |
4512 | } | |
4513 | // support network-path reference with empty base | |
4514 | 0 | else if(iri.indexOf('//')) { |
4515 | 0 | root += '//'; |
4516 | } | |
4517 | ||
4518 | // IRI not relative to base | |
4519 | 174 | if(iri.indexOf(root) !== 0) { |
4520 | 158 | return iri; |
4521 | } | |
4522 | ||
4523 | // remove root from IRI and parse remainder | |
4524 | 16 | var rel = jsonld.url.parse(iri.substr(root.length)); |
4525 | ||
4526 | // remove path segments that match | |
4527 | 16 | var baseSegments = base.normalizedPath.split('/'); |
4528 | 16 | var iriSegments = rel.normalizedPath.split('/'); |
4529 | ||
4530 | 16 | while(baseSegments.length > 0 && iriSegments.length > 0) { |
4531 | 52 | if(baseSegments[0] !== iriSegments[0]) { |
4532 | 14 | break; |
4533 | } | |
4534 | 38 | baseSegments.shift(); |
4535 | 38 | iriSegments.shift(); |
4536 | } | |
4537 | ||
4538 | // use '../' for each non-matching base segment | |
4539 | 16 | var rval = ''; |
4540 | 16 | if(baseSegments.length > 0) { |
4541 | // do not count the last segment if it isn't a path (doesn't end in '/') | |
4542 | 14 | if(base.normalizedPath.substr(-1) !== '/') { |
4543 | 14 | baseSegments.pop(); |
4544 | } | |
4545 | 14 | for(var i = 0; i < baseSegments.length; ++i) { |
4546 | 12 | rval += '../'; |
4547 | } | |
4548 | } | |
4549 | ||
4550 | // prepend remaining segments | |
4551 | 16 | rval += iriSegments.join('/'); |
4552 | ||
4553 | // add query and hash | |
4554 | 16 | if(rel.query) { |
4555 | 1 | rval += '?' + rel.query; |
4556 | } | |
4557 | 16 | if(rel.hash) { |
4558 | 2 | rval += rel.hash; |
4559 | } | |
4560 | ||
4561 | 16 | if(rval === '') { |
4562 | 1 | rval = './'; |
4563 | } | |
4564 | ||
4565 | 16 | return rval; |
4566 | } | |
4567 | ||
4568 | /** | |
4569 | * Gets the initial context. | |
4570 | * | |
4571 | * @param options the options to use. | |
4572 | * base the document base IRI. | |
4573 | * | |
4574 | * @return the initial context. | |
4575 | */ | |
4576 | 2 | function _getInitialContext(options) { |
4577 | 392 | var base = jsonld.url.parse(options.base || ''); |
4578 | 392 | return { |
4579 | '@base': base, | |
4580 | mappings: {}, | |
4581 | inverse: null, | |
4582 | getInverse: _createInverseContext, | |
4583 | clone: _cloneActiveContext | |
4584 | }; | |
4585 | ||
4586 | /** | |
4587 | * Generates an inverse context for use in the compaction algorithm, if | |
4588 | * not already generated for the given active context. | |
4589 | * | |
4590 | * @return the inverse context. | |
4591 | */ | |
4592 | 0 | function _createInverseContext() { |
4593 | 952 | var activeCtx = this; |
4594 | ||
4595 | // lazily create inverse | |
4596 | 952 | if(activeCtx.inverse) { |
4597 | 868 | return activeCtx.inverse; |
4598 | } | |
4599 | 84 | var inverse = activeCtx.inverse = {}; |
4600 | ||
4601 | // handle default language | |
4602 | 84 | var defaultLanguage = activeCtx['@language'] || '@none'; |
4603 | ||
4604 | // create term selections for each mapping in the context, ordered by | |
4605 | // shortest and then lexicographically least | |
4606 | 84 | var mappings = activeCtx.mappings; |
4607 | 84 | var terms = Object.keys(mappings).sort(_compareShortestLeast); |
4608 | 84 | for(var i = 0; i < terms.length; ++i) { |
4609 | 273 | var term = terms[i]; |
4610 | 273 | var mapping = mappings[term]; |
4611 | 273 | if(mapping === null) { |
4612 | 1 | continue; |
4613 | } | |
4614 | ||
4615 | 272 | var container = mapping['@container'] || '@none'; |
4616 | ||
4617 | // iterate over every IRI in the mapping | |
4618 | 272 | var ids = mapping['@id']; |
4619 | 272 | if(!_isArray(ids)) { |
4620 | 272 | ids = [ids]; |
4621 | } | |
4622 | 272 | for(var ii = 0; ii < ids.length; ++ii) { |
4623 | 272 | var iri = ids[ii]; |
4624 | 272 | var entry = inverse[iri]; |
4625 | ||
4626 | // initialize entry | |
4627 | 272 | if(!entry) { |
4628 | 248 | inverse[iri] = entry = {}; |
4629 | } | |
4630 | ||
4631 | // add new entry | |
4632 | 272 | if(!entry[container]) { |
4633 | 254 | entry[container] = { |
4634 | '@language': {}, | |
4635 | '@type': {} | |
4636 | }; | |
4637 | } | |
4638 | 272 | entry = entry[container]; |
4639 | ||
4640 | // term is preferred for values using @reverse | |
4641 | 272 | if(mapping.reverse) { |
4642 | 5 | _addPreferredTerm(mapping, term, entry['@type'], '@reverse'); |
4643 | } | |
4644 | // term is preferred for values using specific type | |
4645 | 267 | else if('@type' in mapping) { |
4646 | 109 | _addPreferredTerm(mapping, term, entry['@type'], mapping['@type']); |
4647 | } | |
4648 | // term is preferred for values using specific language | |
4649 | 158 | else if('@language' in mapping) { |
4650 | 9 | var language = mapping['@language'] || '@null'; |
4651 | 9 | _addPreferredTerm(mapping, term, entry['@language'], language); |
4652 | } | |
4653 | // term is preferred for values w/default language or no type and | |
4654 | // no language | |
4655 | else { | |
4656 | // add an entry for the default language | |
4657 | 149 | _addPreferredTerm(mapping, term, entry['@language'], defaultLanguage); |
4658 | ||
4659 | // add entries for no type and no language | |
4660 | 149 | _addPreferredTerm(mapping, term, entry['@type'], '@none'); |
4661 | 149 | _addPreferredTerm(mapping, term, entry['@language'], '@none'); |
4662 | } | |
4663 | } | |
4664 | } | |
4665 | ||
4666 | 84 | return inverse; |
4667 | } | |
4668 | ||
4669 | /** | |
4670 | * Adds the term for the given entry if not already added. | |
4671 | * | |
4672 | * @param mapping the term mapping. | |
4673 | * @param term the term to add. | |
4674 | * @param entry the inverse context typeOrLanguage entry to add to. | |
4675 | * @param typeOrLanguageValue the key in the entry to add to. | |
4676 | */ | |
4677 | 0 | function _addPreferredTerm(mapping, term, entry, typeOrLanguageValue) { |
4678 | 570 | if(!(typeOrLanguageValue in entry)) { |
4679 | 438 | entry[typeOrLanguageValue] = term; |
4680 | } | |
4681 | } | |
4682 | ||
4683 | /** | |
4684 | * Clones an active context, creating a child active context. | |
4685 | * | |
4686 | * @return a clone (child) of the active context. | |
4687 | */ | |
4688 | 0 | function _cloneActiveContext() { |
4689 | 317 | var child = {}; |
4690 | 317 | child['@base'] = this['@base']; |
4691 | 317 | child.mappings = _clone(this.mappings); |
4692 | 317 | child.clone = this.clone; |
4693 | 317 | child.inverse = null; |
4694 | 317 | child.getInverse = this.getInverse; |
4695 | 317 | if('@language' in this) { |
4696 | 1 | child['@language'] = this['@language']; |
4697 | } | |
4698 | 317 | if('@vocab' in this) { |
4699 | 1 | child['@vocab'] = this['@vocab']; |
4700 | } | |
4701 | 317 | return child; |
4702 | } | |
4703 | } | |
4704 | ||
4705 | /** | |
4706 | * Returns whether or not the given value is a keyword. | |
4707 | * | |
4708 | * @param v the value to check. | |
4709 | * | |
4710 | * @return true if the value is a keyword, false if not. | |
4711 | */ | |
4712 | 2 | function _isKeyword(v) { |
4713 | 18497 | if(!_isString(v)) { |
4714 | 2 | return false; |
4715 | } | |
4716 | 18495 | switch(v) { |
4717 | case '@base': | |
4718 | case '@context': | |
4719 | case '@container': | |
4720 | case '@default': | |
4721 | case '@embed': | |
4722 | case '@explicit': | |
4723 | case '@graph': | |
4724 | case '@id': | |
4725 | case '@index': | |
4726 | case '@language': | |
4727 | case '@list': | |
4728 | case '@omitDefault': | |
4729 | case '@preserve': | |
4730 | case '@reverse': | |
4731 | case '@set': | |
4732 | case '@type': | |
4733 | case '@value': | |
4734 | case '@vocab': | |
4735 | 8418 | return true; |
4736 | } | |
4737 | 10077 | return false; |
4738 | } | |
4739 | ||
4740 | /** | |
4741 | * Returns true if the given value is an Object. | |
4742 | * | |
4743 | * @param v the value to check. | |
4744 | * | |
4745 | * @return true if the value is an Object, false if not. | |
4746 | */ | |
4747 | 2 | function _isObject(v) { |
4748 | 28580 | return (Object.prototype.toString.call(v) === '[object Object]'); |
4749 | } | |
4750 | ||
4751 | /** | |
4752 | * Returns true if the given value is an empty Object. | |
4753 | * | |
4754 | * @param v the value to check. | |
4755 | * | |
4756 | * @return true if the value is an empty Object, false if not. | |
4757 | */ | |
4758 | 2 | function _isEmptyObject(v) { |
4759 | 30 | return _isObject(v) && Object.keys(v).length === 0; |
4760 | } | |
4761 | ||
4762 | /** | |
4763 | * Returns true if the given value is an Array. | |
4764 | * | |
4765 | * @param v the value to check. | |
4766 | * | |
4767 | * @return true if the value is an Array, false if not. | |
4768 | */ | |
4769 | 2 | function _isArray(v) { |
4770 | 37211 | return Array.isArray(v); |
4771 | } | |
4772 | ||
4773 | /** | |
4774 | * Throws an exception if the given value is not a valid @type value. | |
4775 | * | |
4776 | * @param v the value to check. | |
4777 | */ | |
4778 | 2 | function _validateTypeValue(v) { |
4779 | // can be a string or an empty object | |
4780 | 206 | if(_isString(v) || _isEmptyObject(v)) { |
4781 | 177 | return; |
4782 | } | |
4783 | ||
4784 | // must be an array | |
4785 | 29 | var isValid = false; |
4786 | 29 | if(_isArray(v)) { |
4787 | // must contain only strings | |
4788 | 29 | isValid = true; |
4789 | 29 | for(var i in v) { |
4790 | 94 | if(!(_isString(v[i]))) { |
4791 | 0 | isValid = false; |
4792 | 0 | break; |
4793 | } | |
4794 | } | |
4795 | } | |
4796 | ||
4797 | 29 | if(!isValid) { |
4798 | 0 | throw new JsonLdError( |
4799 | 'Invalid JSON-LD syntax; "@type" value must a string, an array of ' + | |
4800 | 'strings, or an empty object.', 'jsonld.SyntaxError', {value: v}); | |
4801 | } | |
4802 | } | |
4803 | ||
4804 | /** | |
4805 | * Returns true if the given value is a String. | |
4806 | * | |
4807 | * @param v the value to check. | |
4808 | * | |
4809 | * @return true if the value is a String, false if not. | |
4810 | */ | |
4811 | 2 | function _isString(v) { |
4812 | 25421 | return (typeof v === 'string' || |
4813 | Object.prototype.toString.call(v) === '[object String]'); | |
4814 | } | |
4815 | ||
4816 | /** | |
4817 | * Returns true if the given value is a Number. | |
4818 | * | |
4819 | * @param v the value to check. | |
4820 | * | |
4821 | * @return true if the value is a Number, false if not. | |
4822 | */ | |
4823 | 2 | function _isNumber(v) { |
4824 | 148 | return (typeof v === 'number' || |
4825 | Object.prototype.toString.call(v) === '[object Number]'); | |
4826 | } | |
4827 | ||
4828 | /** | |
4829 | * Returns true if the given value is a double. | |
4830 | * | |
4831 | * @param v the value to check. | |
4832 | * | |
4833 | * @return true if the value is a double, false if not. | |
4834 | */ | |
4835 | 2 | function _isDouble(v) { |
4836 | 75 | return _isNumber(v) && String(v).indexOf('.') !== -1; |
4837 | } | |
4838 | ||
4839 | /** | |
4840 | * Returns true if the given value is numeric. | |
4841 | * | |
4842 | * @param v the value to check. | |
4843 | * | |
4844 | * @return true if the value is numeric, false if not. | |
4845 | */ | |
4846 | 2 | function _isNumeric(v) { |
4847 | 17 | return !isNaN(parseFloat(v)) && isFinite(v); |
4848 | } | |
4849 | ||
4850 | /** | |
4851 | * Returns true if the given value is a Boolean. | |
4852 | * | |
4853 | * @param v the value to check. | |
4854 | * | |
4855 | * @return true if the value is a Boolean, false if not. | |
4856 | */ | |
4857 | 2 | function _isBoolean(v) { |
4858 | 77 | return (typeof v === 'boolean' || |
4859 | Object.prototype.toString.call(v) === '[object Boolean]'); | |
4860 | } | |
4861 | ||
4862 | /** | |
4863 | * Returns true if the given value is undefined. | |
4864 | * | |
4865 | * @param v the value to check. | |
4866 | * | |
4867 | * @return true if the value is undefined, false if not. | |
4868 | */ | |
4869 | 2 | function _isUndefined(v) { |
4870 | 5461 | return (typeof v === 'undefined'); |
4871 | } | |
4872 | ||
4873 | /** | |
4874 | * Returns true if the given value is a subject with properties. | |
4875 | * | |
4876 | * @param v the value to check. | |
4877 | * | |
4878 | * @return true if the value is a subject with properties, false if not. | |
4879 | */ | |
4880 | 2 | function _isSubject(v) { |
4881 | // Note: A value is a subject if all of these hold true: | |
4882 | // 1. It is an Object. | |
4883 | // 2. It is not a @value, @set, or @list. | |
4884 | // 3. It has more than 1 key OR any existing key is not @id. | |
4885 | 762 | var rval = false; |
4886 | 762 | if(_isObject(v) && |
4887 | !(('@value' in v) || ('@set' in v) || ('@list' in v))) { | |
4888 | 358 | var keyCount = Object.keys(v).length; |
4889 | 358 | rval = (keyCount > 1 || !('@id' in v)); |
4890 | } | |
4891 | 762 | return rval; |
4892 | } | |
4893 | ||
4894 | /** | |
4895 | * Returns true if the given value is a subject reference. | |
4896 | * | |
4897 | * @param v the value to check. | |
4898 | * | |
4899 | * @return true if the value is a subject reference, false if not. | |
4900 | */ | |
4901 | 2 | function _isSubjectReference(v) { |
4902 | // Note: A value is a subject reference if all of these hold true: | |
4903 | // 1. It is an Object. | |
4904 | // 2. It has a single key: @id. | |
4905 | 1256 | return (_isObject(v) && Object.keys(v).length === 1 && ('@id' in v)); |
4906 | } | |
4907 | ||
4908 | /** | |
4909 | * Returns true if the given value is a @value. | |
4910 | * | |
4911 | * @param v the value to check. | |
4912 | * | |
4913 | * @return true if the value is a @value, false if not. | |
4914 | */ | |
4915 | 2 | function _isValue(v) { |
4916 | // Note: A value is a @value if all of these hold true: | |
4917 | // 1. It is an Object. | |
4918 | // 2. It has the @value property. | |
4919 | 3581 | return _isObject(v) && ('@value' in v); |
4920 | } | |
4921 | ||
4922 | /** | |
4923 | * Returns true if the given value is a @list. | |
4924 | * | |
4925 | * @param v the value to check. | |
4926 | * | |
4927 | * @return true if the value is a @list, false if not. | |
4928 | */ | |
4929 | 2 | function _isList(v) { |
4930 | // Note: A value is a @list if all of these hold true: | |
4931 | // 1. It is an Object. | |
4932 | // 2. It has the @list property. | |
4933 | 4257 | return _isObject(v) && ('@list' in v); |
4934 | } | |
4935 | ||
4936 | /** | |
4937 | * Returns true if the given value is a blank node. | |
4938 | * | |
4939 | * @param v the value to check. | |
4940 | * | |
4941 | * @return true if the value is a blank node, false if not. | |
4942 | */ | |
4943 | 2 | function _isBlankNode(v) { |
4944 | // Note: A value is a blank node if all of these hold true: | |
4945 | // 1. It is an Object. | |
4946 | // 2. If it has an @id key its value begins with '_:'. | |
4947 | // 3. It has no keys OR is not a @value, @set, or @list. | |
4948 | 690 | var rval = false; |
4949 | 690 | if(_isObject(v)) { |
4950 | 690 | if('@id' in v) { |
4951 | 652 | rval = (v['@id'].indexOf('_:') === 0); |
4952 | } | |
4953 | else { | |
4954 | 38 | rval = (Object.keys(v).length === 0 || |
4955 | !(('@value' in v) || ('@set' in v) || ('@list' in v))); | |
4956 | } | |
4957 | } | |
4958 | 690 | return rval; |
4959 | } | |
4960 | ||
4961 | /** | |
4962 | * Returns true if the given value is an absolute IRI, false if not. | |
4963 | * | |
4964 | * @param v the value to check. | |
4965 | * | |
4966 | * @return true if the value is an absolute IRI, false if not. | |
4967 | */ | |
4968 | 2 | function _isAbsoluteIri(v) { |
4969 | 2290 | return _isString(v) && v.indexOf(':') !== -1; |
4970 | } | |
4971 | ||
4972 | /** | |
4973 | * Clones an object, array, or string/number. | |
4974 | * | |
4975 | * @param value the value to clone. | |
4976 | * | |
4977 | * @return the cloned value. | |
4978 | */ | |
4979 | 2 | function _clone(value) { |
4980 | 67273 | if(value && typeof value === 'object') { |
4981 | 12365 | var rval = _isArray(value) ? [] : {}; |
4982 | 12365 | for(var i in value) { |
4983 | 57168 | rval[i] = _clone(value[i]); |
4984 | } | |
4985 | 12365 | return rval; |
4986 | } | |
4987 | 54908 | return value; |
4988 | } | |
4989 | ||
4990 | /** | |
4991 | * Finds all @context URLs in the given JSON-LD input. | |
4992 | * | |
4993 | * @param input the JSON-LD input. | |
4994 | * @param urls a map of URLs (url => false/@contexts). | |
4995 | * @param replace true to replace the URLs in the given input with the | |
4996 | * @contexts from the urls map, false not to. | |
4997 | * @param base the base IRI to use to resolve relative IRIs. | |
4998 | * | |
4999 | * @return true if new URLs to retrieve were found, false if not. | |
5000 | */ | |
5001 | 2 | function _findContextUrls(input, urls, replace, base) { |
5002 | 7830 | var count = Object.keys(urls).length; |
5003 | 7830 | if(_isArray(input)) { |
5004 | 1058 | for(var i in input) { |
5005 | 2406 | _findContextUrls(input[i], urls, replace, base); |
5006 | } | |
5007 | 1058 | return (count < Object.keys(urls).length); |
5008 | } | |
5009 | 6772 | else if(_isObject(input)) { |
5010 | 2460 | for(var key in input) { |
5011 | 5298 | if(key !== '@context') { |
5012 | 4646 | _findContextUrls(input[key], urls, replace, base); |
5013 | 4646 | continue; |
5014 | } | |
5015 | ||
5016 | // get @context | |
5017 | 652 | var ctx = input[key]; |
5018 | ||
5019 | // array @context | |
5020 | 652 | if(_isArray(ctx)) { |
5021 | 8 | var length = ctx.length; |
5022 | 8 | for(var i = 0; i < length; ++i) { |
5023 | 16 | var _ctx = ctx[i]; |
5024 | 16 | if(_isString(_ctx)) { |
5025 | 0 | _ctx = _prependBase(base, _ctx); |
5026 | // replace w/@context if requested | |
5027 | 0 | if(replace) { |
5028 | 0 | _ctx = urls[_ctx]; |
5029 | 0 | if(_isArray(_ctx)) { |
5030 | // add flattened context | |
5031 | 0 | Array.prototype.splice.apply(ctx, [i, 1].concat(_ctx)); |
5032 | 0 | i += _ctx.length; |
5033 | 0 | length += _ctx.length; |
5034 | } | |
5035 | else { | |
5036 | 0 | ctx[i] = _ctx; |
5037 | } | |
5038 | } | |
5039 | // @context URL found | |
5040 | 0 | else if(!(_ctx in urls)) { |
5041 | 0 | urls[_ctx] = false; |
5042 | } | |
5043 | } | |
5044 | } | |
5045 | } | |
5046 | // string @context | |
5047 | 644 | else if(_isString(ctx)) { |
5048 | 0 | ctx = _prependBase(base, ctx); |
5049 | // replace w/@context if requested | |
5050 | 0 | if(replace) { |
5051 | 0 | input[key] = urls[ctx]; |
5052 | } | |
5053 | // @context URL found | |
5054 | 0 | else if(!(ctx in urls)) { |
5055 | 0 | urls[ctx] = false; |
5056 | } | |
5057 | } | |
5058 | } | |
5059 | 2460 | return (count < Object.keys(urls).length); |
5060 | } | |
5061 | 4312 | return false; |
5062 | } | |
5063 | ||
5064 | /** | |
5065 | * Retrieves external @context URLs using the given context loader. Every | |
5066 | * instance of @context in the input that refers to a URL will be replaced | |
5067 | * with the JSON @context found at that URL. | |
5068 | * | |
5069 | * @param input the JSON-LD input with possible contexts. | |
5070 | * @param options the options to use: | |
5071 | * loadContext(url, callback(err, url, result)) the context loader. | |
5072 | * @param callback(err, input) called once the operation completes. | |
5073 | */ | |
5074 | 2 | function _retrieveContextUrls(input, options, callback) { |
5075 | // if any error occurs during URL resolution, quit | |
5076 | 389 | var error = null; |
5077 | 389 | var regex = /(http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/; |
5078 | ||
5079 | // recursive context loader | |
5080 | 389 | var loadContext = options.loadContext; |
5081 | 389 | var retrieve = function(input, cycles, loadContext, base, callback) { |
5082 | 389 | if(Object.keys(cycles).length > MAX_CONTEXT_URLS) { |
5083 | 0 | error = new JsonLdError( |
5084 | 'Maximum number of @context URLs exceeded.', | |
5085 | 'jsonld.ContextUrlError', {max: MAX_CONTEXT_URLS}); | |
5086 | 0 | return callback(error); |
5087 | } | |
5088 | ||
5089 | // for tracking the URLs to retrieve | |
5090 | 389 | var urls = {}; |
5091 | ||
5092 | // finished will be called once the URL queue is empty | |
5093 | 389 | var finished = function() { |
5094 | // replace all URLs in the input | |
5095 | 389 | _findContextUrls(input, urls, true, base); |
5096 | 389 | callback(null, input); |
5097 | }; | |
5098 | ||
5099 | // find all URLs in the given input | |
5100 | 389 | if(!_findContextUrls(input, urls, false, base)) { |
5101 | // no new URLs in input | |
5102 | 389 | finished(); |
5103 | } | |
5104 | ||
5105 | // queue all unretrieved URLs | |
5106 | 389 | var queue = []; |
5107 | 389 | for(var url in urls) { |
5108 | 0 | if(urls[url] === false) { |
5109 | // validate URL | |
5110 | 0 | if(!regex.test(url)) { |
5111 | 0 | error = new JsonLdError( |
5112 | 'Malformed URL.', 'jsonld.InvalidUrl', {url: url}); | |
5113 | 0 | return callback(error); |
5114 | } | |
5115 | 0 | queue.push(url); |
5116 | } | |
5117 | } | |
5118 | ||
5119 | // retrieve URLs in queue | |
5120 | 389 | var count = queue.length; |
5121 | 389 | for(var i in queue) { |
5122 | 0 | (function(url) { |
5123 | // check for context URL cycle | |
5124 | 0 | if(url in cycles) { |
5125 | 0 | error = new JsonLdError( |
5126 | 'Cyclical @context URLs detected.', | |
5127 | 'jsonld.ContextUrlError', {url: url}); | |
5128 | 0 | return callback(error); |
5129 | } | |
5130 | 0 | var _cycles = _clone(cycles); |
5131 | 0 | _cycles[url] = true; |
5132 | ||
5133 | 0 | loadContext(url, function(err, finalUrl, ctx) { |
5134 | // short-circuit if there was an error with another URL | |
5135 | 0 | if(error) { |
5136 | 0 | return; |
5137 | } | |
5138 | ||
5139 | // parse string context as JSON | |
5140 | 0 | if(!err && _isString(ctx)) { |
5141 | 0 | try { |
5142 | 0 | ctx = JSON.parse(ctx); |
5143 | } | |
5144 | catch(ex) { | |
5145 | 0 | err = ex; |
5146 | } | |
5147 | } | |
5148 | ||
5149 | // ensure ctx is an object | |
5150 | 0 | if(err) { |
5151 | 0 | err = new JsonLdError( |
5152 | 'Derefencing a URL did not result in a valid JSON-LD object. ' + | |
5153 | 'Possible causes are an inaccessible URL perhaps due to ' + | |
5154 | 'a same-origin policy (ensure the server uses CORS if you are ' + | |
5155 | 'using client-side JavaScript), too many redirects, or a ' + | |
5156 | 'non-JSON response.', | |
5157 | 'jsonld.InvalidUrl', {url: url, cause: err}); | |
5158 | } | |
5159 | 0 | else if(!_isObject(ctx)) { |
5160 | 0 | err = new JsonLdError( |
5161 | 'Derefencing a URL did not result in a JSON object. The ' + | |
5162 | 'response was valid JSON, but it was not a JSON object.', | |
5163 | 'jsonld.InvalidUrl', {url: url, cause: err}); | |
5164 | } | |
5165 | 0 | if(err) { |
5166 | 0 | error = err; |
5167 | 0 | return callback(error); |
5168 | } | |
5169 | ||
5170 | // use empty context if no @context key is present | |
5171 | 0 | if(!('@context' in ctx)) { |
5172 | 0 | ctx = {'@context': {}}; |
5173 | } | |
5174 | ||
5175 | // recurse | |
5176 | 0 | retrieve(ctx, _cycles, loadContext, url, function(err, ctx) { |
5177 | 0 | if(err) { |
5178 | 0 | return callback(err); |
5179 | } | |
5180 | 0 | urls[url] = ctx['@context']; |
5181 | 0 | count -= 1; |
5182 | 0 | if(count === 0) { |
5183 | 0 | finished(); |
5184 | } | |
5185 | }); | |
5186 | }); | |
5187 | }(queue[i])); | |
5188 | } | |
5189 | }; | |
5190 | 389 | retrieve(input, {}, loadContext, options.base, callback); |
5191 | } | |
5192 | ||
5193 | // define js 1.8.5 Object.keys method if not present | |
5194 | 2 | if(!Object.keys) { |
5195 | 0 | Object.keys = function(o) { |
5196 | 0 | if(o !== Object(o)) { |
5197 | 0 | throw new TypeError('Object.keys called on non-object'); |
5198 | } | |
5199 | 0 | var rval = []; |
5200 | 0 | for(var p in o) { |
5201 | 0 | if(Object.prototype.hasOwnProperty.call(o, p)) { |
5202 | 0 | rval.push(p); |
5203 | } | |
5204 | } | |
5205 | 0 | return rval; |
5206 | }; | |
5207 | } | |
5208 | ||
5209 | /** | |
5210 | * Parses RDF in the form of N-Quads. | |
5211 | * | |
5212 | * @param input the N-Quads input to parse. | |
5213 | * | |
5214 | * @return an RDF dataset. | |
5215 | */ | |
5216 | 2 | function _parseNQuads(input) { |
5217 | // define partial regexes | |
5218 | 7 | var iri = '(?:<([^:]+:[^>]*)>)'; |
5219 | 7 | var bnode = '(_:(?:[A-Za-z][A-Za-z0-9]*))'; |
5220 | 7 | var plain = '"([^"\\\\]*(?:\\\\.[^"\\\\]*)*)"'; |
5221 | 7 | var datatype = '(?:\\^\\^' + iri + ')'; |
5222 | 7 | var language = '(?:@([a-z]+(?:-[a-z0-9]+)*))'; |
5223 | 7 | var literal = '(?:' + plain + '(?:' + datatype + '|' + language + ')?)'; |
5224 | 7 | var ws = '[ \\t]+'; |
5225 | 7 | var wso = '[ \\t]*'; |
5226 | 7 | var eoln = /(?:\r\n)|(?:\n)|(?:\r)/g; |
5227 | 7 | var empty = new RegExp('^' + wso + '$'); |
5228 | ||
5229 | // define quad part regexes | |
5230 | 7 | var subject = '(?:' + iri + '|' + bnode + ')' + ws; |
5231 | 7 | var property = iri + ws; |
5232 | 7 | var object = '(?:' + iri + '|' + bnode + '|' + literal + ')' + wso; |
5233 | 7 | var graphName = '(?:\\.|(?:(?:' + iri + '|' + bnode + ')' + wso + '\\.))'; |
5234 | ||
5235 | // full quad regex | |
5236 | 7 | var quad = new RegExp( |
5237 | '^' + wso + subject + property + object + graphName + wso + '$'); | |
5238 | ||
5239 | // build RDF dataset | |
5240 | 7 | var dataset = {}; |
5241 | ||
5242 | // split N-Quad input into lines | |
5243 | 7 | var lines = input.split(eoln); |
5244 | 7 | var lineNumber = 0; |
5245 | 7 | for(var li = 0; li < lines.length; ++li) { |
5246 | 61 | var line = lines[li]; |
5247 | 61 | lineNumber++; |
5248 | ||
5249 | // skip empty lines | |
5250 | 61 | if(empty.test(line)) { |
5251 | 7 | continue; |
5252 | } | |
5253 | ||
5254 | // parse quad | |
5255 | 54 | var match = line.match(quad); |
5256 | 54 | if(match === null) { |
5257 | 0 | throw new JsonLdError( |
5258 | 'Error while parsing N-Quads; invalid quad.', | |
5259 | 'jsonld.ParseError', {line: lineNumber}); | |
5260 | } | |
5261 | ||
5262 | // create RDF triple | |
5263 | 54 | var triple = {}; |
5264 | ||
5265 | // get subject | |
5266 | 54 | if(!_isUndefined(match[1])) { |
5267 | 35 | triple.subject = {type: 'IRI', value: match[1]}; |
5268 | } | |
5269 | else { | |
5270 | 19 | triple.subject = {type: 'blank node', value: match[2]}; |
5271 | } | |
5272 | ||
5273 | // get predicate | |
5274 | 54 | triple.predicate = {type: 'IRI', value: match[3]}; |
5275 | ||
5276 | // get object | |
5277 | 54 | if(!_isUndefined(match[4])) { |
5278 | 24 | triple.object = {type: 'IRI', value: match[4]}; |
5279 | } | |
5280 | 30 | else if(!_isUndefined(match[5])) { |
5281 | 10 | triple.object = {type: 'blank node', value: match[5]}; |
5282 | } | |
5283 | else { | |
5284 | 20 | triple.object = {type: 'literal'}; |
5285 | 20 | if(!_isUndefined(match[7])) { |
5286 | 7 | triple.object.datatype = match[7]; |
5287 | } | |
5288 | 13 | else if(!_isUndefined(match[8])) { |
5289 | 1 | triple.object.datatype = RDF_LANGSTRING; |
5290 | 1 | triple.object.language = match[8]; |
5291 | } | |
5292 | else { | |
5293 | 12 | triple.object.datatype = XSD_STRING; |
5294 | } | |
5295 | 20 | var unescaped = match[6] |
5296 | .replace(/\\"/g, '"') | |
5297 | .replace(/\\t/g, '\t') | |
5298 | .replace(/\\n/g, '\n') | |
5299 | .replace(/\\r/g, '\r') | |
5300 | .replace(/\\\\/g, '\\'); | |
5301 | 20 | triple.object.value = unescaped; |
5302 | } | |
5303 | ||
5304 | // get graph name ('@default' is used for the default graph) | |
5305 | 54 | var name = '@default'; |
5306 | 54 | if(!_isUndefined(match[9])) { |
5307 | 24 | name = match[9]; |
5308 | } | |
5309 | 30 | else if(!_isUndefined(match[10])) { |
5310 | 0 | name = match[10]; |
5311 | } | |
5312 | ||
5313 | // initialize graph in dataset | |
5314 | 54 | if(!(name in dataset)) { |
5315 | 11 | dataset[name] = [triple]; |
5316 | } | |
5317 | // add triple if unique to its graph | |
5318 | else { | |
5319 | 43 | var unique = true; |
5320 | 43 | var triples = dataset[name]; |
5321 | 43 | for(var ti = 0; unique && ti < triples.length; ++ti) { |
5322 | 146 | if(_compareRDFTriples(triples[ti], triple)) { |
5323 | 0 | unique = false; |
5324 | } | |
5325 | } | |
5326 | 43 | if(unique) { |
5327 | 43 | triples.push(triple); |
5328 | } | |
5329 | } | |
5330 | } | |
5331 | ||
5332 | 7 | return dataset; |
5333 | } | |
5334 | ||
5335 | // register the N-Quads RDF parser | |
5336 | 2 | jsonld.registerRDFParser('application/nquads', _parseNQuads); |
5337 | ||
5338 | /** | |
5339 | * Converts an RDF dataset to N-Quads. | |
5340 | * | |
5341 | * @param dataset the RDF dataset to convert. | |
5342 | * | |
5343 | * @return the N-Quads string. | |
5344 | */ | |
5345 | 2 | function _toNQuads(dataset) { |
5346 | 30 | var quads = []; |
5347 | 30 | for(var graphName in dataset) { |
5348 | 36 | var triples = dataset[graphName]; |
5349 | 36 | for(var ti = 0; ti < triples.length; ++ti) { |
5350 | 66 | var triple = triples[ti]; |
5351 | 66 | if(graphName === '@default') { |
5352 | 30 | graphName = null; |
5353 | } | |
5354 | 66 | quads.push(_toNQuad(triple, graphName)); |
5355 | } | |
5356 | } | |
5357 | 30 | quads.sort(); |
5358 | 30 | return quads.join(''); |
5359 | } | |
5360 | ||
5361 | /** | |
5362 | * Converts an RDF triple and graph name to an N-Quad string (a single quad). | |
5363 | * | |
5364 | * @param triple the RDF triple to convert. | |
5365 | * @param graphName the name of the graph containing the triple, null for | |
5366 | * the default graph. | |
5367 | * @param bnode the bnode the quad is mapped to (optional, for use | |
5368 | * during normalization only). | |
5369 | * | |
5370 | * @return the N-Quad string. | |
5371 | */ | |
5372 | 2 | function _toNQuad(triple, graphName, bnode) { |
5373 | 863 | var s = triple.subject; |
5374 | 863 | var p = triple.predicate; |
5375 | 863 | var o = triple.object; |
5376 | 863 | var g = graphName; |
5377 | ||
5378 | 863 | var quad = ''; |
5379 | ||
5380 | // subject is an IRI or bnode | |
5381 | 863 | if(s.type === 'IRI') { |
5382 | 107 | quad += '<' + s.value + '>'; |
5383 | } | |
5384 | // normalization mode | |
5385 | 756 | else if(bnode) { |
5386 | 480 | quad += (s.value === bnode) ? '_:a' : '_:z'; |
5387 | } | |
5388 | // normal mode | |
5389 | else { | |
5390 | 276 | quad += s.value; |
5391 | } | |
5392 | ||
5393 | // predicate is always an IRI | |
5394 | 863 | quad += ' <' + p.value + '> '; |
5395 | ||
5396 | // object is IRI, bnode, or literal | |
5397 | 863 | if(o.type === 'IRI') { |
5398 | 71 | quad += '<' + o.value + '>'; |
5399 | } | |
5400 | 792 | else if(o.type === 'blank node') { |
5401 | // normalization mode | |
5402 | 691 | if(bnode) { |
5403 | 453 | quad += (o.value === bnode) ? '_:a' : '_:z'; |
5404 | } | |
5405 | // normal mode | |
5406 | else { | |
5407 | 238 | quad += o.value; |
5408 | } | |
5409 | } | |
5410 | else { | |
5411 | 101 | var escaped = o.value |
5412 | .replace(/\\/g, '\\\\') | |
5413 | .replace(/\t/g, '\\t') | |
5414 | .replace(/\n/g, '\\n') | |
5415 | .replace(/\r/g, '\\r') | |
5416 | .replace(/\"/g, '\\"'); | |
5417 | 101 | quad += '"' + escaped + '"'; |
5418 | 101 | if(o.datatype === RDF_LANGSTRING) { |
5419 | 3 | quad += '@' + o.language; |
5420 | } | |
5421 | 98 | else if(o.datatype !== XSD_STRING) { |
5422 | 16 | quad += '^^<' + o.datatype + '>'; |
5423 | } | |
5424 | } | |
5425 | ||
5426 | // graph | |
5427 | 863 | if(g !== null) { |
5428 | 18 | if(g.indexOf('_:') !== 0) { |
5429 | 12 | quad += ' <' + g + '>'; |
5430 | } | |
5431 | 6 | else if(bnode) { |
5432 | 4 | quad += ' _:g'; |
5433 | } | |
5434 | else { | |
5435 | 2 | quad += ' ' + g; |
5436 | } | |
5437 | } | |
5438 | ||
5439 | 863 | quad += ' .\n'; |
5440 | 863 | return quad; |
5441 | } | |
5442 | ||
5443 | /** | |
5444 | * Parses the RDF dataset found via the data object from the RDFa API. | |
5445 | * | |
5446 | * @param data the RDFa API data object. | |
5447 | * | |
5448 | * @return the RDF dataset. | |
5449 | */ | |
5450 | 2 | function _parseRdfaApiData(data) { |
5451 | 0 | var dataset = {}; |
5452 | 0 | dataset['@default'] = []; |
5453 | ||
5454 | 0 | var subjects = data.getSubjects(); |
5455 | 0 | for(var si = 0; si < subjects.length; ++si) { |
5456 | 0 | var subject = subjects[si]; |
5457 | 0 | if(subject === null) { |
5458 | 0 | continue; |
5459 | } | |
5460 | ||
5461 | // get all related triples | |
5462 | 0 | var triples = data.getSubjectTriples(subject); |
5463 | 0 | if(triples === null) { |
5464 | 0 | continue; |
5465 | } | |
5466 | 0 | var predicates = triples.predicates; |
5467 | 0 | for(var predicate in predicates) { |
5468 | // iterate over objects | |
5469 | 0 | var objects = predicates[predicate].objects; |
5470 | 0 | for(var oi = 0; oi < objects.length; ++oi) { |
5471 | 0 | var object = objects[oi]; |
5472 | ||
5473 | // create RDF triple | |
5474 | 0 | var triple = {}; |
5475 | ||
5476 | // add subject | |
5477 | 0 | if(subject.indexOf('_:') === 0) { |
5478 | 0 | triple.subject = {type: 'blank node', value: subject}; |
5479 | } | |
5480 | else { | |
5481 | 0 | triple.subject = {type: 'IRI', value: subject}; |
5482 | } | |
5483 | ||
5484 | // add predicate | |
5485 | 0 | triple.predicate = {type: 'IRI', value: predicate}; |
5486 | ||
5487 | // serialize XML literal | |
5488 | 0 | var value = object.value; |
5489 | 0 | if(object.type === RDF_XML_LITERAL) { |
5490 | // initialize XMLSerializer | |
5491 | 0 | if(!XMLSerializer) { |
5492 | 0 | _defineXMLSerializer(); |
5493 | } | |
5494 | 0 | var serializer = new XMLSerializer(); |
5495 | 0 | value = ''; |
5496 | 0 | for(var x = 0; x < object.value.length; x++) { |
5497 | 0 | if(object.value[x].nodeType === Node.ELEMENT_NODE) { |
5498 | 0 | value += serializer.serializeToString(object.value[x]); |
5499 | } | |
5500 | 0 | else if(object.value[x].nodeType === Node.TEXT_NODE) { |
5501 | 0 | value += object.value[x].nodeValue; |
5502 | } | |
5503 | } | |
5504 | } | |
5505 | ||
5506 | // add object | |
5507 | 0 | triple.object = {}; |
5508 | ||
5509 | // object is an IRI | |
5510 | 0 | if(object.type === RDF_OBJECT) { |
5511 | 0 | if(object.value.indexOf('_:') === 0) { |
5512 | 0 | triple.object.type = 'blank node'; |
5513 | } | |
5514 | else { | |
5515 | 0 | triple.object.type = 'IRI'; |
5516 | } | |
5517 | } | |
5518 | // literal | |
5519 | else { | |
5520 | 0 | triple.object.type = 'literal'; |
5521 | 0 | if(object.type === RDF_PLAIN_LITERAL) { |
5522 | 0 | if(object.language) { |
5523 | 0 | triple.object.datatype = RDF_LANGSTRING; |
5524 | 0 | triple.object.language = object.language; |
5525 | } | |
5526 | else { | |
5527 | 0 | triple.object.datatype = XSD_STRING; |
5528 | } | |
5529 | } | |
5530 | else { | |
5531 | 0 | triple.object.datatype = object.type; |
5532 | } | |
5533 | } | |
5534 | 0 | triple.object.value = value; |
5535 | ||
5536 | // add triple to dataset in default graph | |
5537 | 0 | dataset['@default'].push(triple); |
5538 | } | |
5539 | } | |
5540 | } | |
5541 | ||
5542 | 0 | return dataset; |
5543 | } | |
5544 | ||
5545 | // register the RDFa API RDF parser | |
5546 | 2 | jsonld.registerRDFParser('rdfa-api', _parseRdfaApiData); |
5547 | ||
5548 | /** | |
5549 | * Creates a new UniqueNamer. A UniqueNamer issues unique names, keeping | |
5550 | * track of any previously issued names. | |
5551 | * | |
5552 | * @param prefix the prefix to use ('<prefix><counter>'). | |
5553 | */ | |
5554 | 2 | function UniqueNamer(prefix) { |
5555 | 9366 | this.prefix = prefix; |
5556 | 9366 | this.counter = 0; |
5557 | 9366 | this.existing = {}; |
5558 | 2 | }; |
5559 | ||
5560 | /** | |
5561 | * Copies this UniqueNamer. | |
5562 | * | |
5563 | * @return a copy of this UniqueNamer. | |
5564 | */ | |
5565 | 2 | UniqueNamer.prototype.clone = function() { |
5566 | 8984 | var copy = new UniqueNamer(this.prefix); |
5567 | 8984 | copy.counter = this.counter; |
5568 | 8984 | copy.existing = _clone(this.existing); |
5569 | 8984 | return copy; |
5570 | }; | |
5571 | ||
5572 | /** | |
5573 | * Gets the new name for the given old name, where if no old name is given | |
5574 | * a new name will be generated. | |
5575 | * | |
5576 | * @param [oldName] the old name to get the new name for. | |
5577 | * | |
5578 | * @return the new name. | |
5579 | */ | |
5580 | 2 | UniqueNamer.prototype.getName = function(oldName) { |
5581 | // return existing old name | |
5582 | 21283 | if(oldName && oldName in this.existing) { |
5583 | 19200 | return this.existing[oldName]; |
5584 | } | |
5585 | ||
5586 | // get next name | |
5587 | 2083 | var name = this.prefix + this.counter; |
5588 | 2083 | this.counter += 1; |
5589 | ||
5590 | // save mapping | |
5591 | 2083 | if(oldName) { |
5592 | 2035 | this.existing[oldName] = name; |
5593 | } | |
5594 | ||
5595 | 2083 | return name; |
5596 | }; | |
5597 | ||
5598 | /** | |
5599 | * Returns true if the given oldName has already been assigned a new name. | |
5600 | * | |
5601 | * @param oldName the oldName to check. | |
5602 | * | |
5603 | * @return true if the oldName has been assigned a new name, false if not. | |
5604 | */ | |
5605 | 2 | UniqueNamer.prototype.isNamed = function(oldName) { |
5606 | 38487 | return (oldName in this.existing); |
5607 | }; | |
5608 | ||
5609 | /** | |
5610 | * A Permutator iterates over all possible permutations of the given array | |
5611 | * of elements. | |
5612 | * | |
5613 | * @param list the array of elements to iterate over. | |
5614 | */ | |
5615 | 2 | Permutator = function(list) { |
5616 | // original array | |
5617 | 8336 | this.list = list.sort(); |
5618 | // indicates whether there are more permutations | |
5619 | 8336 | this.done = false; |
5620 | // directional info for permutation algorithm | |
5621 | 8336 | this.left = {}; |
5622 | 8336 | for(var i in list) { |
5623 | 8768 | this.left[list[i]] = true; |
5624 | } | |
5625 | }; | |
5626 | ||
5627 | /** | |
5628 | * Returns true if there is another permutation. | |
5629 | * | |
5630 | * @return true if there is another permutation, false if not. | |
5631 | */ | |
5632 | 2 | Permutator.prototype.hasNext = function() { |
5633 | 8984 | return !this.done; |
5634 | }; | |
5635 | ||
5636 | /** | |
5637 | * Gets the next permutation. Call hasNext() to ensure there is another one | |
5638 | * first. | |
5639 | * | |
5640 | * @return the next permutation. | |
5641 | */ | |
5642 | 2 | Permutator.prototype.next = function() { |
5643 | // copy current permutation | |
5644 | 8984 | var rval = this.list.slice(); |
5645 | ||
5646 | /* Calculate the next permutation using the Steinhaus-Johnson-Trotter | |
5647 | permutation algorithm. */ | |
5648 | ||
5649 | // get largest mobile element k | |
5650 | // (mobile: element is greater than the one it is looking at) | |
5651 | 8984 | var k = null; |
5652 | 8984 | var pos = 0; |
5653 | 8984 | var length = this.list.length; |
5654 | 8984 | for(var i = 0; i < length; ++i) { |
5655 | 10424 | var element = this.list[i]; |
5656 | 10424 | var left = this.left[element]; |
5657 | 10424 | if((k === null || element > k) && |
5658 | ((left && i > 0 && element > this.list[i - 1]) || | |
5659 | (!left && i < (length - 1) && element > this.list[i + 1]))) { | |
5660 | 720 | k = element; |
5661 | 720 | pos = i; |
5662 | } | |
5663 | } | |
5664 | ||
5665 | // no more permutations | |
5666 | 8984 | if(k === null) { |
5667 | 8336 | this.done = true; |
5668 | } | |
5669 | else { | |
5670 | // swap k and the element it is looking at | |
5671 | 648 | var swap = this.left[k] ? pos - 1 : pos + 1; |
5672 | 648 | this.list[pos] = this.list[swap]; |
5673 | 648 | this.list[swap] = k; |
5674 | ||
5675 | // reverse the direction of all elements larger than k | |
5676 | 648 | for(var i = 0; i < length; ++i) { |
5677 | 1656 | if(this.list[i] > k) { |
5678 | 72 | this.left[this.list[i]] = !this.left[this.list[i]]; |
5679 | } | |
5680 | } | |
5681 | } | |
5682 | ||
5683 | 8984 | return rval; |
5684 | }; | |
5685 | ||
5686 | // SHA-1 API | |
5687 | 2 | var sha1 = jsonld.sha1 = {}; |
5688 | ||
5689 | 2 | if(_nodejs) { |
5690 | 2 | var crypto = require('crypto'); |
5691 | 2 | sha1.create = function() { |
5692 | 10475 | var md = crypto.createHash('sha1'); |
5693 | 10475 | return { |
5694 | update: function(data) { | |
5695 | 43467 | md.update(data, 'utf8'); |
5696 | }, | |
5697 | digest: function() { | |
5698 | 10475 | return md.digest('hex'); |
5699 | } | |
5700 | }; | |
5701 | }; | |
5702 | } | |
5703 | else { | |
5704 | 0 | sha1.create = function() { |
5705 | 0 | return new sha1.MessageDigest(); |
5706 | }; | |
5707 | } | |
5708 | ||
5709 | /** | |
5710 | * Hashes the given array of quads and returns its hexadecimal SHA-1 message | |
5711 | * digest. | |
5712 | * | |
5713 | * @param nquads the list of serialized quads to hash. | |
5714 | * | |
5715 | * @return the hexadecimal SHA-1 message digest. | |
5716 | */ | |
5717 | 2 | sha1.hash = function(nquads) { |
5718 | 166 | var md = sha1.create(); |
5719 | 166 | for(var i in nquads) { |
5720 | 491 | md.update(nquads[i]); |
5721 | } | |
5722 | 166 | return md.digest(); |
5723 | }; | |
5724 | ||
5725 | // only define sha1 MessageDigest for non-nodejs | |
5726 | 2 | if(!_nodejs) { |
5727 | ||
5728 | /** | |
5729 | * Creates a simple byte buffer for message digest operations. | |
5730 | */ | |
5731 | 0 | sha1.Buffer = function() { |
5732 | 0 | this.data = ''; |
5733 | 0 | this.read = 0; |
5734 | }; | |
5735 | ||
5736 | /** | |
5737 | * Puts a 32-bit integer into this buffer in big-endian order. | |
5738 | * | |
5739 | * @param i the 32-bit integer. | |
5740 | */ | |
5741 | 0 | sha1.Buffer.prototype.putInt32 = function(i) { |
5742 | 0 | this.data += ( |
5743 | String.fromCharCode(i >> 24 & 0xFF) + | |
5744 | String.fromCharCode(i >> 16 & 0xFF) + | |
5745 | String.fromCharCode(i >> 8 & 0xFF) + | |
5746 | String.fromCharCode(i & 0xFF)); | |
5747 | }; | |
5748 | ||
5749 | /** | |
5750 | * Gets a 32-bit integer from this buffer in big-endian order and | |
5751 | * advances the read pointer by 4. | |
5752 | * | |
5753 | * @return the word. | |
5754 | */ | |
5755 | 0 | sha1.Buffer.prototype.getInt32 = function() { |
5756 | 0 | var rval = ( |
5757 | this.data.charCodeAt(this.read) << 24 ^ | |
5758 | this.data.charCodeAt(this.read + 1) << 16 ^ | |
5759 | this.data.charCodeAt(this.read + 2) << 8 ^ | |
5760 | this.data.charCodeAt(this.read + 3)); | |
5761 | 0 | this.read += 4; |
5762 | 0 | return rval; |
5763 | }; | |
5764 | ||
5765 | /** | |
5766 | * Gets the bytes in this buffer. | |
5767 | * | |
5768 | * @return a string full of UTF-8 encoded characters. | |
5769 | */ | |
5770 | 0 | sha1.Buffer.prototype.bytes = function() { |
5771 | 0 | return this.data.slice(this.read); |
5772 | }; | |
5773 | ||
5774 | /** | |
5775 | * Gets the number of bytes in this buffer. | |
5776 | * | |
5777 | * @return the number of bytes in this buffer. | |
5778 | */ | |
5779 | 0 | sha1.Buffer.prototype.length = function() { |
5780 | 0 | return this.data.length - this.read; |
5781 | }; | |
5782 | ||
5783 | /** | |
5784 | * Compacts this buffer. | |
5785 | */ | |
5786 | 0 | sha1.Buffer.prototype.compact = function() { |
5787 | 0 | this.data = this.data.slice(this.read); |
5788 | 0 | this.read = 0; |
5789 | }; | |
5790 | ||
5791 | /** | |
5792 | * Converts this buffer to a hexadecimal string. | |
5793 | * | |
5794 | * @return a hexadecimal string. | |
5795 | */ | |
5796 | 0 | sha1.Buffer.prototype.toHex = function() { |
5797 | 0 | var rval = ''; |
5798 | 0 | for(var i = this.read; i < this.data.length; ++i) { |
5799 | 0 | var b = this.data.charCodeAt(i); |
5800 | 0 | if(b < 16) { |
5801 | 0 | rval += '0'; |
5802 | } | |
5803 | 0 | rval += b.toString(16); |
5804 | } | |
5805 | 0 | return rval; |
5806 | }; | |
5807 | ||
5808 | /** | |
5809 | * Creates a SHA-1 message digest object. | |
5810 | * | |
5811 | * @return a message digest object. | |
5812 | */ | |
5813 | 0 | sha1.MessageDigest = function() { |
5814 | // do initialization as necessary | |
5815 | 0 | if(!_sha1.initialized) { |
5816 | 0 | _sha1.init(); |
5817 | } | |
5818 | ||
5819 | 0 | this.blockLength = 64; |
5820 | 0 | this.digestLength = 20; |
5821 | // length of message so far (does not including padding) | |
5822 | 0 | this.messageLength = 0; |
5823 | ||
5824 | // input buffer | |
5825 | 0 | this.input = new sha1.Buffer(); |
5826 | ||
5827 | // for storing words in the SHA-1 algorithm | |
5828 | 0 | this.words = new Array(80); |
5829 | ||
5830 | // SHA-1 state contains five 32-bit integers | |
5831 | 0 | this.state = { |
5832 | h0: 0x67452301, | |
5833 | h1: 0xEFCDAB89, | |
5834 | h2: 0x98BADCFE, | |
5835 | h3: 0x10325476, | |
5836 | h4: 0xC3D2E1F0 | |
5837 | }; | |
5838 | }; | |
5839 | ||
5840 | /** | |
5841 | * Updates the digest with the given string input. | |
5842 | * | |
5843 | * @param msg the message input to update with. | |
5844 | */ | |
5845 | 0 | sha1.MessageDigest.prototype.update = function(msg) { |
5846 | // UTF-8 encode message | |
5847 | 0 | msg = unescape(encodeURIComponent(msg)); |
5848 | ||
5849 | // update message length and input buffer | |
5850 | 0 | this.messageLength += msg.length; |
5851 | 0 | this.input.data += msg; |
5852 | ||
5853 | // process input | |
5854 | 0 | _sha1.update(this.state, this.words, this.input); |
5855 | ||
5856 | // compact input buffer every 2K or if empty | |
5857 | 0 | if(this.input.read > 2048 || this.input.length() === 0) { |
5858 | 0 | this.input.compact(); |
5859 | } | |
5860 | }; | |
5861 | ||
5862 | /** | |
5863 | * Produces the digest. | |
5864 | * | |
5865 | * @return the digest as a hexadecimal string. | |
5866 | */ | |
5867 | 0 | sha1.MessageDigest.prototype.digest = function() { |
5868 | /* Determine the number of bytes that must be added to the message | |
5869 | to ensure its length is congruent to 448 mod 512. In other words, | |
5870 | a 64-bit integer that gives the length of the message will be | |
5871 | appended to the message and whatever the length of the message is | |
5872 | plus 64 bits must be a multiple of 512. So the length of the | |
5873 | message must be congruent to 448 mod 512 because 512 - 64 = 448. | |
5874 | ||
5875 | In order to fill up the message length it must be filled with | |
5876 | padding that begins with 1 bit followed by all 0 bits. Padding | |
5877 | must *always* be present, so if the message length is already | |
5878 | congruent to 448 mod 512, then 512 padding bits must be added. */ | |
5879 | ||
5880 | // 512 bits == 64 bytes, 448 bits == 56 bytes, 64 bits = 8 bytes | |
5881 | // _padding starts with 1 byte with first bit is set in it which | |
5882 | // is byte value 128, then there may be up to 63 other pad bytes | |
5883 | 0 | var len = this.messageLength; |
5884 | 0 | var padBytes = new sha1.Buffer(); |
5885 | 0 | padBytes.data += this.input.bytes(); |
5886 | 0 | padBytes.data += _sha1.padding.substr(0, 64 - ((len + 8) % 64)); |
5887 | ||
5888 | /* Now append length of the message. The length is appended in bits | |
5889 | as a 64-bit number in big-endian order. Since we store the length | |
5890 | in bytes, we must multiply it by 8 (or left shift by 3). So here | |
5891 | store the high 3 bits in the low end of the first 32-bits of the | |
5892 | 64-bit number and the lower 5 bits in the high end of the second | |
5893 | 32-bits. */ | |
5894 | 0 | padBytes.putInt32((len >>> 29) & 0xFF); |
5895 | 0 | padBytes.putInt32((len << 3) & 0xFFFFFFFF); |
5896 | 0 | _sha1.update(this.state, this.words, padBytes); |
5897 | 0 | var rval = new sha1.Buffer(); |
5898 | 0 | rval.putInt32(this.state.h0); |
5899 | 0 | rval.putInt32(this.state.h1); |
5900 | 0 | rval.putInt32(this.state.h2); |
5901 | 0 | rval.putInt32(this.state.h3); |
5902 | 0 | rval.putInt32(this.state.h4); |
5903 | 0 | return rval.toHex(); |
5904 | }; | |
5905 | ||
5906 | // private SHA-1 data | |
5907 | 0 | var _sha1 = { |
5908 | padding: null, | |
5909 | initialized: false | |
5910 | }; | |
5911 | ||
5912 | /** | |
5913 | * Initializes the constant tables. | |
5914 | */ | |
5915 | 0 | _sha1.init = function() { |
5916 | // create padding | |
5917 | 0 | _sha1.padding = String.fromCharCode(128); |
5918 | 0 | var c = String.fromCharCode(0x00); |
5919 | 0 | var n = 64; |
5920 | 0 | while(n > 0) { |
5921 | 0 | if(n & 1) { |
5922 | 0 | _sha1.padding += c; |
5923 | } | |
5924 | 0 | n >>>= 1; |
5925 | 0 | if(n > 0) { |
5926 | 0 | c += c; |
5927 | } | |
5928 | } | |
5929 | ||
5930 | // now initialized | |
5931 | 0 | _sha1.initialized = true; |
5932 | }; | |
5933 | ||
5934 | /** | |
5935 | * Updates a SHA-1 state with the given byte buffer. | |
5936 | * | |
5937 | * @param s the SHA-1 state to update. | |
5938 | * @param w the array to use to store words. | |
5939 | * @param input the input byte buffer. | |
5940 | */ | |
5941 | 0 | _sha1.update = function(s, w, input) { |
5942 | // consume 512 bit (64 byte) chunks | |
5943 | 0 | var t, a, b, c, d, e, f, i; |
5944 | 0 | var len = input.length(); |
5945 | 0 | while(len >= 64) { |
5946 | // the w array will be populated with sixteen 32-bit big-endian words | |
5947 | // and then extended into 80 32-bit words according to SHA-1 algorithm | |
5948 | // and for 32-79 using Max Locktyukhin's optimization | |
5949 | ||
5950 | // initialize hash value for this chunk | |
5951 | 0 | a = s.h0; |
5952 | 0 | b = s.h1; |
5953 | 0 | c = s.h2; |
5954 | 0 | d = s.h3; |
5955 | 0 | e = s.h4; |
5956 | ||
5957 | // round 1 | |
5958 | 0 | for(i = 0; i < 16; ++i) { |
5959 | 0 | t = input.getInt32(); |
5960 | 0 | w[i] = t; |
5961 | 0 | f = d ^ (b & (c ^ d)); |
5962 | 0 | t = ((a << 5) | (a >>> 27)) + f + e + 0x5A827999 + t; |
5963 | 0 | e = d; |
5964 | 0 | d = c; |
5965 | 0 | c = (b << 30) | (b >>> 2); |
5966 | 0 | b = a; |
5967 | 0 | a = t; |
5968 | } | |
5969 | 0 | for(; i < 20; ++i) { |
5970 | 0 | t = (w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16]); |
5971 | 0 | t = (t << 1) | (t >>> 31); |
5972 | 0 | w[i] = t; |
5973 | 0 | f = d ^ (b & (c ^ d)); |
5974 | 0 | t = ((a << 5) | (a >>> 27)) + f + e + 0x5A827999 + t; |
5975 | 0 | e = d; |
5976 | 0 | d = c; |
5977 | 0 | c = (b << 30) | (b >>> 2); |
5978 | 0 | b = a; |
5979 | 0 | a = t; |
5980 | } | |
5981 | // round 2 | |
5982 | 0 | for(; i < 32; ++i) { |
5983 | 0 | t = (w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16]); |
5984 | 0 | t = (t << 1) | (t >>> 31); |
5985 | 0 | w[i] = t; |
5986 | 0 | f = b ^ c ^ d; |
5987 | 0 | t = ((a << 5) | (a >>> 27)) + f + e + 0x6ED9EBA1 + t; |
5988 | 0 | e = d; |
5989 | 0 | d = c; |
5990 | 0 | c = (b << 30) | (b >>> 2); |
5991 | 0 | b = a; |
5992 | 0 | a = t; |
5993 | } | |
5994 | 0 | for(; i < 40; ++i) { |
5995 | 0 | t = (w[i - 6] ^ w[i - 16] ^ w[i - 28] ^ w[i - 32]); |
5996 | 0 | t = (t << 2) | (t >>> 30); |
5997 | 0 | w[i] = t; |
5998 | 0 | f = b ^ c ^ d; |
5999 | 0 | t = ((a << 5) | (a >>> 27)) + f + e + 0x6ED9EBA1 + t; |
6000 | 0 | e = d; |
6001 | 0 | d = c; |
6002 | 0 | c = (b << 30) | (b >>> 2); |
6003 | 0 | b = a; |
6004 | 0 | a = t; |
6005 | } | |
6006 | // round 3 | |
6007 | 0 | for(; i < 60; ++i) { |
6008 | 0 | t = (w[i - 6] ^ w[i - 16] ^ w[i - 28] ^ w[i - 32]); |
6009 | 0 | t = (t << 2) | (t >>> 30); |
6010 | 0 | w[i] = t; |
6011 | 0 | f = (b & c) | (d & (b ^ c)); |
6012 | 0 | t = ((a << 5) | (a >>> 27)) + f + e + 0x8F1BBCDC + t; |
6013 | 0 | e = d; |
6014 | 0 | d = c; |
6015 | 0 | c = (b << 30) | (b >>> 2); |
6016 | 0 | b = a; |
6017 | 0 | a = t; |
6018 | } | |
6019 | // round 4 | |
6020 | 0 | for(; i < 80; ++i) { |
6021 | 0 | t = (w[i - 6] ^ w[i - 16] ^ w[i - 28] ^ w[i - 32]); |
6022 | 0 | t = (t << 2) | (t >>> 30); |
6023 | 0 | w[i] = t; |
6024 | 0 | f = b ^ c ^ d; |
6025 | 0 | t = ((a << 5) | (a >>> 27)) + f + e + 0xCA62C1D6 + t; |
6026 | 0 | e = d; |
6027 | 0 | d = c; |
6028 | 0 | c = (b << 30) | (b >>> 2); |
6029 | 0 | b = a; |
6030 | 0 | a = t; |
6031 | } | |
6032 | ||
6033 | // update hash state | |
6034 | 0 | s.h0 += a; |
6035 | 0 | s.h1 += b; |
6036 | 0 | s.h2 += c; |
6037 | 0 | s.h3 += d; |
6038 | 0 | s.h4 += e; |
6039 | ||
6040 | 0 | len -= 64; |
6041 | } | |
6042 | }; | |
6043 | ||
6044 | } // end non-nodejs | |
6045 | ||
6046 | 2 | if(!XMLSerializer) { |
6047 | ||
6048 | 2 | function _defineXMLSerializer() { |
6049 | 0 | XMLSerializer = require('xmldom').XMLSerializer; |
6050 | } | |
6051 | ||
6052 | } // end _defineXMLSerializer | |
6053 | ||
6054 | // define URL parser | |
6055 | 2 | jsonld.url = {}; |
6056 | 2 | if(_nodejs) { |
6057 | 2 | var parse = require('url').parse; |
6058 | 2 | jsonld.url.parse = function(url) { |
6059 | 516 | var parsed = parse(url); |
6060 | 516 | parsed.pathname = parsed.pathname || ''; |
6061 | 516 | _parseAuthority(parsed); |
6062 | 516 | parsed.normalizedPath = _removeDotSegments( |
6063 | parsed.pathname, parsed.authority !== ''); | |
6064 | 516 | return parsed; |
6065 | }; | |
6066 | } | |
6067 | else { | |
6068 | // parseUri 1.2.2 | |
6069 | // (c) Steven Levithan <stevenlevithan.com> | |
6070 | // MIT License | |
6071 | 0 | var parseUri = {}; |
6072 | 0 | parseUri.options = { |
6073 | key: ['href','protocol','host','auth','user','password','hostname','port','relative','path','directory','file','query','hash'], | |
6074 | parser: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/ | |
6075 | }; | |
6076 | 0 | jsonld.url.parse = function(str) { |
6077 | 0 | var o = parseUri.options; |
6078 | 0 | var m = o.parser.exec(str); |
6079 | 0 | var uri = {}; |
6080 | 0 | var i = 14; |
6081 | 0 | while(i--) { |
6082 | 0 | uri[o.key[i]] = m[i] || ''; |
6083 | } | |
6084 | // normalize to node.js API | |
6085 | 0 | if(uri.host && uri.path === '') { |
6086 | 0 | uri.path = '/'; |
6087 | } | |
6088 | 0 | uri.pathname = uri.path || ''; |
6089 | 0 | _parseAuthority(uri); |
6090 | 0 | uri.normalizedPath = _removeDotSegments(uri.pathname, uri.authority !== ''); |
6091 | 0 | if(uri.query) { |
6092 | 0 | uri.path = uri.path + '?' + uri.query; |
6093 | } | |
6094 | 0 | if(uri.protocol) { |
6095 | 0 | uri.protocol += ':'; |
6096 | } | |
6097 | 0 | if(uri.hash) { |
6098 | 0 | uri.hash = '#' + uri.hash; |
6099 | } | |
6100 | 0 | return uri; |
6101 | }; | |
6102 | } | |
6103 | ||
6104 | /** | |
6105 | * Parses the authority for the pre-parsed given URL. | |
6106 | * | |
6107 | * @param parsed the pre-parsed URL. | |
6108 | */ | |
6109 | 2 | function _parseAuthority(parsed) { |
6110 | // parse authority for unparsed relative network-path reference | |
6111 | 516 | if(parsed.href.indexOf(':') === -1 && parsed.href.indexOf('//') === 0 && |
6112 | !parsed.host) { | |
6113 | // must parse authority from pathname | |
6114 | 8 | parsed.pathname = parsed.pathname.substr(2); |
6115 | 8 | var idx = parsed.pathname.indexOf('/'); |
6116 | 8 | if(idx === -1) { |
6117 | 0 | parsed.authority = parsed.pathname; |
6118 | 0 | parsed.pathname = ''; |
6119 | } | |
6120 | else { | |
6121 | 8 | parsed.authority = parsed.pathname.substr(0, idx); |
6122 | 8 | parsed.pathname = parsed.pathname.substr(idx); |
6123 | } | |
6124 | } | |
6125 | else { | |
6126 | // construct authority | |
6127 | 508 | parsed.authority = parsed.host || ''; |
6128 | 508 | if(parsed.auth) { |
6129 | 0 | parsed.authority = parsed.auth + '@' + parsed.authority; |
6130 | } | |
6131 | } | |
6132 | } | |
6133 | ||
6134 | /** | |
6135 | * Removes dot segments from a URL path. | |
6136 | * | |
6137 | * @param path the path to remove dot segments from. | |
6138 | * @param hasAuthority true if the URL has an authority, false if not. | |
6139 | */ | |
6140 | 2 | function _removeDotSegments(path, hasAuthority) { |
6141 | 621 | var rval = ''; |
6142 | ||
6143 | 621 | if(path.indexOf('/') === 0) { |
6144 | 532 | rval = '/'; |
6145 | } | |
6146 | ||
6147 | // RFC 3986 5.2.4 (reworked) | |
6148 | 621 | var input = path.split('/'); |
6149 | 621 | var output = []; |
6150 | 621 | while(input.length > 0) { |
6151 | 2424 | if(input[0] === '.' || (input[0] === '' && input.length > 1)) { |
6152 | 576 | input.shift(); |
6153 | 576 | continue; |
6154 | } | |
6155 | 1848 | if(input[0] === '..') { |
6156 | 190 | input.shift(); |
6157 | 190 | if(hasAuthority || |
6158 | (output.length > 0 && output[output.length - 1] !== '..')) { | |
6159 | 101 | output.pop(); |
6160 | } | |
6161 | // leading relative URL '..' | |
6162 | else { | |
6163 | 89 | output.push('..'); |
6164 | } | |
6165 | 190 | continue; |
6166 | } | |
6167 | 1658 | output.push(input.shift()); |
6168 | } | |
6169 | ||
6170 | 621 | return rval + output.join('/'); |
6171 | } | |
6172 | ||
6173 | 2 | if(_nodejs) { |
6174 | // use node context loader by default | |
6175 | 2 | jsonld.useContextLoader('node'); |
6176 | } | |
6177 | ||
6178 | 2 | if(_nodejs) { |
6179 | 2 | jsonld.use = function(extension) { |
6180 | 0 | switch(extension) { |
6181 | case 'request': | |
6182 | // use node JSON-LD request extension | |
6183 | 0 | jsonld.request = require('./request'); |
6184 | 0 | break; |
6185 | default: | |
6186 | 0 | throw new JsonLdError( |
6187 | 'Unknown extension.', | |
6188 | 'jsonld.UnknownExtension', {extension: extension}); | |
6189 | } | |
6190 | } | |
6191 | } | |
6192 | ||
6193 | // end of jsonld API factory | |
6194 | 2 | return jsonld; |
6195 | }; | |
6196 | ||
6197 | // external APIs: | |
6198 | ||
6199 | // used to generate a new jsonld API instance | |
6200 | 1 | var factory = function() { |
6201 | 1 | return wrapper(function() { |
6202 | 0 | return factory(); |
6203 | }); | |
6204 | }; | |
6205 | // the shared global jsonld API instance | |
6206 | 1 | wrapper(factory); |
6207 | ||
6208 | // export nodejs API | |
6209 | 1 | if(_nodejs) { |
6210 | 1 | module.exports = factory; |
6211 | } | |
6212 | // export AMD API | |
6213 | 0 | else if(typeof define === 'function' && define.amd) { |
6214 | 0 | define('jsonld', [], function() { |
6215 | 0 | return factory; |
6216 | }); | |
6217 | } | |
6218 | // export simple browser API | |
6219 | 0 | else if(_browser) { |
6220 | 0 | window.jsonld = window.jsonld || factory; |
6221 | } | |
6222 | ||
6223 | })(); |