jsonld-compaction 0.23.6

JSON-LD document compaction implementation
Documentation
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
use crate::{
    CompactFragment,
    CompactIndexedFragment,
    Error,
    Options,
    add_value,
    compact_collection_with,
    compact_iri,
    compact_iri_with,
    compact_iri_with_memo,
    iri::{CompactIriMemo, keyword_alias},
    value_value,
};

use jsonld_core::{
    Container,
    ContainerKind,
    Context,
    Id,
    Indexed,
    Loader,
    Node,
    Object,
    Term,
    context::Nest,
    object::{self, List},
};
use jsonld_syntax::{Keyword, native_stack::Recursion};
use rdfx::vocabulary::VocabularyMut;
use std::hash::Hash;

/// Compacts a list object and adds it to `nest_result` under
/// `item_active_property`.
///
/// When the term's container mapping includes `@list` the list becomes a plain
/// array assigned directly to the key. Otherwise it is wrapped back into a list
/// object — a map holding whatever `@list` compacts to, plus `@index` when the
/// list carried one — and added with [`add_value`].
async fn compact_property_list<N, L>(
    vocabulary: &mut N,
    list: &List<N::Iri, N::BlankId>,
    expanded_index: Option<&str>,
    nest_result: &mut jstrict::Object,
    container: Container,
    as_array: bool,
    item_active_property: &str,
    active_context: &Context<N::Iri, N::BlankId>,
    loader: &L,
    options: Options,
) -> Result<(), Error<L::Error>>
where
    N: VocabularyMut,
    N::Iri: Clone + Hash + Eq,
    N::BlankId: Clone + Hash + Eq,
    L: Loader,
{
    // If expanded item is a list object:
    let mut compacted_item = Recursion::new(compact_collection_with(
        vocabulary,
        list.iter(),
        active_context,
        active_context,
        Some(item_active_property),
        loader,
        options,
    ))
    .await?;

    // If compacted item is not an array,
    // then set `compacted_item` to an array containing only `compacted_item`.
    if !compacted_item.is_array() {
        let array = vec![compacted_item];
        compacted_item = jstrict::Value::Array(array);
    }

    // If container does not include @list:
    if container.contains(ContainerKind::List) {
        // Otherwise, set the value of the item active property entry in nest result to compacted item.
        nest_result.insert(item_active_property.into(), compacted_item);
    } else {
        // Convert `compacted_item` to a list object by setting it to
        // a map containing an entry where the key is the result of
        // IRI compacting @list and the value is the original
        // compacted item.
        let key = keyword_alias(vocabulary, active_context, options, Keyword::List);
        let mut compacted_item_list_object = jstrict::Object::default();
        compacted_item_list_object.insert(key.into(), compacted_item);

        // If `expanded_item` contains the entry @index-value,
        // then add an entry to compacted item where the key is
        // the result of IRI compacting @index and value is value.
        if let Some(index) = expanded_index {
            let key = keyword_alias(vocabulary, active_context, options, Keyword::Index);

            compacted_item_list_object.insert(key.into(), jstrict::Value::String(index.into()));
        }

        compacted_item = jstrict::Value::Object(compacted_item_list_object);

        // Use add value to add `compacted_item` to
        // the `item_active_property` entry in `nest_result` using `as_array`.
        add_value(nest_result, item_active_property, compacted_item, as_array);
    }

    Ok(())
}

/// Compacts a graph object and adds it to `nest_result` under
/// `item_active_property`.
///
/// The shape depends on the term's container mapping: `@graph`+`@id` and
/// `@graph`+`@index` turn the key into a map keyed by the graph's `@id` or
/// `@index`; a plain `@graph` container drops the wrapper entirely (collapsing
/// several graph entries into `@included` when they cannot be told apart);
/// anything else rebuilds an explicit graph object with `@graph`, `@id` and
/// `@index` entries.
///
/// Returns [`Error::CollidingEntry`] when a map-shaped container has to be
/// written where an earlier item of the same property already stored a non-map
/// value — a mix the specification defines no output for.
async fn compact_property_graph<N, L>(
    vocabulary: &mut N,
    node: &Node<N::Iri, N::BlankId>,
    expanded_index: Option<&str>,
    nest_result: &mut jstrict::Object,
    container: Container,
    as_array: bool,
    item_active_property: &str,
    active_context: &Context<N::Iri, N::BlankId>,
    loader: &L,
    options: Options,
) -> Result<(), Error<L::Error>>
where
    N: VocabularyMut,
    N::Iri: Clone + Hash + Eq,
    N::BlankId: Clone + Hash + Eq,
    L: Loader,
{
    // If expanded item is a graph object.
    // `compact_property_graph` is only invoked when `node.is_graph()`, so
    // this never actually returns early.
    let Some(graph) = node.graph() else { return Ok(()) };
    let mut compacted_item =
        Recursion::new(graph.compact_fragment_full(vocabulary, active_context, active_context, Some(item_active_property), loader, options)).await?;

    // If `container` includes @graph and @id:
    if container.contains(ContainerKind::Graph) && container.contains(ContainerKind::Id) {
        // Initialize `map_object` to the value of `item_active_property`
        // in `nest_result`, initializing it to a new empty map,
        // if necessary.
        if nest_result.get_unique(item_active_property).is_ok_and(|o| o.is_none()) {
            nest_result.insert(item_active_property.into(), jsonld_syntax::Object::default().into());
        }

        // The entry exists (just inserted above if absent), but may hold a
        // non-map value if an earlier expanded item was routed through the
        // fall-through branch below (e.g. a named graph mixed with simple
        // graphs under the same property); the spec defines no output for
        // that state.
        let Some(map_object) = nest_result
            .get_unique_mut(item_active_property)
            .ok()
            .flatten()
            .and_then(jstrict::Value::as_object_mut)
        else {
            return Err(Error::CollidingEntry);
        };

        // Initialize `map_key` by IRI compacting the value of @id in
        // `expanded_item` or @none if no such value exists
        // with `vocab` set to false if there is an @id entry in
        // `expanded_item`.
        let (id_value, vocab) = match &node.id {
            Some(entry) => (entry.clone().into_term(), false),
            None => (Term::Keyword(Keyword::None), true),
        };

        let Some(map_key) = compact_iri(vocabulary, active_context, &id_value, vocab, false, options)? else {
            return Err(Error::IriConfusedWithPrefix);
        };

        // Use `add_value` to add `compacted_item` to
        // the `map_key` entry in `map_object` using `as_array`.
        add_value(map_object, &map_key, compacted_item, as_array);
    } else if container.contains(ContainerKind::Graph) && container.contains(ContainerKind::Index) && node.is_simple_graph() {
        // Initialize `map_object` to the value of `item_active_property`
        // in `nest_result`, initializing it to a new empty map,
        // if necessary.
        if nest_result.get_unique(item_active_property).is_ok_and(|o| o.is_none()) {
            nest_result.insert(item_active_property.into(), jsonld_syntax::Object::default().into());
        }

        // Same collision case as the `@graph`+`@id` branch above: an earlier
        // named graph routed through the fall-through branch may have stored
        // a non-map value under this key.
        let Some(map_object) = nest_result
            .get_unique_mut(item_active_property)
            .ok()
            .flatten()
            .and_then(jstrict::Value::as_object_mut)
        else {
            return Err(Error::CollidingEntry);
        };

        // Initialize `map_key` the value of @index in `expanded_item`
        // or @none, if no such value exists.
        let map_key = expanded_index.unwrap_or("@none");

        // Use `add_value` to add `compacted_item` to
        // the `map_key` entry in `map_object` using `as_array`.
        add_value(map_object, map_key, compacted_item, as_array);
    } else if container.contains(ContainerKind::Graph) && node.is_simple_graph() {
        // Otherwise, if `container` includes @graph and
        // `expanded_item` is a simple graph object
        // the value cannot be represented as a map object.

        // If `compacted_item` is an array with more than one value,
        // it cannot be directly represented,
        // as multiple objects would be interpreted as different named graphs.
        // Set `compacted_item` to a new map,
        // containing the key from IRI compacting @included and
        // the original `compacted_item` as the value.
        compacted_item = match compacted_item {
            jstrict::Value::Array(items) if items.len() > 1 => {
                let key = keyword_alias(vocabulary, active_context, options, Keyword::Included);
                let mut map = jstrict::Object::default();
                map.insert(key.into(), jstrict::Value::Array(items));
                jstrict::Value::Object(map)
            }
            item => item,
        };

        // Use `add_value` to add `compacted_item` to the
        // `item_active_property` entry in `nest_result` using `as_array`.
        add_value(nest_result, item_active_property, compacted_item, as_array);
    } else {
        // Otherwise, `container` does not include @graph or
        // otherwise does not match one of the previous cases.

        // Set `compacted_item` to a new map containing the key from
        // IRI compacting @graph using the original `compacted_item` as a value.
        let key = keyword_alias(vocabulary, active_context, options, Keyword::Graph);
        let mut map = jstrict::Object::default();
        map.insert(key.into(), compacted_item);

        // If `expanded_item` contains an @id entry,
        // add an entry in `compacted_item` using the key from
        // IRI compacting @id using the value of
        // IRI compacting the value of @id in `expanded_item` using
        // false for vocab.
        if let Some(id_entry) = &node.id {
            // The key is the literal `"@id"` rather than a `keyword_alias`
            // lookup: this step compacts `@id` with `vocab` set to false, which
            // bypasses the inverse context and so can only ever return `"@id"`.
            let id: Term<N::Iri, N::BlankId> = id_entry.clone().into();
            let value = compact_iri(vocabulary, active_context, &id, false, false, options)?;
            map.insert(
                Keyword::Id.into_str().into(),
                match value {
                    Some(s) => jstrict::Value::String((&*s).into()),
                    None => jstrict::Value::Null,
                },
            );
        }

        // If `expanded_item` contains an @index entry,
        // add an entry in `compacted_item` using the key from
        // IRI compacting @index and the value of @index in `expanded_item`.
        if let Some(index_entry) = expanded_index {
            let key = keyword_alias(vocabulary, active_context, options, Keyword::Index);
            map.insert(key.into(), index_entry.into());
        }

        // Use `add_value` to add `compacted_item` to the
        // `item_active_property` entry in `nest_result` using `as_array`.
        let compacted_item = jstrict::Value::Object(map);
        add_value(nest_result, item_active_property, compacted_item, as_array);
    }

    Ok(())
}

/// Picks the object a compacted property should be written into, and returns it
/// together with the term's container mapping and whether its values must be
/// wrapped in an array.
///
/// A term with a `@nest` entry is written into a nested sub-object of `result`
/// keyed by the nest term, created on demand; every other term is written into
/// `result` itself. `as_array` is true when the container mapping includes
/// `@set`, when the key is `@graph` or `@list`, or when `compact_arrays` is off.
///
/// Returns [`Error::InvalidNestValue`] if `@nest` names something that is not
/// `@nest` or an alias for it, and [`Error::CollidingEntry`] if the nest key
/// already holds a non-map value.
fn select_nest_result<'a, I, B, E>(
    result: &'a mut jstrict::Object,
    active_context: &Context<I, B>,
    item_active_property: &str,
    compact_arrays: bool,
) -> Result<(&'a mut jstrict::Object, Container, bool), Error<E>>
where
    I: Clone + Hash + Eq,
    B: Clone + Hash + Eq,
{
    let (nest_result, container) = match active_context.get(item_active_property) {
        Some(term_definition) => {
            let nest_result = match term_definition.nest() {
                Some(nest_term) => {
                    // If nest term is not @nest,
                    // or a term in the active context that expands to @nest,
                    // an invalid @nest value error has been detected,
                    // and processing is aborted.
                    if *nest_term != Nest::Nest {
                        match active_context.get(nest_term.as_str()) {
                            Some(term_def) if term_def.value() == Some(&Term::Keyword(Keyword::Nest)) => {}
                            _ => return Err(Error::InvalidNestValue),
                        }
                    }

                    // If result does not have a nest_term entry,
                    // initialize it to an empty map.
                    if result.get_unique(nest_term.as_str()).is_ok_and(|o| o.is_none()) {
                        result.insert(nest_term.as_str().into(), jstrict::Object::default().into());
                    }

                    // Initialize `nest_result` to the value of `nest_term` in result.
                    // The entry exists (just inserted above if absent), but may hold
                    // a non-map value if another property already compacted to the
                    // same key; the spec defines no output for that state.
                    match result.get_unique_mut(nest_term.as_str()).ok().flatten().and_then(jstrict::Value::as_object_mut) {
                        Some(object) => object,
                        None => return Err(Error::CollidingEntry),
                    }
                }
                None => {
                    // Otherwise, initialize `nest_result` to result.
                    result
                }
            };

            (nest_result, term_definition.container())
        }
        None => (result, Container::None),
    };

    // Initialize container to container mapping for item active property
    // in active context, or to a new empty array,
    // if there is no such container mapping.
    // DONE.

    let as_array = values_as_array(container, item_active_property, compact_arrays);

    Ok((nest_result, container, as_array))
}

/// Checks whether the values of a property are written as an array even when
/// there is only one.
///
/// `item_active_property` is the term the property compacted to and
/// `container` that term's container mapping in the active context, or
/// [`Container::None`] when the term has no definition. Follows the
/// *as array* rule the [compaction algorithm][1] applies to each value of a
/// property: `true` when the container mapping
/// includes `@set`, when the term is `@graph` or `@list`, or when
/// `compact_arrays` is off.
///
/// A term whose container mapping includes `@list` writes a list object's
/// items as an array regardless, and terms with an `@language`, `@index`,
/// `@id` or `@type` container write a map whose entries this flag applies to.
///
/// [1]: https://www.w3.org/TR/json-ld-api/#compaction-algorithm
#[must_use]
pub fn values_as_array(container: Container, item_active_property: &str, compact_arrays: bool) -> bool {
    // Initialize `as_array` to true if `container` includes @set,
    // or if `item_active_property` is @graph or @list,
    // otherwise the negation of `options.compact_arrays`.
    if container.contains(ContainerKind::Set) || item_active_property == "@graph" || item_active_property == "@list" {
        true
    } else {
        !compact_arrays
    }
}

/// Compacts one expanded property and all of its values into `result`.
///
/// Each value is compacted independently, and may select a different term for
/// the same expanded property — a language-tagged string and a node reference
/// can end up under different keys. Values are then routed by the selected
/// term's container mapping: list and graph objects to
/// [`compact_property_list`] and [`compact_property_graph`], and `@language`,
/// `@index`, `@id` and `@type` containers into a map keyed by the corresponding
/// part of the value.
///
/// `inside_reverse` marks the property as coming from an `@reverse` entry, which
/// restricts term selection to terms declared with `@reverse`.
///
/// An empty value array still produces an entry: the property is compacted
/// against an empty node object and assigned an empty array.
pub async fn compact_property<'a, N, L, O, T>(
    vocabulary: &mut N,
    result: &mut jstrict::Object,
    expanded_property: Term<N::Iri, N::BlankId>,
    expanded_value: O,
    active_context: &Context<N::Iri, N::BlankId>,
    loader: &L,
    inside_reverse: bool,
    options: Options,
) -> Result<(), Error<L::Error>>
where
    N: VocabularyMut,
    N::Iri: Clone + Hash + Eq,
    N::BlankId: Clone + Hash + Eq,
    O: IntoIterator<Item = &'a Indexed<T>>,
    T: 'a + object::Any<N::Iri, N::BlankId>,
    L: Loader,
{
    let mut is_empty = true;

    // A property's values are near-always alike — an array of value objects, or
    // of node references — and IRI compaction reads the value only through a
    // handful of features. Remembering the last one lets a run of them share a
    // single term selection. Valid only because every other argument below is
    // fixed for this call.
    let mut memo = CompactIriMemo::new();

    // For each item `expanded_item` in `expanded value`
    for expanded_item in expanded_value {
        is_empty = false;
        // Initialize `item_active_property` by IRI compacting `expanded_property`
        // using `expanded_item` for value and `inside_reverse` for `reverse`.
        let item_active_property = compact_iri_with_memo(
            vocabulary,
            active_context,
            &expanded_property,
            expanded_item,
            true,
            inside_reverse,
            options,
            &mut memo,
        )?;

        // If the term definition for `item_active_property` in the active context
        // has a nest value entry (nest term)
        if let Some(item_active_property) = item_active_property {
            let (nest_result, container, as_array) = select_nest_result(result, active_context, &item_active_property, options.compact_arrays)?;

            // Initialize `compacted_item` to the result of using this algorithm
            // recursively, passing `active_context`, `item_active_property` for
            // `active_property`, `expanded_item` for `element`, along with the
            // `compact_arrays` and `ordered_flags`.
            // If `expanded_item` is a list object or a graph object,
            // use the value of the @list or @graph entries, respectively,
            // for `element` instead of `expanded_item`.
            match expanded_item.inner().as_ref() {
                object::Ref::List(list) => {
                    compact_property_list(
                        vocabulary,
                        list,
                        expanded_item.index(),
                        nest_result,
                        container,
                        as_array,
                        &item_active_property,
                        active_context,
                        loader,
                        options,
                    )
                    .await?;
                }
                object::Ref::Node(node) if node.is_graph() => {
                    compact_property_graph(
                        vocabulary,
                        node,
                        expanded_item.index(),
                        nest_result,
                        container,
                        as_array,
                        &item_active_property,
                        active_context,
                        loader,
                        options,
                    )
                    .await?;
                }
                _ => {
                    let mut compacted_item = Recursion::new(expanded_item.compact_fragment_full(
                        vocabulary,
                        active_context,
                        active_context,
                        Some(&item_active_property),
                        loader,
                        options,
                    ))
                    .await?;

                    // if container includes @language, @index, @id,
                    // or @type and container does not include @graph:
                    if !container.contains(ContainerKind::Graph)
                        && (container.contains(ContainerKind::Language)
                            || container.contains(ContainerKind::Index)
                            || container.contains(ContainerKind::Id)
                            || container.contains(ContainerKind::Type))
                    {
                        // Initialize `map_object` to the value of
                        // `item_active_property` in `nest_result`,
                        // initializing it to a new empty map, if necessary.
                        if nest_result.get_unique(&*item_active_property).is_ok_and(|o| o.is_none()) {
                            nest_result.insert((&*item_active_property).into(), jstrict::Object::default().into());
                        }

                        // The entry exists (just inserted above if absent), but may
                        // hold a non-map value if another property already compacted
                        // to the same key with a different container shape; the spec
                        // defines no output for that state.
                        let Some(map_object) = nest_result
                            .get_unique_mut(&*item_active_property)
                            .ok()
                            .flatten()
                            .and_then(jstrict::Value::as_object_mut)
                        else {
                            return Err(Error::CollidingEntry);
                        };

                        // Initialize container key by IRI compacting either
                        // @language, @index, @id, or @type based on the contents of container.
                        let container_type = if container.contains(ContainerKind::Language) {
                            ContainerKind::Language
                        } else if container.contains(ContainerKind::Index) {
                            ContainerKind::Index
                        } else if container.contains(ContainerKind::Id) {
                            ContainerKind::Id
                        } else {
                            ContainerKind::Type
                        };

                        let mut container_key: String = keyword_alias(vocabulary, active_context, options, container_type.into()).to_string();

                        // Initialize `index_key` to the value of index mapping in
                        // the term definition associated with `item_active_property`
                        // in active context, or @index (None in our case), if no such value exists.
                        let index_key = match active_context.get(&*item_active_property) {
                            Some(def) if def.index().is_some() => def.index(),
                            _ => None,
                        };

                        // If `container` includes @language and `expanded_item`
                        // contains a @value entry, then set `compacted_item` to
                        // the value associated with its @value entry.
                        // Set `map_key` to the value of @language in `expanded_item`,
                        // if any.
                        let map_key = if container_type == ContainerKind::Language && expanded_item.is_value() {
                            if let object::Ref::Value(value) = expanded_item.inner().as_ref() {
                                compacted_item = value_value(value);
                            }

                            expanded_item.language().map(std::string::ToString::to_string)
                        } else if container_type == ContainerKind::Index {
                            match index_key {
                                Some(index_key) => {
                                    // Otherwise, if `container` includes @index and
                                    // `index_key` is not @index:

                                    // Reinitialize `container_key` by
                                    // IRI compacting `index_key`.
                                    container_key =
                                        match compact_iri(vocabulary, active_context, &Term::Id(Id::Invalid(index_key.to_string())), true, false, options)? {
                                            Some(arc) => arc.to_string(),
                                            None => return Err(Error::IriConfusedWithPrefix),
                                        };

                                    // Set `map_key` to the first value of
                                    // `container_key` in `compacted_item`, if any.
                                    let (map_key, remaining_values) = match &mut compacted_item {
                                        jstrict::Value::Object(map) => match map.remove_unique(container_key.as_str()).ok().flatten() {
                                            Some(entry) => match entry.value {
                                                jstrict::Value::String(s) => (Some(s.to_string()), Vec::new()),
                                                jstrict::Value::Array(values) => {
                                                    let mut values = values.into_iter();
                                                    match values.next() {
                                                        Some(first_value) => (first_value.as_str().map(std::string::ToString::to_string), values.collect()),
                                                        None => (None, values.collect()),
                                                    }
                                                }
                                                other => (None, vec![other]),
                                            },
                                            None => (None, Vec::new()),
                                        },
                                        _ => (None, Vec::new()),
                                    };

                                    // If there are remaining values in `compacted_item`
                                    // for container key, use `add_value` to add
                                    // those remaining values to the `container_key`
                                    // in `compacted_item`.
                                    // Otherwise, remove that entry from compacted item.
                                    if !remaining_values.is_empty()
                                        && let Some(map) = compacted_item.as_object_mut()
                                    {
                                        for value in remaining_values {
                                            add_value(map, container_key.as_str(), value, false);
                                        }
                                    }

                                    map_key
                                }
                                None => {
                                    // Otherwise, if `container` includes @index and
                                    // `index_key` is @index, set `map_key` to the value of
                                    // @index in `expanded_item`, if any.
                                    expanded_item.index().map(ToOwned::to_owned)
                                }
                            }
                        } else if container_type == ContainerKind::Id {
                            // Otherwise, if `container` includes @id,
                            // set `map_key` to the value of `container_key` in
                            // `compacted_item` and remove `container_key` from
                            // `compacted_item`.
                            compacted_item
                                .as_object_mut()
                                .and_then(|map| {
                                    map.remove_unique(container_key.as_str())
                                        .ok()
                                        .flatten()
                                        .map(|entry| entry.value.as_str().map(ToOwned::to_owned))
                                })
                                .flatten()
                        } else {
                            // Otherwise, if container includes @type:

                            // Set `map_key` to the first value of `container_key` in
                            // `compacted_item`, if any.
                            let (map_key, remaining_values) = match compacted_item.as_object_mut() {
                                Some(map) => match map.remove_unique(container_key.as_str()).ok().flatten() {
                                    Some(entry) => match entry.value {
                                        jstrict::Value::String(s) => (Some((*s).to_string()), Vec::new()),
                                        jstrict::Value::Array(values) => {
                                            let mut values = values.into_iter();
                                            match values.next() {
                                                Some(first_value) => (first_value.as_str().map(ToOwned::to_owned), values.collect()),
                                                None => (None, values.collect()),
                                            }
                                        }
                                        other => (None, vec![other]),
                                    },
                                    None => (None, Vec::new()),
                                },
                                _ => (None, Vec::new()),
                            };

                            // If there are remaining values in `compacted_item` for
                            // `container_key`, use `add_value` to add those
                            // remaining values to the `container_key` in
                            // `compacted_item`.
                            // Otherwise, remove that entry from compacted item.
                            if !remaining_values.is_empty()
                                && let Some(map) = compacted_item.as_object_mut()
                            {
                                for value in remaining_values {
                                    add_value(map, container_key.as_str(), value, false);
                                }
                            }

                            // If `compacted_item` contains a single entry with a key
                            // expanding to @id, set `compacted_item` to the result of
                            // using this algorithm recursively,
                            // passing `active_context`, `item_active_property` for
                            // `active_property`, and a map composed of the single
                            // entry for @id from `expanded_item` for `element`.
                            if let Some(map) = compacted_item.as_object()
                                && map.len() == 1
                                && map.get_unique("@id").ok().flatten().is_some()
                                // An `@id`-only map implies the expanded item has an
                                // `id`, so this last condition always holds here.
                                && let Some(id) = expanded_item.id()
                            {
                                let obj = Object::node(Node::with_id(id.clone()));
                                compacted_item = Recursion::new(obj.compact_indexed_fragment(
                                    vocabulary,
                                    None,
                                    active_context,
                                    active_context,
                                    Some(&item_active_property),
                                    loader,
                                    options,
                                ))
                                .await?;
                            }

                            map_key
                        };

                        // If `map_key` is null, set it to the result of
                        // IRI compacting @none.
                        let map_key = match map_key {
                            Some(key) => key,
                            None => keyword_alias(vocabulary, active_context, options, Keyword::None).to_string(),
                        };

                        // Use `add_value` to add `compacted_item` to
                        // the `map_key` entry in `map_object` using `as_array`.
                        add_value(map_object, &map_key, compacted_item, as_array);
                    } else {
                        // Otherwise, use `add_value` to add `compacted_item` to the
                        // `item_active_property` entry in `nest_result` using `as_array`.
                        add_value(nest_result, &item_active_property, compacted_item, as_array);
                    }
                }
            }
        }
    }

    // If expanded value is an empty array:
    if is_empty {
        // Initialize `item_active_property` by IRI compacting
        // `expanded_property` using `expanded_value` for `value` and
        // `inside_reverse` for `reverse`.
        let item_active_property = compact_iri_with(
            vocabulary,
            active_context,
            &expanded_property,
            &Indexed::new(Object::node(Node::new()), None),
            true,
            inside_reverse,
            options,
        )?;

        // If the term definition for `item_active_property` in the active context
        // has a nest value entry (nest term):
        if let Some(item_active_property) = item_active_property {
            let (nest_result, _, _) = select_nest_result(result, active_context, &item_active_property, options.compact_arrays)?;

            // Use `add_value` to add an empty array to the `item_active_property` entry in
            // `nest_result` using true for `as_array`.
            add_value(nest_result, &item_active_property, Vec::new().into(), true);
        }
    }

    Ok(())
}