-
Notifications
You must be signed in to change notification settings - Fork 197
/
context.js
1607 lines (1469 loc) · 48.8 KB
/
context.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 2017-2019 Digital Bazaar, Inc. All rights reserved.
*/
'use strict';
const util = require('./util');
const JsonLdError = require('./JsonLdError');
const {
isArray: _isArray,
isObject: _isObject,
isString: _isString,
isUndefined: _isUndefined
} = require('./types');
const {
isAbsolute: _isAbsoluteIri,
isRelative: _isRelativeIri,
prependBase
} = require('./url');
const {
handleEvent: _handleEvent
} = require('./events');
const {
REGEX_BCP47,
REGEX_KEYWORD,
asArray: _asArray,
compareShortestLeast: _compareShortestLeast
} = require('./util');
const INITIAL_CONTEXT_CACHE = new Map();
const INITIAL_CONTEXT_CACHE_MAX_SIZE = 10000;
const api = {};
module.exports = api;
/**
* Processes a local context and returns a new active context.
*
* @param activeCtx the current active context.
* @param localCtx the local context to process.
* @param options the context processing options.
* @param propagate `true` if `false`, retains any previously defined term,
* which can be rolled back when the descending into a new node object.
* @param overrideProtected `false` allows protected terms to be modified.
*
* @return a Promise that resolves to the new active context.
*/
api.process = async ({
activeCtx, localCtx, options,
propagate = true,
overrideProtected = false,
cycles = new Set()
}) => {
// normalize local context to an array of @context objects
if(_isObject(localCtx) && '@context' in localCtx &&
_isArray(localCtx['@context'])) {
localCtx = localCtx['@context'];
}
const ctxs = _asArray(localCtx);
// no contexts in array, return current active context w/o changes
if(ctxs.length === 0) {
return activeCtx;
}
// event handler for capturing events to replay when using a cached context
const events = [];
const eventCaptureHandler = [
({event, next}) => {
events.push(event);
next();
}
];
// chain to original handler
if(options.eventHandler) {
eventCaptureHandler.push(options.eventHandler);
}
// store original options to use when replaying events
const originalOptions = options;
// shallow clone options with event capture handler
options = {...options, eventHandler: eventCaptureHandler};
// resolve contexts
const resolved = await options.contextResolver.resolve({
activeCtx,
context: localCtx,
documentLoader: options.documentLoader,
base: options.base
});
// override propagate if first resolved context has `@propagate`
if(_isObject(resolved[0].document) &&
typeof resolved[0].document['@propagate'] === 'boolean') {
// retrieve early, error checking done later
propagate = resolved[0].document['@propagate'];
}
// process each context in order, update active context
// on each iteration to ensure proper caching
let rval = activeCtx;
// track the previous context
// if not propagating, make sure rval has a previous context
if(!propagate && !rval.previousContext) {
// clone `rval` context before updating
rval = rval.clone();
rval.previousContext = activeCtx;
}
for(const resolvedContext of resolved) {
let {document: ctx} = resolvedContext;
// update active context to one computed from last iteration
activeCtx = rval;
// reset to initial context
if(ctx === null) {
// We can't nullify if there are protected terms and we're
// not allowing overrides (e.g. processing a property term scoped context)
if(!overrideProtected && Object.keys(activeCtx.protected).length !== 0) {
throw new JsonLdError(
'Tried to nullify a context with protected terms outside of ' +
'a term definition.',
'jsonld.SyntaxError',
{code: 'invalid context nullification'});
}
rval = activeCtx = api.getInitialContext(options).clone();
continue;
}
// get processed context from cache if available
const processed = resolvedContext.getProcessed(activeCtx);
if(processed) {
if(originalOptions.eventHandler) {
// replay events with original non-capturing options
for(const event of processed.events) {
_handleEvent({event, options: originalOptions});
}
}
rval = activeCtx = processed.context;
continue;
}
// dereference @context key if present
if(_isObject(ctx) && '@context' in ctx) {
ctx = ctx['@context'];
}
// context must be an object by now, all URLs retrieved before this call
if(!_isObject(ctx)) {
throw new JsonLdError(
'Invalid JSON-LD syntax; @context must be an object.',
'jsonld.SyntaxError', {code: 'invalid local context', context: ctx});
}
// TODO: there is likely a `previousContext` cloning optimization that
// could be applied here (no need to copy it under certain conditions)
// clone context before updating it
rval = rval.clone();
// define context mappings for keys in local context
const defined = new Map();
// handle @version
if('@version' in ctx) {
if(ctx['@version'] !== 1.1) {
throw new JsonLdError(
'Unsupported JSON-LD version: ' + ctx['@version'],
'jsonld.UnsupportedVersion',
{code: 'invalid @version value', context: ctx});
}
if(activeCtx.processingMode &&
activeCtx.processingMode === 'json-ld-1.0') {
throw new JsonLdError(
'@version: ' + ctx['@version'] + ' not compatible with ' +
activeCtx.processingMode,
'jsonld.ProcessingModeConflict',
{code: 'processing mode conflict', context: ctx});
}
rval.processingMode = 'json-ld-1.1';
rval['@version'] = ctx['@version'];
defined.set('@version', true);
}
// if not set explicitly, set processingMode to "json-ld-1.1"
rval.processingMode =
rval.processingMode || activeCtx.processingMode;
// handle @base
if('@base' in ctx) {
let base = ctx['@base'];
if(base === null || _isAbsoluteIri(base)) {
// no action
} else if(_isRelativeIri(base)) {
base = prependBase(rval['@base'], base);
} else {
throw new JsonLdError(
'Invalid JSON-LD syntax; the value of "@base" in a ' +
'@context must be an absolute IRI, a relative IRI, or null.',
'jsonld.SyntaxError', {code: 'invalid base IRI', context: ctx});
}
rval['@base'] = base;
defined.set('@base', true);
}
// handle @vocab
if('@vocab' in ctx) {
const value = ctx['@vocab'];
if(value === null) {
delete rval['@vocab'];
} else if(!_isString(value)) {
throw new JsonLdError(
'Invalid JSON-LD syntax; the value of "@vocab" in a ' +
'@context must be a string or null.',
'jsonld.SyntaxError', {code: 'invalid vocab mapping', context: ctx});
} else if(!_isAbsoluteIri(value) && api.processingMode(rval, 1.0)) {
throw new JsonLdError(
'Invalid JSON-LD syntax; the value of "@vocab" in a ' +
'@context must be an absolute IRI.',
'jsonld.SyntaxError', {code: 'invalid vocab mapping', context: ctx});
} else {
const vocab = _expandIri(rval, value, {vocab: true, base: true},
undefined, undefined, options);
if(!_isAbsoluteIri(vocab)) {
if(options.eventHandler) {
_handleEvent({
event: {
type: ['JsonLdEvent'],
code: 'relative @vocab reference',
level: 'warning',
message: 'Relative @vocab reference found.',
details: {
vocab
}
},
options
});
}
}
rval['@vocab'] = vocab;
}
defined.set('@vocab', true);
}
// handle @language
if('@language' in ctx) {
const value = ctx['@language'];
if(value === null) {
delete rval['@language'];
} else if(!_isString(value)) {
throw new JsonLdError(
'Invalid JSON-LD syntax; the value of "@language" in a ' +
'@context must be a string or null.',
'jsonld.SyntaxError',
{code: 'invalid default language', context: ctx});
} else {
if(!value.match(REGEX_BCP47)) {
if(options.eventHandler) {
_handleEvent({
event: {
type: ['JsonLdEvent'],
code: 'invalid @language value',
level: 'warning',
message: '@language value must be valid BCP47.',
details: {
language: value
}
},
options
});
}
}
rval['@language'] = value.toLowerCase();
}
defined.set('@language', true);
}
// handle @direction
if('@direction' in ctx) {
const value = ctx['@direction'];
if(activeCtx.processingMode === 'json-ld-1.0') {
throw new JsonLdError(
'Invalid JSON-LD syntax; @direction not compatible with ' +
activeCtx.processingMode,
'jsonld.SyntaxError',
{code: 'invalid context member', context: ctx});
}
if(value === null) {
delete rval['@direction'];
} else if(value !== 'ltr' && value !== 'rtl') {
throw new JsonLdError(
'Invalid JSON-LD syntax; the value of "@direction" in a ' +
'@context must be null, "ltr", or "rtl".',
'jsonld.SyntaxError',
{code: 'invalid base direction', context: ctx});
} else {
rval['@direction'] = value;
}
defined.set('@direction', true);
}
// handle @propagate
// note: we've already extracted it, here we just do error checking
if('@propagate' in ctx) {
const value = ctx['@propagate'];
if(activeCtx.processingMode === 'json-ld-1.0') {
throw new JsonLdError(
'Invalid JSON-LD syntax; @propagate not compatible with ' +
activeCtx.processingMode,
'jsonld.SyntaxError',
{code: 'invalid context entry', context: ctx});
}
if(typeof value !== 'boolean') {
throw new JsonLdError(
'Invalid JSON-LD syntax; @propagate value must be a boolean.',
'jsonld.SyntaxError',
{code: 'invalid @propagate value', context: localCtx});
}
defined.set('@propagate', true);
}
// handle @import
if('@import' in ctx) {
const value = ctx['@import'];
if(activeCtx.processingMode === 'json-ld-1.0') {
throw new JsonLdError(
'Invalid JSON-LD syntax; @import not compatible with ' +
activeCtx.processingMode,
'jsonld.SyntaxError',
{code: 'invalid context entry', context: ctx});
}
if(!_isString(value)) {
throw new JsonLdError(
'Invalid JSON-LD syntax; @import must be a string.',
'jsonld.SyntaxError',
{code: 'invalid @import value', context: localCtx});
}
// resolve contexts
const resolvedImport = await options.contextResolver.resolve({
activeCtx,
context: value,
documentLoader: options.documentLoader,
base: options.base
});
if(resolvedImport.length !== 1) {
throw new JsonLdError(
'Invalid JSON-LD syntax; @import must reference a single context.',
'jsonld.SyntaxError',
{code: 'invalid remote context', context: localCtx});
}
const processedImport = resolvedImport[0].getProcessed(activeCtx);
if(processedImport) {
// Note: if the same context were used in this active context
// as a reference context, then processed_input might not
// be a dict.
ctx = processedImport;
} else {
const importCtx = resolvedImport[0].document;
if('@import' in importCtx) {
throw new JsonLdError(
'Invalid JSON-LD syntax: ' +
'imported context must not include @import.',
'jsonld.SyntaxError',
{code: 'invalid context entry', context: localCtx});
}
// merge ctx into importCtx and replace rval with the result
for(const key in importCtx) {
if(!ctx.hasOwnProperty(key)) {
ctx[key] = importCtx[key];
}
}
// Note: this could potenially conflict if the import
// were used in the same active context as a referenced
// context and an import. In this case, we
// could override the cached result, but seems unlikely.
resolvedImport[0].setProcessed(activeCtx, ctx);
}
defined.set('@import', true);
}
// handle @protected; determine whether this sub-context is declaring
// all its terms to be "protected" (exceptions can be made on a
// per-definition basis)
defined.set('@protected', ctx['@protected'] || false);
// process all other keys
for(const key in ctx) {
api.createTermDefinition({
activeCtx: rval,
localCtx: ctx,
term: key,
defined,
options,
overrideProtected
});
if(_isObject(ctx[key]) && '@context' in ctx[key]) {
const keyCtx = ctx[key]['@context'];
let process = true;
if(_isString(keyCtx)) {
const url = prependBase(options.base, keyCtx);
// track processed contexts to avoid scoped context recursion
if(cycles.has(url)) {
process = false;
} else {
cycles.add(url);
}
}
// parse context to validate
if(process) {
try {
await api.process({
activeCtx: rval.clone(),
localCtx: ctx[key]['@context'],
overrideProtected: true,
options,
cycles
});
} catch(e) {
throw new JsonLdError(
'Invalid JSON-LD syntax; invalid scoped context.',
'jsonld.SyntaxError',
{
code: 'invalid scoped context',
context: ctx[key]['@context'],
term: key
});
}
}
}
}
// cache processed result
resolvedContext.setProcessed(activeCtx, {
context: rval,
events
});
}
return rval;
};
/**
* Creates a term definition during context processing.
*
* @param activeCtx the current active context.
* @param localCtx the local context being processed.
* @param term the term in the local context to define the mapping for.
* @param defined a map of defining/defined keys to detect cycles and prevent
* double definitions.
* @param {Object} [options] - creation options.
* @param overrideProtected `false` allows protected terms to be modified.
*/
api.createTermDefinition = ({
activeCtx,
localCtx,
term,
defined,
options,
overrideProtected = false,
}) => {
if(defined.has(term)) {
// term already defined
if(defined.get(term)) {
return;
}
// cycle detected
throw new JsonLdError(
'Cyclical context definition detected.',
'jsonld.CyclicalContext',
{code: 'cyclic IRI mapping', context: localCtx, term});
}
// now defining term
defined.set(term, false);
// get context term value
let value;
if(localCtx.hasOwnProperty(term)) {
value = localCtx[term];
}
if(term === '@type' &&
_isObject(value) &&
(value['@container'] || '@set') === '@set' &&
api.processingMode(activeCtx, 1.1)) {
const validKeys = ['@container', '@id', '@protected'];
const keys = Object.keys(value);
if(keys.length === 0 || keys.some(k => !validKeys.includes(k))) {
throw new JsonLdError(
'Invalid JSON-LD syntax; keywords cannot be overridden.',
'jsonld.SyntaxError',
{code: 'keyword redefinition', context: localCtx, term});
}
} else if(api.isKeyword(term)) {
throw new JsonLdError(
'Invalid JSON-LD syntax; keywords cannot be overridden.',
'jsonld.SyntaxError',
{code: 'keyword redefinition', context: localCtx, term});
} else if(term.match(REGEX_KEYWORD)) {
if(options.eventHandler) {
_handleEvent({
event: {
type: ['JsonLdEvent'],
code: 'reserved term',
level: 'warning',
message:
'Terms beginning with "@" are ' +
'reserved for future use and dropped.',
details: {
term
}
},
options
});
}
return;
} else if(term === '') {
throw new JsonLdError(
'Invalid JSON-LD syntax; a term cannot be an empty string.',
'jsonld.SyntaxError',
{code: 'invalid term definition', context: localCtx});
}
// keep reference to previous mapping for potential `@protected` check
const previousMapping = activeCtx.mappings.get(term);
// remove old mapping
if(activeCtx.mappings.has(term)) {
activeCtx.mappings.delete(term);
}
// convert short-hand value to object w/@id
let simpleTerm = false;
if(_isString(value) || value === null) {
simpleTerm = true;
value = {'@id': value};
}
if(!_isObject(value)) {
throw new JsonLdError(
'Invalid JSON-LD syntax; @context term values must be ' +
'strings or objects.',
'jsonld.SyntaxError',
{code: 'invalid term definition', context: localCtx});
}
// create new mapping
const mapping = {};
activeCtx.mappings.set(term, mapping);
mapping.reverse = false;
// make sure term definition only has expected keywords
const validKeys = ['@container', '@id', '@language', '@reverse', '@type'];
// JSON-LD 1.1 support
if(api.processingMode(activeCtx, 1.1)) {
validKeys.push(
'@context', '@direction', '@index', '@nest', '@prefix', '@protected');
}
for(const kw in value) {
if(!validKeys.includes(kw)) {
throw new JsonLdError(
'Invalid JSON-LD syntax; a term definition must not contain ' + kw,
'jsonld.SyntaxError',
{code: 'invalid term definition', context: localCtx});
}
}
// always compute whether term has a colon as an optimization for
// _compactIri
const colon = term.indexOf(':');
mapping._termHasColon = (colon > 0);
if('@reverse' in value) {
if('@id' in value) {
throw new JsonLdError(
'Invalid JSON-LD syntax; a @reverse term definition must not ' +
'contain @id.', 'jsonld.SyntaxError',
{code: 'invalid reverse property', context: localCtx});
}
if('@nest' in value) {
throw new JsonLdError(
'Invalid JSON-LD syntax; a @reverse term definition must not ' +
'contain @nest.', 'jsonld.SyntaxError',
{code: 'invalid reverse property', context: localCtx});
}
const reverse = value['@reverse'];
if(!_isString(reverse)) {
throw new JsonLdError(
'Invalid JSON-LD syntax; a @context @reverse value must be a string.',
'jsonld.SyntaxError', {code: 'invalid IRI mapping', context: localCtx});
}
if(reverse.match(REGEX_KEYWORD)) {
if(options.eventHandler) {
_handleEvent({
event: {
type: ['JsonLdEvent'],
code: 'reserved @reverse value',
level: 'warning',
message:
'@reverse values beginning with "@" are ' +
'reserved for future use and dropped.',
details: {
reverse
}
},
options
});
}
if(previousMapping) {
activeCtx.mappings.set(term, previousMapping);
} else {
activeCtx.mappings.delete(term);
}
return;
}
// expand and add @id mapping
const id = _expandIri(
activeCtx, reverse, {vocab: true, base: false}, localCtx, defined,
options);
if(!_isAbsoluteIri(id)) {
throw new JsonLdError(
'Invalid JSON-LD syntax; a @context @reverse value must be an ' +
'absolute IRI or a blank node identifier.',
'jsonld.SyntaxError', {code: 'invalid IRI mapping', context: localCtx});
}
mapping['@id'] = id;
mapping.reverse = true;
} else if('@id' in value) {
let id = value['@id'];
if(id && !_isString(id)) {
throw new JsonLdError(
'Invalid JSON-LD syntax; a @context @id value must be an array ' +
'of strings or a string.',
'jsonld.SyntaxError', {code: 'invalid IRI mapping', context: localCtx});
}
if(id === null) {
// reserve a null term, which may be protected
mapping['@id'] = null;
} else if(!api.isKeyword(id) && id.match(REGEX_KEYWORD)) {
if(options.eventHandler) {
_handleEvent({
event: {
type: ['JsonLdEvent'],
code: 'reserved @id value',
level: 'warning',
message:
'@id values beginning with "@" are ' +
'reserved for future use and dropped.',
details: {
id
}
},
options
});
}
if(previousMapping) {
activeCtx.mappings.set(term, previousMapping);
} else {
activeCtx.mappings.delete(term);
}
return;
} else if(id !== term) {
// expand and add @id mapping
id = _expandIri(
activeCtx, id, {vocab: true, base: false}, localCtx, defined, options);
if(!_isAbsoluteIri(id) && !api.isKeyword(id)) {
throw new JsonLdError(
'Invalid JSON-LD syntax; a @context @id value must be an ' +
'absolute IRI, a blank node identifier, or a keyword.',
'jsonld.SyntaxError',
{code: 'invalid IRI mapping', context: localCtx});
}
// if term has the form of an IRI it must map the same
if(term.match(/(?::[^:])|\//)) {
const termDefined = new Map(defined).set(term, true);
const termIri = _expandIri(
activeCtx, term, {vocab: true, base: false},
localCtx, termDefined, options);
if(termIri !== id) {
throw new JsonLdError(
'Invalid JSON-LD syntax; term in form of IRI must ' +
'expand to definition.',
'jsonld.SyntaxError',
{code: 'invalid IRI mapping', context: localCtx});
}
}
mapping['@id'] = id;
// indicate if this term may be used as a compact IRI prefix
mapping._prefix = (simpleTerm &&
!mapping._termHasColon &&
id.match(/[:\/\?#\[\]@]$/) !== null);
}
}
if(!('@id' in mapping)) {
// see if the term has a prefix
if(mapping._termHasColon) {
const prefix = term.substr(0, colon);
if(localCtx.hasOwnProperty(prefix)) {
// define parent prefix
api.createTermDefinition({
activeCtx, localCtx, term: prefix, defined, options
});
}
if(activeCtx.mappings.has(prefix)) {
// set @id based on prefix parent
const suffix = term.substr(colon + 1);
mapping['@id'] = activeCtx.mappings.get(prefix)['@id'] + suffix;
} else {
// term is an absolute IRI
mapping['@id'] = term;
}
} else if(term === '@type') {
// Special case, were we've previously determined that container is @set
mapping['@id'] = term;
} else {
// non-IRIs *must* define @ids if @vocab is not available
if(!('@vocab' in activeCtx)) {
throw new JsonLdError(
'Invalid JSON-LD syntax; @context terms must define an @id.',
'jsonld.SyntaxError',
{code: 'invalid IRI mapping', context: localCtx, term});
}
// prepend vocab to term
mapping['@id'] = activeCtx['@vocab'] + term;
}
}
// Handle term protection
if(value['@protected'] === true ||
(defined.get('@protected') === true && value['@protected'] !== false)) {
activeCtx.protected[term] = true;
mapping.protected = true;
}
// IRI mapping now defined
defined.set(term, true);
if('@type' in value) {
let type = value['@type'];
if(!_isString(type)) {
throw new JsonLdError(
'Invalid JSON-LD syntax; an @context @type value must be a string.',
'jsonld.SyntaxError',
{code: 'invalid type mapping', context: localCtx});
}
if((type === '@json' || type === '@none')) {
if(api.processingMode(activeCtx, 1.0)) {
throw new JsonLdError(
'Invalid JSON-LD syntax; an @context @type value must not be ' +
`"${type}" in JSON-LD 1.0 mode.`,
'jsonld.SyntaxError',
{code: 'invalid type mapping', context: localCtx});
}
} else if(type !== '@id' && type !== '@vocab') {
// expand @type to full IRI
type = _expandIri(
activeCtx, type, {vocab: true, base: false}, localCtx, defined,
options);
if(!_isAbsoluteIri(type)) {
throw new JsonLdError(
'Invalid JSON-LD syntax; an @context @type value must be an ' +
'absolute IRI.',
'jsonld.SyntaxError',
{code: 'invalid type mapping', context: localCtx});
}
if(type.indexOf('_:') === 0) {
throw new JsonLdError(
'Invalid JSON-LD syntax; an @context @type value must be an IRI, ' +
'not a blank node identifier.',
'jsonld.SyntaxError',
{code: 'invalid type mapping', context: localCtx});
}
}
// add @type to mapping
mapping['@type'] = type;
}
if('@container' in value) {
// normalize container to an array form
const container = _isString(value['@container']) ?
[value['@container']] : (value['@container'] || []);
const validContainers = ['@list', '@set', '@index', '@language'];
let isValid = true;
const hasSet = container.includes('@set');
// JSON-LD 1.1 support
if(api.processingMode(activeCtx, 1.1)) {
validContainers.push('@graph', '@id', '@type');
// check container length
if(container.includes('@list')) {
if(container.length !== 1) {
throw new JsonLdError(
'Invalid JSON-LD syntax; @context @container with @list must ' +
'have no other values',
'jsonld.SyntaxError',
{code: 'invalid container mapping', context: localCtx});
}
} else if(container.includes('@graph')) {
if(container.some(key =>
key !== '@graph' && key !== '@id' && key !== '@index' &&
key !== '@set')) {
throw new JsonLdError(
'Invalid JSON-LD syntax; @context @container with @graph must ' +
'have no other values other than @id, @index, and @set',
'jsonld.SyntaxError',
{code: 'invalid container mapping', context: localCtx});
}
} else {
// otherwise, container may also include @set
isValid &= container.length <= (hasSet ? 2 : 1);
}
if(container.includes('@type')) {
// If mapping does not have an @type,
// set it to @id
mapping['@type'] = mapping['@type'] || '@id';
// type mapping must be either @id or @vocab
if(!['@id', '@vocab'].includes(mapping['@type'])) {
throw new JsonLdError(
'Invalid JSON-LD syntax; container: @type requires @type to be ' +
'@id or @vocab.',
'jsonld.SyntaxError',
{code: 'invalid type mapping', context: localCtx});
}
}
} else {
// in JSON-LD 1.0, container must not be an array (it must be a string,
// which is one of the validContainers)
isValid &= !_isArray(value['@container']);
// check container length
isValid &= container.length <= 1;
}
// check against valid containers
isValid &= container.every(c => validContainers.includes(c));
// @set not allowed with @list
isValid &= !(hasSet && container.includes('@list'));
if(!isValid) {
throw new JsonLdError(
'Invalid JSON-LD syntax; @context @container value must be ' +
'one of the following: ' + validContainers.join(', '),
'jsonld.SyntaxError',
{code: 'invalid container mapping', context: localCtx});
}
if(mapping.reverse &&
!container.every(c => ['@index', '@set'].includes(c))) {
throw new JsonLdError(
'Invalid JSON-LD syntax; @context @container value for a @reverse ' +
'type definition must be @index or @set.', 'jsonld.SyntaxError',
{code: 'invalid reverse property', context: localCtx});
}
// add @container to mapping
mapping['@container'] = container;
}
// property indexing
if('@index' in value) {
if(!('@container' in value) || !mapping['@container'].includes('@index')) {
throw new JsonLdError(
'Invalid JSON-LD syntax; @index without @index in @container: ' +
`"${value['@index']}" on term "${term}".`, 'jsonld.SyntaxError',
{code: 'invalid term definition', context: localCtx});
}
if(!_isString(value['@index']) || value['@index'].indexOf('@') === 0) {
throw new JsonLdError(
'Invalid JSON-LD syntax; @index must expand to an IRI: ' +
`"${value['@index']}" on term "${term}".`, 'jsonld.SyntaxError',
{code: 'invalid term definition', context: localCtx});
}
mapping['@index'] = value['@index'];
}
// scoped contexts
if('@context' in value) {
mapping['@context'] = value['@context'];
}
if('@language' in value && !('@type' in value)) {
let language = value['@language'];
if(language !== null && !_isString(language)) {
throw new JsonLdError(
'Invalid JSON-LD syntax; @context @language value must be ' +
'a string or null.', 'jsonld.SyntaxError',
{code: 'invalid language mapping', context: localCtx});
}
// add @language to mapping
if(language !== null) {
language = language.toLowerCase();
}
mapping['@language'] = language;
}
// term may be used as a prefix
if('@prefix' in value) {
if(term.match(/:|\//)) {
throw new JsonLdError(
'Invalid JSON-LD syntax; @context @prefix used on a compact IRI term',
'jsonld.SyntaxError',
{code: 'invalid term definition', context: localCtx});
}
if(api.isKeyword(mapping['@id'])) {
throw new JsonLdError(
'Invalid JSON-LD syntax; keywords may not be used as prefixes',
'jsonld.SyntaxError',
{code: 'invalid term definition', context: localCtx});
}
if(typeof value['@prefix'] === 'boolean') {
mapping._prefix = value['@prefix'] === true;
} else {
throw new JsonLdError(
'Invalid JSON-LD syntax; @context value for @prefix must be boolean',
'jsonld.SyntaxError',
{code: 'invalid @prefix value', context: localCtx});
}
}
if('@direction' in value) {
const direction = value['@direction'];
if(direction !== null && direction !== 'ltr' && direction !== 'rtl') {
throw new JsonLdError(
'Invalid JSON-LD syntax; @direction value must be ' +
'null, "ltr", or "rtl".',
'jsonld.SyntaxError',
{code: 'invalid base direction', context: localCtx});
}
mapping['@direction'] = direction;
}
if('@nest' in value) {
const nest = value['@nest'];
if(!_isString(nest) || (nest !== '@nest' && nest.indexOf('@') === 0)) {
throw new JsonLdError(
'Invalid JSON-LD syntax; @context @nest value must be ' +
'a string which is not a keyword other than @nest.',
'jsonld.SyntaxError',
{code: 'invalid @nest value', context: localCtx});
}
mapping['@nest'] = nest;
}
// disallow aliasing @context and @preserve
const id = mapping['@id'];
if(id === '@context' || id === '@preserve') {
throw new JsonLdError(
'Invalid JSON-LD syntax; @context and @preserve cannot be aliased.',
'jsonld.SyntaxError', {code: 'invalid keyword alias', context: localCtx});
}
// Check for overriding protected terms
if(previousMapping && previousMapping.protected && !overrideProtected) {
// force new term to continue to be protected and see if the mappings would
// be equal
activeCtx.protected[term] = true;
mapping.protected = true;
if(!_deepCompare(previousMapping, mapping)) {
throw new JsonLdError(
'Invalid JSON-LD syntax; tried to redefine a protected term.',
'jsonld.SyntaxError',
{code: 'protected term redefinition', context: localCtx, term});
}
}
};
/**
* Expands a string to a full IRI. The string may be a term, a prefix, a
* relative IRI, or an absolute IRI. The associated absolute IRI will be
* returned.
*