-
Notifications
You must be signed in to change notification settings - Fork 197
/
expand.js
1281 lines (1194 loc) · 38.9 KB
/
expand.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 Digital Bazaar, Inc. All rights reserved.
*/
'use strict';
const JsonLdError = require('./JsonLdError');
const {
isArray: _isArray,
isObject: _isObject,
isEmptyObject: _isEmptyObject,
isString: _isString,
isUndefined: _isUndefined
} = require('./types');
const {
isList: _isList,
isValue: _isValue,
isGraph: _isGraph,
isSubject: _isSubject
} = require('./graphTypes');
const {
expandIri: _expandIri,
getContextValue: _getContextValue,
isKeyword: _isKeyword,
process: _processContext,
processingMode: _processingMode
} = require('./context');
const {
isAbsolute: _isAbsoluteIri
} = require('./url');
const {
REGEX_BCP47,
REGEX_KEYWORD,
addValue: _addValue,
asArray: _asArray,
getValues: _getValues,
validateTypeValue: _validateTypeValue
} = require('./util');
const {
handleEvent: _handleEvent
} = require('./events');
const api = {};
module.exports = api;
/**
* Recursively expands an element using the given context. Any context in
* the element will be removed. All context URLs must have been retrieved
* before calling this method.
*
* @param activeCtx the context to use.
* @param activeProperty the property for the element, null for none.
* @param element the element to expand.
* @param options the expansion options.
* @param insideList true if the element is a list, false if not.
* @param insideIndex true if the element is inside an index container,
* false if not.
* @param typeScopedContext an optional type-scoped active context for
* expanding values of nodes that were expressed according to
* a type-scoped context.
*
* @return a Promise that resolves to the expanded value.
*/
api.expand = async ({
activeCtx,
activeProperty = null,
element,
options = {},
insideList = false,
insideIndex = false,
typeScopedContext = null
}) => {
// nothing to expand
if(element === null || element === undefined) {
return null;
}
// disable framing if activeProperty is @default
if(activeProperty === '@default') {
options = Object.assign({}, options, {isFrame: false});
}
if(!_isArray(element) && !_isObject(element)) {
// drop free-floating scalars that are not in lists
if(!insideList && (activeProperty === null ||
_expandIri(activeCtx, activeProperty, {vocab: true},
options) === '@graph')) {
// FIXME
if(options.eventHandler) {
_handleEvent({
event: {
type: ['JsonLdEvent'],
code: 'free-floating scalar',
level: 'warning',
message: 'Dropping free-floating scalar not in a list.',
details: {
value: element
//activeProperty
//insideList
}
},
options
});
}
return null;
}
// expand element according to value expansion rules
return _expandValue({activeCtx, activeProperty, value: element, options});
}
// recursively expand array
if(_isArray(element)) {
let rval = [];
const container = _getContextValue(
activeCtx, activeProperty, '@container') || [];
insideList = insideList || container.includes('@list');
for(let i = 0; i < element.length; ++i) {
// expand element
let e = await api.expand({
activeCtx,
activeProperty,
element: element[i],
options,
insideIndex,
typeScopedContext
});
if(insideList && _isArray(e)) {
e = {'@list': e};
}
if(e === null) {
// FIXME: add debug event?
//unmappedValue: element[i],
//activeProperty,
//parent: element,
//index: i,
//expandedParent: rval,
//insideList
// NOTE: no-value events emitted at calling sites as needed
continue;
}
if(_isArray(e)) {
rval = rval.concat(e);
} else {
rval.push(e);
}
}
return rval;
}
// recursively expand object:
// first, expand the active property
const expandedActiveProperty = _expandIri(
activeCtx, activeProperty, {vocab: true}, options);
// Get any property-scoped context for activeProperty
const propertyScopedCtx =
_getContextValue(activeCtx, activeProperty, '@context');
// second, determine if any type-scoped context should be reverted; it
// should only be reverted when the following are all true:
// 1. `element` is not a value or subject reference
// 2. `insideIndex` is false
typeScopedContext = typeScopedContext ||
(activeCtx.previousContext ? activeCtx : null);
let keys = Object.keys(element).sort();
let mustRevert = !insideIndex;
if(mustRevert && typeScopedContext && keys.length <= 2 &&
!keys.includes('@context')) {
for(const key of keys) {
const expandedProperty = _expandIri(
typeScopedContext, key, {vocab: true}, options);
if(expandedProperty === '@value') {
// value found, ensure type-scoped context is used to expand it
mustRevert = false;
activeCtx = typeScopedContext;
break;
}
if(expandedProperty === '@id' && keys.length === 1) {
// subject reference found, do not revert
mustRevert = false;
break;
}
}
}
if(mustRevert) {
// revert type scoped context
activeCtx = activeCtx.revertToPreviousContext();
}
// apply property-scoped context after reverting term-scoped context
if(!_isUndefined(propertyScopedCtx)) {
activeCtx = await _processContext({
activeCtx,
localCtx: propertyScopedCtx,
propagate: true,
overrideProtected: true,
options
});
}
// if element has a context, process it
if('@context' in element) {
activeCtx = await _processContext(
{activeCtx, localCtx: element['@context'], options});
}
// set the type-scoped context to the context on input, for use later
typeScopedContext = activeCtx;
// Remember the first key found expanding to @type
let typeKey = null;
// look for scoped contexts on `@type`
for(const key of keys) {
const expandedProperty = _expandIri(activeCtx, key, {vocab: true}, options);
if(expandedProperty === '@type') {
// set scoped contexts from @type
// avoid sorting if possible
typeKey = typeKey || key;
const value = element[key];
const types =
Array.isArray(value) ?
(value.length > 1 ? value.slice().sort() : value) : [value];
for(const type of types) {
const ctx = _getContextValue(typeScopedContext, type, '@context');
if(!_isUndefined(ctx)) {
activeCtx = await _processContext({
activeCtx,
localCtx: ctx,
options,
propagate: false
});
}
}
}
}
// process each key and value in element, ignoring @nest content
let rval = {};
await _expandObject({
activeCtx,
activeProperty,
expandedActiveProperty,
element,
expandedParent: rval,
options,
insideList,
typeKey,
typeScopedContext
});
// get property count on expanded output
keys = Object.keys(rval);
let count = keys.length;
if('@value' in rval) {
// @value must only have @language or @type
if('@type' in rval && ('@language' in rval || '@direction' in rval)) {
throw new JsonLdError(
'Invalid JSON-LD syntax; an element containing "@value" may not ' +
'contain both "@type" and either "@language" or "@direction".',
'jsonld.SyntaxError', {code: 'invalid value object', element: rval});
}
let validCount = count - 1;
if('@type' in rval) {
validCount -= 1;
}
if('@index' in rval) {
validCount -= 1;
}
if('@language' in rval) {
validCount -= 1;
}
if('@direction' in rval) {
validCount -= 1;
}
if(validCount !== 0) {
throw new JsonLdError(
'Invalid JSON-LD syntax; an element containing "@value" may only ' +
'have an "@index" property and either "@type" ' +
'or either or both "@language" or "@direction".',
'jsonld.SyntaxError', {code: 'invalid value object', element: rval});
}
const values = rval['@value'] === null ? [] : _asArray(rval['@value']);
const types = _getValues(rval, '@type');
// drop null @values
if(_processingMode(activeCtx, 1.1) && types.includes('@json') &&
types.length === 1) {
// Any value of @value is okay if @type: @json
} else if(values.length === 0) {
// FIXME
if(options.eventHandler) {
_handleEvent({
event: {
type: ['JsonLdEvent'],
code: 'null @value value',
level: 'warning',
message: 'Dropping null @value value.',
details: {
value: rval
}
},
options
});
}
rval = null;
} else if(!values.every(v => (_isString(v) || _isEmptyObject(v))) &&
'@language' in rval) {
// if @language is present, @value must be a string
throw new JsonLdError(
'Invalid JSON-LD syntax; only strings may be language-tagged.',
'jsonld.SyntaxError',
{code: 'invalid language-tagged value', element: rval});
} else if(!types.every(t =>
(_isAbsoluteIri(t) && !(_isString(t) && t.indexOf('_:') === 0) ||
_isEmptyObject(t)))) {
throw new JsonLdError(
'Invalid JSON-LD syntax; an element containing "@value" and "@type" ' +
'must have an absolute IRI for the value of "@type".',
'jsonld.SyntaxError', {code: 'invalid typed value', element: rval});
}
} else if('@type' in rval && !_isArray(rval['@type'])) {
// convert @type to an array
rval['@type'] = [rval['@type']];
} else if('@set' in rval || '@list' in rval) {
// handle @set and @list
if(count > 1 && !(count === 2 && '@index' in rval)) {
throw new JsonLdError(
'Invalid JSON-LD syntax; if an element has the property "@set" ' +
'or "@list", then it can have at most one other property that is ' +
'"@index".', 'jsonld.SyntaxError',
{code: 'invalid set or list object', element: rval});
}
// optimize away @set
if('@set' in rval) {
rval = rval['@set'];
keys = Object.keys(rval);
count = keys.length;
}
} else if(count === 1 && '@language' in rval) {
// drop objects with only @language
// FIXME
if(options.eventHandler) {
_handleEvent({
event: {
type: ['JsonLdEvent'],
code: 'object with only @language',
level: 'warning',
message: 'Dropping object with only @language.',
details: {
value: rval
}
},
options
});
}
rval = null;
}
// drop certain top-level objects that do not occur in lists
if(_isObject(rval) &&
!options.keepFreeFloatingNodes && !insideList &&
(activeProperty === null ||
expandedActiveProperty === '@graph' ||
(_getContextValue(activeCtx, activeProperty, '@container') || [])
.includes('@graph')
)) {
// drop empty object, top-level @value/@list, or object with only @id
rval = _dropUnsafeObject({value: rval, count, options});
}
return rval;
};
/**
* Drop empty object, top-level @value/@list, or object with only @id
*
* @param value Value to check.
* @param count Number of properties in object.
* @param options The expansion options.
*
* @return null if dropped, value otherwise.
*/
function _dropUnsafeObject({
value,
count,
options
}) {
if(count === 0 || '@value' in value || '@list' in value ||
(count === 1 && '@id' in value)) {
// FIXME
if(options.eventHandler) {
// FIXME: one event or diff event for empty, @v/@l, {@id}?
let code;
let message;
if(count === 0) {
code = 'empty object';
message = 'Dropping empty object.';
} else if('@value' in value) {
code = 'object with only @value';
message = 'Dropping object with only @value.';
} else if('@list' in value) {
code = 'object with only @list';
message = 'Dropping object with only @list.';
} else if(count === 1 && '@id' in value) {
code = 'object with only @id';
message = 'Dropping object with only @id.';
}
_handleEvent({
event: {
type: ['JsonLdEvent'],
code,
level: 'warning',
message,
details: {
value
}
},
options
});
}
return null;
}
return value;
}
/**
* Expand each key and value of element adding to result
*
* @param activeCtx the context to use.
* @param activeProperty the property for the element.
* @param expandedActiveProperty the expansion of activeProperty
* @param element the element to expand.
* @param expandedParent the expanded result into which to add values.
* @param options the expansion options.
* @param insideList true if the element is a list, false if not.
* @param typeKey first key found expanding to @type.
* @param typeScopedContext the context before reverting.
*/
async function _expandObject({
activeCtx,
activeProperty,
expandedActiveProperty,
element,
expandedParent,
options = {},
insideList,
typeKey,
typeScopedContext
}) {
const keys = Object.keys(element).sort();
const nests = [];
let unexpandedValue;
// Figure out if this is the type for a JSON literal
const isJsonType = element[typeKey] &&
_expandIri(activeCtx,
(_isArray(element[typeKey]) ? element[typeKey][0] : element[typeKey]),
{vocab: true}, {
...options,
typeExpansion: true
}) === '@json';
for(const key of keys) {
let value = element[key];
let expandedValue;
// skip @context
if(key === '@context') {
continue;
}
// expand property
const expandedProperty = _expandIri(activeCtx, key, {vocab: true}, options);
// drop non-absolute IRI keys that aren't keywords
if(expandedProperty === null ||
!(_isAbsoluteIri(expandedProperty) || _isKeyword(expandedProperty))) {
if(options.eventHandler) {
_handleEvent({
event: {
type: ['JsonLdEvent'],
code: 'invalid property',
level: 'warning',
message: 'Dropping property that did not expand into an ' +
'absolute IRI or keyword.',
details: {
property: key,
expandedProperty
}
},
options
});
}
continue;
}
if(_isKeyword(expandedProperty)) {
if(expandedActiveProperty === '@reverse') {
throw new JsonLdError(
'Invalid JSON-LD syntax; a keyword cannot be used as a @reverse ' +
'property.', 'jsonld.SyntaxError',
{code: 'invalid reverse property map', value});
}
if(expandedProperty in expandedParent &&
expandedProperty !== '@included' &&
expandedProperty !== '@type') {
throw new JsonLdError(
'Invalid JSON-LD syntax; colliding keywords detected.',
'jsonld.SyntaxError',
{code: 'colliding keywords', keyword: expandedProperty});
}
}
// syntax error if @id is not a string
if(expandedProperty === '@id') {
if(!_isString(value)) {
if(!options.isFrame) {
throw new JsonLdError(
'Invalid JSON-LD syntax; "@id" value must a string.',
'jsonld.SyntaxError', {code: 'invalid @id value', value});
}
if(_isObject(value)) {
// empty object is a wildcard
if(!_isEmptyObject(value)) {
throw new JsonLdError(
'Invalid JSON-LD syntax; "@id" value an empty object or array ' +
'of strings, if framing',
'jsonld.SyntaxError', {code: 'invalid @id value', value});
}
} else if(_isArray(value)) {
if(!value.every(v => _isString(v))) {
throw new JsonLdError(
'Invalid JSON-LD syntax; "@id" value an empty object or array ' +
'of strings, if framing',
'jsonld.SyntaxError', {code: 'invalid @id value', value});
}
} else {
throw new JsonLdError(
'Invalid JSON-LD syntax; "@id" value an empty object or array ' +
'of strings, if framing',
'jsonld.SyntaxError', {code: 'invalid @id value', value});
}
}
_addValue(
expandedParent, '@id',
_asArray(value).map(v => {
if(_isString(v)) {
const ve = _expandIri(activeCtx, v, {base: true}, options);
if(options.eventHandler) {
if(ve === null) {
// NOTE: spec edge case
// See https://github.com/w3c/json-ld-api/issues/480
if(v === null) {
_handleEvent({
event: {
type: ['JsonLdEvent'],
code: 'null @id value',
level: 'warning',
message: 'Null @id found.',
details: {
id: v
}
},
options
});
} else {
// matched KEYWORD regex
_handleEvent({
event: {
type: ['JsonLdEvent'],
code: 'reserved @id value',
level: 'warning',
message: 'Reserved @id found.',
details: {
id: v
}
},
options
});
}
} else if(!_isAbsoluteIri(ve)) {
_handleEvent({
event: {
type: ['JsonLdEvent'],
code: 'relative @id reference',
level: 'warning',
message: 'Relative @id reference found.',
details: {
id: v,
expandedId: ve
}
},
options
});
}
}
return ve;
}
return v;
}),
{propertyIsArray: options.isFrame});
continue;
}
if(expandedProperty === '@type') {
// if framing, can be a default object, but need to expand
// key to determine that
if(_isObject(value)) {
value = Object.fromEntries(Object.entries(value).map(([k, v]) => [
_expandIri(typeScopedContext, k, {vocab: true}),
_asArray(v).map(vv =>
_expandIri(typeScopedContext, vv, {base: true, vocab: true},
{...options, typeExpansion: true})
)
]));
}
_validateTypeValue(value, options.isFrame);
_addValue(
expandedParent, '@type',
_asArray(value).map(v => {
if(_isString(v)) {
const ve = _expandIri(typeScopedContext, v,
{base: true, vocab: true},
{...options, typeExpansion: true});
if(ve !== '@json' && !_isAbsoluteIri(ve)) {
if(options.eventHandler) {
_handleEvent({
event: {
type: ['JsonLdEvent'],
code: 'relative @type reference',
level: 'warning',
message: 'Relative @type reference found.',
details: {
type: v
}
},
options
});
}
}
return ve;
}
return v;
}),
{propertyIsArray: !!options.isFrame});
continue;
}
// Included blocks are treated as an array of separate object nodes sharing
// the same referencing active_property.
// For 1.0, it is skipped as are other unknown keywords
if(expandedProperty === '@included' && _processingMode(activeCtx, 1.1)) {
const includedResult = _asArray(await api.expand({
activeCtx,
activeProperty,
element: value,
options
}));
// Expanded values must be node objects
if(!includedResult.every(v => _isSubject(v))) {
throw new JsonLdError(
'Invalid JSON-LD syntax; ' +
'values of @included must expand to node objects.',
'jsonld.SyntaxError', {code: 'invalid @included value', value});
}
_addValue(
expandedParent, '@included', includedResult, {propertyIsArray: true});
continue;
}
// @graph must be an array or an object
if(expandedProperty === '@graph' &&
!(_isObject(value) || _isArray(value))) {
throw new JsonLdError(
'Invalid JSON-LD syntax; "@graph" value must not be an ' +
'object or an array.',
'jsonld.SyntaxError', {code: 'invalid @graph value', value});
}
if(expandedProperty === '@value') {
// capture value for later
// "colliding keywords" check prevents this from being set twice
unexpandedValue = value;
if(isJsonType && _processingMode(activeCtx, 1.1)) {
// no coercion to array, and retain all values
expandedParent['@value'] = value;
} else {
_addValue(
expandedParent, '@value', value, {propertyIsArray: options.isFrame});
}
continue;
}
// @language must be a string
// it should match BCP47
if(expandedProperty === '@language') {
if(value === null) {
// drop null @language values, they expand as if they didn't exist
continue;
}
if(!_isString(value) && !options.isFrame) {
throw new JsonLdError(
'Invalid JSON-LD syntax; "@language" value must be a string.',
'jsonld.SyntaxError',
{code: 'invalid language-tagged string', value});
}
// ensure language value is lowercase
value = _asArray(value).map(v => _isString(v) ? v.toLowerCase() : v);
// ensure language tag matches BCP47
for(const language of value) {
if(_isString(language) && !language.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
}
},
options
});
}
}
}
_addValue(
expandedParent, '@language', value, {propertyIsArray: options.isFrame});
continue;
}
// @direction must be "ltr" or "rtl"
if(expandedProperty === '@direction') {
if(!_isString(value) && !options.isFrame) {
throw new JsonLdError(
'Invalid JSON-LD syntax; "@direction" value must be a string.',
'jsonld.SyntaxError',
{code: 'invalid base direction', value});
}
value = _asArray(value);
// ensure direction is "ltr" or "rtl"
for(const dir of value) {
if(_isString(dir) && dir !== 'ltr' && dir !== 'rtl') {
throw new JsonLdError(
'Invalid JSON-LD syntax; "@direction" must be "ltr" or "rtl".',
'jsonld.SyntaxError',
{code: 'invalid base direction', value});
}
}
_addValue(
expandedParent, '@direction', value,
{propertyIsArray: options.isFrame});
continue;
}
// @index must be a string
if(expandedProperty === '@index') {
if(!_isString(value)) {
throw new JsonLdError(
'Invalid JSON-LD syntax; "@index" value must be a string.',
'jsonld.SyntaxError',
{code: 'invalid @index value', value});
}
_addValue(expandedParent, '@index', value);
continue;
}
// @reverse must be an object
if(expandedProperty === '@reverse') {
if(!_isObject(value)) {
throw new JsonLdError(
'Invalid JSON-LD syntax; "@reverse" value must be an object.',
'jsonld.SyntaxError', {code: 'invalid @reverse value', value});
}
expandedValue = await api.expand({
activeCtx,
activeProperty: '@reverse',
element: value,
options
});
// properties double-reversed
if('@reverse' in expandedValue) {
for(const property in expandedValue['@reverse']) {
_addValue(
expandedParent, property, expandedValue['@reverse'][property],
{propertyIsArray: true});
}
}
// FIXME: can this be merged with code below to simplify?
// merge in all reversed properties
let reverseMap = expandedParent['@reverse'] || null;
for(const property in expandedValue) {
if(property === '@reverse') {
continue;
}
if(reverseMap === null) {
reverseMap = expandedParent['@reverse'] = {};
}
_addValue(reverseMap, property, [], {propertyIsArray: true});
const items = expandedValue[property];
for(let ii = 0; ii < items.length; ++ii) {
const item = items[ii];
if(_isValue(item) || _isList(item)) {
throw new JsonLdError(
'Invalid JSON-LD syntax; "@reverse" value must not be a ' +
'@value or an @list.', 'jsonld.SyntaxError',
{code: 'invalid reverse property value', value: expandedValue});
}
_addValue(reverseMap, property, item, {propertyIsArray: true});
}
}
continue;
}
// nested keys
if(expandedProperty === '@nest') {
nests.push(key);
continue;
}
// use potential scoped context for key
let termCtx = activeCtx;
const ctx = _getContextValue(activeCtx, key, '@context');
if(!_isUndefined(ctx)) {
termCtx = await _processContext({
activeCtx,
localCtx: ctx,
propagate: true,
overrideProtected: true,
options
});
}
const container = _getContextValue(activeCtx, key, '@container') || [];
if(container.includes('@language') && _isObject(value)) {
const direction = _getContextValue(termCtx, key, '@direction');
// handle language map container (skip if value is not an object)
expandedValue = _expandLanguageMap(termCtx, value, direction, options);
} else if(container.includes('@index') && _isObject(value)) {
// handle index container (skip if value is not an object)
const asGraph = container.includes('@graph');
const indexKey = _getContextValue(termCtx, key, '@index') || '@index';
const propertyIndex = indexKey !== '@index' &&
_expandIri(activeCtx, indexKey, {vocab: true}, options);
expandedValue = await _expandIndexMap({
activeCtx: termCtx,
options,
activeProperty: key,
value,
asGraph,
indexKey,
propertyIndex
});
} else if(container.includes('@id') && _isObject(value)) {
// handle id container (skip if value is not an object)
const asGraph = container.includes('@graph');
expandedValue = await _expandIndexMap({
activeCtx: termCtx,
options,
activeProperty: key,
value,
asGraph,
indexKey: '@id'
});
} else if(container.includes('@type') && _isObject(value)) {
// handle type container (skip if value is not an object)
expandedValue = await _expandIndexMap({
// since container is `@type`, revert type scoped context when expanding
activeCtx: termCtx.revertToPreviousContext(),
options,
activeProperty: key,
value,
asGraph: false,
indexKey: '@type'
});
} else {
// recurse into @list or @set
const isList = expandedProperty === '@list';
if(isList || expandedProperty === '@set') {
let nextActiveProperty = activeProperty;
if(isList && expandedActiveProperty === '@graph') {
nextActiveProperty = null;
}
expandedValue = await api.expand({
activeCtx: termCtx,
activeProperty: nextActiveProperty,
element: value,
options,
insideList: isList
});
} else if(
_getContextValue(activeCtx, key, '@type') === '@json') {
expandedValue = {
'@type': '@json',
'@value': value
};
} else {
// recursively expand value with key as new active property
expandedValue = await api.expand({
activeCtx: termCtx,
activeProperty: key,
element: value,
options,
insideList: false
});
}
}
// drop null values if property is not @value
if(expandedValue === null && expandedProperty !== '@value') {
// FIXME: event?
//unmappedValue: value,
//expandedProperty,
//key,
continue;
}
// convert expanded value to @list if container specifies it
if(expandedProperty !== '@list' && !_isList(expandedValue) &&
container.includes('@list')) {
// ensure expanded value in @list is an array
expandedValue = {'@list': _asArray(expandedValue)};
}
// convert expanded value to @graph if container specifies it
// and value is not, itself, a graph
// index cases handled above
if(container.includes('@graph') &&
!container.some(key => key === '@id' || key === '@index')) {
// ensure expanded values are in an array
expandedValue = _asArray(expandedValue);
if(!options.isFrame) {
// drop items if needed
expandedValue = expandedValue.filter(v => {
const count = Object.keys(v).length;
return _dropUnsafeObject({value: v, count, options}) !== null;
});
}
if(expandedValue.length === 0) {
// all items dropped, skip adding and continue
continue;
}
// convert to graph
expandedValue = expandedValue.map(v => ({'@graph': _asArray(v)}));
}
// FIXME: can this be merged with code above to simplify?
// merge in reverse properties
if(termCtx.mappings.has(key) && termCtx.mappings.get(key).reverse) {
const reverseMap =
expandedParent['@reverse'] = expandedParent['@reverse'] || {};
expandedValue = _asArray(expandedValue);
for(let ii = 0; ii < expandedValue.length; ++ii) {
const item = expandedValue[ii];
if(_isValue(item) || _isList(item)) {
throw new JsonLdError(
'Invalid JSON-LD syntax; "@reverse" value must not be a ' +
'@value or an @list.', 'jsonld.SyntaxError',
{code: 'invalid reverse property value', value: expandedValue});
}
_addValue(reverseMap, expandedProperty, item, {propertyIsArray: true});
}
continue;
}
// add value for property
// special keywords handled above
_addValue(expandedParent, expandedProperty, expandedValue, {
propertyIsArray: true
});
}
// @value must not be an object or an array (unless framing) or if @type is