-
Notifications
You must be signed in to change notification settings - Fork 198
/
compact.js
1062 lines (969 loc) · 33.6 KB
/
compact.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,
isString: _isString
} = require('./types');
const {
isList: _isList,
isValue: _isValue,
isGraph: _isGraph,
isSimpleGraph: _isSimpleGraph,
isSubjectReference: _isSubjectReference
} = require('./graphTypes');
const {
expandIri: _expandIri,
getContextValue: _getContextValue,
isKeyword: _isKeyword,
process: _processContext
} = require('./context');
const {
removeBase: _removeBase
} = require('./url');
const {
addValue: _addValue,
compareShortestLeast: _compareShortestLeast
} = require('./util');
const api = {};
module.exports = api;
/**
* Recursively compacts an element using the given active context. All values
* must be in expanded form before this method is called.
*
* @param activeCtx the active context to use.
* @param activeProperty the compacted property associated with the element
* to compact, null for none.
* @param element the element to compact.
* @param options the compaction options.
* @param compactionMap the compaction map to use.
*
* @return the compacted value.
*/
api.compact = ({
activeCtx,
activeProperty = null,
element,
options = {},
compactionMap = () => undefined
}) => {
// recursively compact array
if(_isArray(element)) {
let rval = [];
for(let i = 0; i < element.length; ++i) {
// compact, dropping any null values unless custom mapped
let compacted = api.compact({
activeCtx,
activeProperty,
element: element[i],
options,
compactionMap
});
if(compacted === null) {
// TODO: use `await` to support async
compacted = compactionMap({
unmappedValue: element[i],
activeCtx,
activeProperty,
parent: element,
index: i,
options
});
if(compacted === undefined) {
continue;
}
}
rval.push(compacted);
}
if(options.compactArrays && rval.length === 1) {
// use single element if no container is specified
const container = _getContextValue(
activeCtx, activeProperty, '@container') || [];
if(container.length === 0) {
rval = rval[0];
}
}
return rval;
}
// use any scoped context on activeProperty
const ctx = _getContextValue(activeCtx, activeProperty, '@context');
if(ctx) {
activeCtx = _processContext({activeCtx, localCtx: ctx, options});
}
// recursively compact object
if(_isObject(element)) {
if(options.link && '@id' in element && element['@id'] in options.link) {
// check for a linked element to reuse
const linked = options.link[element['@id']];
for(let i = 0; i < linked.length; ++i) {
if(linked[i].expanded === element) {
return linked[i].compacted;
}
}
}
// do value compaction on @values and subject references
if(_isValue(element) || _isSubjectReference(element)) {
const rval =
api.compactValue({activeCtx, activeProperty, value: element});
if(options.link && _isSubjectReference(element)) {
// store linked element
if(!(element['@id'] in options.link)) {
options.link[element['@id']] = [];
}
options.link[element['@id']].push({expanded: element, compacted: rval});
}
return rval;
}
// FIXME: avoid misuse of active property as an expanded property?
const insideReverse = (activeProperty === '@reverse');
const rval = {};
if(options.link && '@id' in element) {
// store linked element
if(!(element['@id'] in options.link)) {
options.link[element['@id']] = [];
}
options.link[element['@id']].push({expanded: element, compacted: rval});
}
// apply any context defined on an alias of @type
// if key is @type and any compacted value is a term having a local
// context, overlay that context
const types = element['@type'] || [];
for(const type of types) {
const compactedType = api.compactIri(
{activeCtx, iri: type, relativeTo: {vocab: true}});
// Use any scoped context defined on this value
const ctx = _getContextValue(activeCtx, compactedType, '@context');
if(ctx) {
activeCtx = _processContext({activeCtx, localCtx: ctx, options});
}
}
// process element keys in order
const keys = Object.keys(element).sort();
for(const expandedProperty of keys) {
const expandedValue = element[expandedProperty];
// compact @id and @type(s)
if(expandedProperty === '@id' || expandedProperty === '@type') {
let compactedValue = [].concat(expandedValue).map(
expandedIri => api.compactIri({
activeCtx,
iri: expandedIri,
relativeTo: {
vocab: expandedProperty === '@type'
}
}));
if(compactedValue.length === 1) {
compactedValue = compactedValue[0];
}
// use keyword alias and add value
const alias = api.compactIri(
{activeCtx, iri: expandedProperty, relativeTo: {vocab: true}});
const isArray = _isArray(compactedValue) && expandedValue.length === 0;
_addValue(rval, alias, compactedValue, {propertyIsArray: isArray});
continue;
}
// handle @reverse
if(expandedProperty === '@reverse') {
// recursively compact expanded value
const compactedValue = api.compact({
activeCtx,
activeProperty: '@reverse',
element: expandedValue,
options,
compactionMap
});
// handle double-reversed properties
for(const compactedProperty in compactedValue) {
if(activeCtx.mappings[compactedProperty] &&
activeCtx.mappings[compactedProperty].reverse) {
const value = compactedValue[compactedProperty];
const container = _getContextValue(
activeCtx, compactedProperty, '@container') || [];
const useArray = (
container.includes('@set') || !options.compactArrays);
_addValue(
rval, compactedProperty, value, {propertyIsArray: useArray});
delete compactedValue[compactedProperty];
}
}
if(Object.keys(compactedValue).length > 0) {
// use keyword alias and add value
const alias = api.compactIri({
activeCtx,
iri: expandedProperty,
relativeTo: {vocab: true}
});
_addValue(rval, alias, compactedValue);
}
continue;
}
if(expandedProperty === '@preserve') {
// compact using activeProperty
const compactedValue = api.compact({
activeCtx,
activeProperty,
element: expandedValue,
options,
compactionMap});
if(!(_isArray(compactedValue) && compactedValue.length === 0)) {
_addValue(rval, expandedProperty, compactedValue);
}
continue;
}
// handle @index property
if(expandedProperty === '@index') {
// drop @index if inside an @index container
const container = _getContextValue(
activeCtx, activeProperty, '@container') || [];
if(container.includes('@index')) {
continue;
}
// use keyword alias and add value
const alias = api.compactIri({
activeCtx,
iri: expandedProperty,
relativeTo: {vocab: true}
});
_addValue(rval, alias, expandedValue);
continue;
}
// skip array processing for keywords that aren't @graph or @list
if(expandedProperty !== '@graph' && expandedProperty !== '@list' &&
_isKeyword(expandedProperty)) {
// use keyword alias and add value as is
const alias = api.compactIri({
activeCtx,
iri: expandedProperty,
relativeTo: {vocab: true}
});
_addValue(rval, alias, expandedValue);
continue;
}
// Note: expanded value must be an array due to expansion algorithm.
if(!_isArray(expandedValue)) {
throw new JsonLdError(
'JSON-LD expansion error; expanded value must be an array.',
'jsonld.SyntaxError');
}
// preserve empty arrays
if(expandedValue.length === 0) {
const itemActiveProperty = api.compactIri({
activeCtx,
iri: expandedProperty,
value: expandedValue,
relativeTo: {vocab: true},
reverse: insideReverse
});
const nestProperty = (itemActiveProperty in activeCtx.mappings) ?
activeCtx.mappings[itemActiveProperty]['@nest'] : null;
let nestResult = rval;
if(nestProperty) {
_checkNestProperty(activeCtx, nestProperty);
if(!_isObject(rval[nestProperty])) {
rval[nestProperty] = {};
}
nestResult = rval[nestProperty];
}
_addValue(
nestResult, itemActiveProperty, expandedValue, {
propertyIsArray: true
});
}
// recusively process array values
for(const expandedItem of expandedValue) {
// compact property and get container type
const itemActiveProperty = api.compactIri({
activeCtx,
iri: expandedProperty,
value: expandedItem,
relativeTo: {vocab: true},
reverse: insideReverse
});
// if itemActiveProperty is a @nest property, add values to nestResult,
// otherwise rval
const nestProperty = (itemActiveProperty in activeCtx.mappings) ?
activeCtx.mappings[itemActiveProperty]['@nest'] : null;
let nestResult = rval;
if(nestProperty) {
_checkNestProperty(activeCtx, nestProperty);
if(!_isObject(rval[nestProperty])) {
rval[nestProperty] = {};
}
nestResult = rval[nestProperty];
}
const container = _getContextValue(
activeCtx, itemActiveProperty, '@container') || [];
// get simple @graph or @list value if appropriate
const isGraph = _isGraph(expandedItem);
const isList = _isList(expandedItem);
let inner;
if(isList) {
inner = expandedItem['@list'];
} else if(isGraph) {
inner = expandedItem['@graph'];
}
// recursively compact expanded item
let compactedItem = api.compact({
activeCtx,
activeProperty: itemActiveProperty,
element: (isList || isGraph) ? inner : expandedItem,
options,
compactionMap
});
// handle @list
if(isList) {
// ensure @list value is an array
if(!_isArray(compactedItem)) {
compactedItem = [compactedItem];
}
if(!container.includes('@list')) {
// wrap using @list alias
compactedItem = {
[api.compactIri({
activeCtx,
iri: '@list',
relativeTo: {vocab: true}
})]: compactedItem
};
// include @index from expanded @list, if any
if('@index' in expandedItem) {
compactedItem[api.compactIri({
activeCtx,
iri: '@index',
relativeTo: {vocab: true}
})] = expandedItem['@index'];
}
} else if(itemActiveProperty in nestResult) {
// can't use @list container for more than 1 list
throw new JsonLdError(
'JSON-LD compact error; property has a "@list" @container ' +
'rule but there is more than a single @list that matches ' +
'the compacted term in the document. Compaction might mix ' +
'unwanted items into the list.',
'jsonld.SyntaxError', {code: 'compaction to list of lists'});
}
}
// Graph object compaction cases
if(isGraph) {
if(container.includes('@graph') && (container.includes('@id') ||
container.includes('@index') && _isSimpleGraph(expandedItem))) {
// get or create the map object
let mapObject;
if(itemActiveProperty in nestResult) {
mapObject = nestResult[itemActiveProperty];
} else {
nestResult[itemActiveProperty] = mapObject = {};
}
// index on @id or @index or alias of @none
const key = (container.includes('@id') ?
expandedItem['@id'] : expandedItem['@index']) ||
api.compactIri({activeCtx, iri: '@none', vocab: true});
// add compactedItem to map, using value of `@id` or a new blank
// node identifier
_addValue(
mapObject, key, compactedItem, {
propertyIsArray:
(!options.compactArrays || container.includes('@set'))
});
} else if(container.includes('@graph') &&
_isSimpleGraph(expandedItem)) {
// container includes @graph but not @id or @index and value is a
// simple graph object add compact value
_addValue(
nestResult, itemActiveProperty, compactedItem, {
propertyIsArray:
(!options.compactArrays || container.includes('@set'))
});
} else {
// wrap using @graph alias, remove array if only one item and
// compactArrays not set
if(_isArray(compactedItem) && compactedItem.length === 1 &&
options.compactArrays) {
compactedItem = compactedItem[0];
}
compactedItem = {
[api.compactIri({
activeCtx,
iri: '@graph',
relativeTo: {vocab: true}
})]: compactedItem
};
// include @id from expanded graph, if any
if('@id' in expandedItem) {
compactedItem[api.compactIri({
activeCtx,
iri: '@id',
relativeTo: {vocab: true}
})] = expandedItem['@id'];
}
// include @index from expanded graph, if any
if('@index' in expandedItem) {
compactedItem[api.compactIri({
activeCtx,
iri: '@index',
relativeTo: {vocab: true}
})] = expandedItem['@index'];
}
_addValue(
nestResult, itemActiveProperty, compactedItem, {
propertyIsArray:
(!options.compactArrays || container.includes('@set'))
});
}
} else if(container.includes('@language') ||
container.includes('@index') || container.includes('@id') ||
container.includes('@type')) {
// handle language and index maps
// get or create the map object
let mapObject;
if(itemActiveProperty in nestResult) {
mapObject = nestResult[itemActiveProperty];
} else {
nestResult[itemActiveProperty] = mapObject = {};
}
let key;
if(container.includes('@language')) {
// if container is a language map, simplify compacted value to
// a simple string
if(_isValue(compactedItem)) {
compactedItem = compactedItem['@value'];
}
key = expandedItem['@language'];
} else if(container.includes('@index')) {
key = expandedItem['@index'];
} else if(container.includes('@id')) {
const idKey = api.compactIri({activeCtx, iri: '@id', vocab: true});
key = compactedItem[idKey];
delete compactedItem[idKey];
} else if(container.includes('@type')) {
const typeKey = api.compactIri({
activeCtx,
iri: '@type',
vocab: true
});
let types;
[key, ...types] = [].concat(compactedItem[typeKey] || []);
switch(types.length) {
case 0:
delete compactedItem[typeKey];
break;
case 1:
compactedItem[typeKey] = types[0];
break;
default:
compactedItem[typeKey] = types;
break;
}
}
// if compacting this value which has no key, index on @none
if(!key) {
key = api.compactIri({activeCtx, iri: '@none', vocab: true});
}
// add compact value to map object using key from expanded value
// based on the container type
_addValue(
mapObject, key, compactedItem, {
propertyIsArray: container.includes('@set')
});
} else {
// use an array if: compactArrays flag is false,
// @container is @set or @list , value is an empty
// array, or key is @graph
const isArray = (!options.compactArrays ||
container.includes('@set') || container.includes('@list') ||
(_isArray(compactedItem) && compactedItem.length === 0) ||
expandedProperty === '@list' || expandedProperty === '@graph');
// add compact value
_addValue(
nestResult, itemActiveProperty, compactedItem,
{propertyIsArray: isArray});
}
}
}
return rval;
}
// only primitives remain which are already compact
return element;
};
/**
* Compacts an IRI or keyword into a term or prefix if it can be. If the
* IRI has an associated value it may be passed.
*
* @param activeCtx the active context to use.
* @param iri the IRI to compact.
* @param value the value to check or null.
* @param relativeTo options for how to compact IRIs:
* vocab: true to split after @vocab, false not to.
* @param reverse true if a reverse property is being compacted, false if not.
*
* @return the compacted term, prefix, keyword alias, or the original IRI.
*/
api.compactIri = ({
activeCtx,
iri,
value = null,
relativeTo = {vocab: false},
reverse = false
}) => {
// can't compact null
if(iri === null) {
return iri;
}
const inverseCtx = activeCtx.getInverse();
// if term is a keyword, it may be compacted to a simple alias
if(_isKeyword(iri) &&
iri in inverseCtx &&
'@none' in inverseCtx[iri] &&
'@type' in inverseCtx[iri]['@none'] &&
'@none' in inverseCtx[iri]['@none']['@type']) {
return inverseCtx[iri]['@none']['@type']['@none'];
}
// use inverse context to pick a term if iri is relative to vocab
if(relativeTo.vocab && iri in inverseCtx) {
const defaultLanguage = activeCtx['@language'] || '@none';
// prefer @index if available in value
const containers = [];
if(_isObject(value) && '@index' in value && !('@graph' in value)) {
containers.push('@index', '@index@set');
}
// if value is a preserve object, use its value
if(_isObject(value) && '@preserve' in value) {
value = value['@preserve'][0];
}
// prefer most specific container including @graph, prefering @set
// variations
if(_isGraph(value)) {
// favor indexmap if the graph is indexed
if('@index' in value) {
containers.push(
'@graph@index', '@graph@index@set', '@index', '@index@set');
}
// favor idmap if the graph is has an @id
if('@id' in value) {
containers.push(
'@graph@id', '@graph@id@set');
}
containers.push('@graph', '@graph@set', '@set');
// allow indexmap if the graph is not indexed
if(!('@index' in value)) {
containers.push(
'@graph@index', '@graph@index@set', '@index', '@index@set');
}
// allow idmap if the graph does not have an @id
if(!('@id' in value)) {
containers.push('@graph@id', '@graph@id@set');
}
} else if(_isObject(value) && !_isValue(value)) {
containers.push('@id', '@id@set', '@type', '@set@type');
}
// defaults for term selection based on type/language
let typeOrLanguage = '@language';
let typeOrLanguageValue = '@null';
if(reverse) {
typeOrLanguage = '@type';
typeOrLanguageValue = '@reverse';
containers.push('@set');
} else if(_isList(value)) {
// choose the most specific term that works for all elements in @list
// only select @list containers if @index is NOT in value
if(!('@index' in value)) {
containers.push('@list');
}
const list = value['@list'];
if(list.length === 0) {
// any empty list can be matched against any term that uses the
// @list container regardless of @type or @language
typeOrLanguage = '@any';
typeOrLanguageValue = '@none';
} else {
let commonLanguage = (list.length === 0) ? defaultLanguage : null;
let commonType = null;
for(let i = 0; i < list.length; ++i) {
const item = list[i];
let itemLanguage = '@none';
let itemType = '@none';
if(_isValue(item)) {
if('@language' in item) {
itemLanguage = item['@language'];
} else if('@type' in item) {
itemType = item['@type'];
} else {
// plain literal
itemLanguage = '@null';
}
} else {
itemType = '@id';
}
if(commonLanguage === null) {
commonLanguage = itemLanguage;
} else if(itemLanguage !== commonLanguage && _isValue(item)) {
commonLanguage = '@none';
}
if(commonType === null) {
commonType = itemType;
} else if(itemType !== commonType) {
commonType = '@none';
}
// there are different languages and types in the list, so choose
// the most generic term, no need to keep iterating the list
if(commonLanguage === '@none' && commonType === '@none') {
break;
}
}
commonLanguage = commonLanguage || '@none';
commonType = commonType || '@none';
if(commonType !== '@none') {
typeOrLanguage = '@type';
typeOrLanguageValue = commonType;
} else {
typeOrLanguageValue = commonLanguage;
}
}
} else {
if(_isValue(value)) {
if('@language' in value && !('@index' in value)) {
containers.push('@language', '@language@set');
typeOrLanguageValue = value['@language'];
} else if('@type' in value) {
typeOrLanguage = '@type';
typeOrLanguageValue = value['@type'];
}
} else {
typeOrLanguage = '@type';
typeOrLanguageValue = '@id';
}
containers.push('@set');
}
// do term selection
containers.push('@none');
// an index map can be used to index values using @none, so add as a low
// priority
if(_isObject(value) && !('@index' in value)) {
// allow indexing even if no @index present
containers.push('@index', '@index@set');
}
// values without type or language can use @language map
if(_isValue(value) && Object.keys(value).length === 1) {
// allow indexing even if no @index present
containers.push('@language', '@language@set');
}
const term = _selectTerm(
activeCtx, iri, value, containers, typeOrLanguage, typeOrLanguageValue);
if(term !== null) {
return term;
}
}
// no term match, use @vocab if available
if(relativeTo.vocab) {
if('@vocab' in activeCtx) {
// determine if vocab is a prefix of the iri
const vocab = activeCtx['@vocab'];
if(iri.indexOf(vocab) === 0 && iri !== vocab) {
// use suffix as relative iri if it is not a term in the active context
const suffix = iri.substr(vocab.length);
if(!(suffix in activeCtx.mappings)) {
return suffix;
}
}
}
}
// no term or @vocab match, check for possible CURIEs
let choice = null;
// TODO: make FastCurieMap a class with a method to do this lookup
const partialMatches = [];
let iriMap = activeCtx.fastCurieMap;
// check for partial matches of against `iri`, which means look until
// iri.length - 1, not full length
const maxPartialLength = iri.length - 1;
for(let i = 0; i < maxPartialLength && iri[i] in iriMap; ++i) {
iriMap = iriMap[iri[i]];
if('' in iriMap) {
partialMatches.push(iriMap[''][0]);
}
}
// check partial matches in reverse order to prefer longest ones first
for(let i = partialMatches.length - 1; i >= 0; --i) {
const entry = partialMatches[i];
const terms = entry.terms;
for(const term of terms) {
// a CURIE is usable if:
// 1. it has no mapping, OR
// 2. value is null, which means we're not compacting an @value, AND
// the mapping matches the IRI
const curie = term + ':' + iri.substr(entry.iri.length);
const isUsableCurie = (activeCtx.mappings[term]._prefix &&
(!(curie in activeCtx.mappings) ||
(value === null && activeCtx.mappings[curie]['@id'] === iri)));
// select curie if it is shorter or the same length but lexicographically
// less than the current choice
if(isUsableCurie && (choice === null ||
_compareShortestLeast(curie, choice) < 0)) {
choice = curie;
}
}
}
// return chosen curie
if(choice !== null) {
return choice;
}
// compact IRI relative to base
if(!relativeTo.vocab) {
return _removeBase(activeCtx['@base'], iri);
}
// return IRI as is
return iri;
};
/**
* Performs value compaction on an object with '@value' or '@id' as the only
* property.
*
* @param activeCtx the active context.
* @param activeProperty the active property that points to the value.
* @param value the value to compact.
*
* @return the compaction result.
*/
api.compactValue = ({activeCtx, activeProperty, value}) => {
// value is a @value
if(_isValue(value)) {
// get context rules
const type = _getContextValue(activeCtx, activeProperty, '@type');
const language = _getContextValue(activeCtx, activeProperty, '@language');
const container =
_getContextValue(activeCtx, activeProperty, '@container') || [];
// whether or not the value has an @index that must be preserved
const preserveIndex = '@index' in value && !container.includes('@index');
// if there's no @index to preserve ...
if(!preserveIndex) {
// matching @type or @language specified in context, compact value
if(value['@type'] === type || value['@language'] === language) {
return value['@value'];
}
}
// return just the value of @value if all are true:
// 1. @value is the only key or @index isn't being preserved
// 2. there is no default language or @value is not a string or
// the key has a mapping with a null @language
const keyCount = Object.keys(value).length;
const isValueOnlyKey = (keyCount === 1 ||
(keyCount === 2 && '@index' in value && !preserveIndex));
const hasDefaultLanguage = ('@language' in activeCtx);
const isValueString = _isString(value['@value']);
const hasNullMapping = (activeCtx.mappings[activeProperty] &&
activeCtx.mappings[activeProperty]['@language'] === null);
if(isValueOnlyKey &&
(!hasDefaultLanguage || !isValueString || hasNullMapping)) {
return value['@value'];
}
const rval = {};
// preserve @index
if(preserveIndex) {
rval[api.compactIri({
activeCtx,
iri: '@index',
relativeTo: {vocab: true}
})] = value['@index'];
}
if('@type' in value) {
// compact @type IRI
rval[api.compactIri({
activeCtx,
iri: '@type',
relativeTo: {vocab: true}
})] = api.compactIri(
{activeCtx, iri: value['@type'], relativeTo: {vocab: true}});
} else if('@language' in value) {
// alias @language
rval[api.compactIri({
activeCtx,
iri: '@language',
relativeTo: {vocab: true}
})] = value['@language'];
}
// alias @value
rval[api.compactIri({
activeCtx,
iri: '@value',
relativeTo: {vocab: true}
})] = value['@value'];
return rval;
}
// value is a subject reference
const expandedProperty = _expandIri(activeCtx, activeProperty, {vocab: true});
const type = _getContextValue(activeCtx, activeProperty, '@type');
const compacted = api.compactIri(
{activeCtx, iri: value['@id'], relativeTo: {vocab: type === '@vocab'}});
// compact to scalar
if(type === '@id' || type === '@vocab' || expandedProperty === '@graph') {
return compacted;
}
return {
[api.compactIri({
activeCtx,
iri: '@id',
relativeTo: {vocab: true}
})]: compacted
};
};
/**
* Removes the @preserve keywords as the last step of the compaction
* algorithm when it is running on framed output.
*
* @param ctx the active context used to compact the input.
* @param input the framed, compacted output.
* @param options the compaction options used.
*
* @return the resulting output.
*/
api.removePreserve = (ctx, input, options) => {
// recurse through arrays
if(_isArray(input)) {
const output = [];
for(let i = 0; i < input.length; ++i) {
const result = api.removePreserve(ctx, input[i], options);
// drop nulls from arrays
if(result !== null) {
output.push(result);
}
}
input = output;
} else if(_isObject(input)) {
// remove @preserve
if('@preserve' in input) {
if(input['@preserve'] === '@null') {
return null;
}
return input['@preserve'];
}
// skip @values
if(_isValue(input)) {
return input;
}
// recurse through @lists
if(_isList(input)) {
input['@list'] = api.removePreserve(ctx, input['@list'], options);
return input;
}
// handle in-memory linked nodes
const idAlias = api.compactIri({
activeCtx: ctx,
iri: '@id',
relativeTo: {vocab: true}
});
if(idAlias in input) {
const id = input[idAlias];
if(id in options.link) {
const idx = options.link[id].indexOf(input);
if(idx !== -1) {
// already visited
return options.link[id][idx];
}
// prevent circular visitation
options.link[id].push(input);
} else {
// prevent circular visitation
options.link[id] = [input];
}
}
// recurse through properties
const graphAlias = api.compactIri({
activeCtx: ctx,
iri: '@graph',
relativeTo: {vocab: true}
});
for(const prop in input) {
// potentially remove the id, if it is an unreference bnode
if(prop === idAlias && options.bnodesToClear.includes(input[prop])) {
delete input[idAlias];
continue;
}
let result = api.removePreserve(ctx, input[prop], options);
const container = _getContextValue(ctx, prop, '@container') || [];
if(options.compactArrays && _isArray(result) && result.length === 1 &&
container.length === 0 && prop !== graphAlias) {
result = result[0];
}
input[prop] = result;
}
}
return input;
};
/**
* Picks the preferred compaction term from the given inverse context entry.
*
* @param activeCtx the active context.
* @param iri the IRI to pick the term for.
* @param value the value to pick the term for.
* @param containers the preferred containers.
* @param typeOrLanguage either '@type' or '@language'.
* @param typeOrLanguageValue the preferred value for '@type' or '@language'.
*
* @return the preferred term.
*/
function _selectTerm(
activeCtx, iri, value, containers, typeOrLanguage, typeOrLanguageValue) {
if(typeOrLanguageValue === null) {
typeOrLanguageValue = '@null';
}
// preferences for the value of @type or @language
const prefs = [];
// determine prefs for @id based on whether or not value compacts to a term