frdt 0.3.0

Edit and inspect Resonite FrDT (.brson) documents without expanding them to JSON
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
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
//! Edit handle over one decompressed BSON buffer.
//!
//! `Document` and `SlotHandle` share the buffer through `Arc`. A handle follows
//! an internal slot key, not the BSON `ID` string. After an edit shifts byte
//! offsets, the next call resolves that key again.

use std::collections::HashMap;
use std::io::Write;
use std::sync::{Arc, Mutex, MutexGuard};

use crate::container::{self, DEFAULT_QUALITY};
use crate::datatree;
use crate::edit;
use crate::empty;
use crate::error::{Error, Result};
use crate::extract;
use crate::import::{self, ImportOptions, UnresolvedPolicy};
use crate::index::{self, Index};
use crate::merge;
use crate::renumber;
use crate::typetable;
use crate::value::Value;
use crate::versions::{self, Mismatch, RootInfo, VersionPolicy};
use crate::work;

struct Inner {
    bytes: Vec<u8>,
    index: Index,
    /// Bumped on every committed edit. Handles cache an offset only while this
    /// still matches; otherwise they look the slot up by its key.
    generation: u64,
}

/// An open FrDT document. Mutations update this buffer in place.
#[derive(Clone)]
pub struct Document {
    inner: Arc<Mutex<Inner>>,
}

/// A slot inside a [`Document`].
///
/// The cached offset is valid only for `generation`. `key` stays with the slot
/// when its BSON `ID` field changes, so a duplicate id cannot retarget it.
#[derive(Clone)]
pub struct SlotHandle {
    inner: Arc<Mutex<Inner>>,
    key: u64,
    offset: usize,
    generation: u64,
}

/// `Type` index, resolved name, and reference targets of one component.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ComponentInfo {
    pub type_index: i64,
    pub type_name: String,
    pub references: Vec<String>,
}

/// One entry of the root `Asset` array.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AssetInfo {
    pub id: String,
    pub type_index: Option<i64>,
}

/// What [`Document::import`] copied.
pub struct Import {
    slots: Vec<SlotHandle>,
    ids: HashMap<String, String>,
    unresolved: Vec<String>,
    asset_count: usize,
    mismatches: Vec<Mismatch>,
}

impl Import {
    /// The copied slots in the destination, in the order they were passed.
    pub fn slots(&self) -> &[SlotHandle] {
        &self.slots
    }

    /// The destination identifier that replaced a source identifier.
    ///
    /// Covers every slot, component, field, and asset identifier that was
    /// copied, so a caller can point a new reference (for example a new
    /// `Static.ChildrenParent`) at a copied target.
    pub fn new_id(&self, source_id: &str) -> Option<&str> {
        self.ids.get(source_id).map(String::as_str)
    }

    /// Source identifiers that the copy still names but that were not copied.
    /// Those strings are left unchanged. Sorted.
    pub fn unresolved(&self) -> &[String] {
        &self.unresolved
    }

    /// Number of asset entries copied because the subtrees use them.
    pub fn asset_count(&self) -> usize {
        self.asset_count
    }

    /// Where the source's `VersionNumber`, `FeatureFlags`, or `TypeVersions`
    /// differed from the destination's before the import. Listed under every
    /// [`VersionPolicy`]; with [`VersionPolicy::Newer`] the destination has
    /// since moved to the newer side of each.
    pub fn mismatches(&self) -> &[Mismatch] {
        &self.mismatches
    }
}

/// What [`Document::copy_component`] added.
pub struct CopiedComponent {
    index: usize,
    id: String,
    unresolved: Vec<String>,
    asset_count: usize,
    mismatches: Vec<Mismatch>,
}

impl CopiedComponent {
    /// The copy's position in [`SlotHandle::components`] of the target slot.
    pub fn index(&self) -> usize {
        self.index
    }

    /// The copy's new id.
    pub fn id(&self) -> &str {
        &self.id
    }

    /// Source ids the component refers to that were not copied, sorted.
    /// Under [`UnresolvedPolicy::Null`] these were written as null.
    pub fn unresolved(&self) -> &[String] {
        &self.unresolved
    }

    /// Number of assets copied with the component.
    pub fn asset_count(&self) -> usize {
        self.asset_count
    }

    /// As [`Import::mismatches`].
    pub fn mismatches(&self) -> &[Mismatch] {
        &self.mismatches
    }
}

/// What [`Document::copy_components`] added.
pub struct CopiedComponents {
    first: usize,
    ids: Vec<String>,
    unresolved: Vec<String>,
    asset_count: usize,
    mismatches: Vec<Mismatch>,
}

impl CopiedComponents {
    /// Position of each copy in [`SlotHandle::components`] of the target
    /// slot, in the order given.
    pub fn indices(&self) -> Vec<usize> {
        (self.first..self.first + self.ids.len()).collect()
    }

    /// The copies' new ids, in the order given.
    pub fn ids(&self) -> &[String] {
        &self.ids
    }

    /// Source ids the components refer to that were not copied, sorted.
    /// Under [`UnresolvedPolicy::Null`] these were written as null.
    pub fn unresolved(&self) -> &[String] {
        &self.unresolved
    }

    /// Number of assets copied with the components.
    pub fn asset_count(&self) -> usize {
        self.asset_count
    }

    /// As [`Import::mismatches`].
    pub fn mismatches(&self) -> &[Mismatch] {
        &self.mismatches
    }
}

/// The result of [`Document::extract`].
pub struct Extract {
    document: Document,
    unresolved: Vec<String>,
}

impl Extract {
    /// The new document. Its root is the copy of the extracted slot.
    pub fn document(&self) -> &Document {
        &self.document
    }

    /// The new document, taken out of the result.
    pub fn into_document(self) -> Document {
        self.document
    }

    /// Ids the copy refers to that the source defines outside the extracted
    /// subtree and its assets, sorted. Under [`UnresolvedPolicy::Null`] these
    /// were written as null.
    pub fn unresolved(&self) -> &[String] {
        &self.unresolved
    }
}

impl Document {
    /// A document with one empty root slot named `root_name`.
    ///
    /// `version_number` must read as `year.month.day[.build]`. Feature flags are
    /// written as int64, in the order given. `Types`, `TypeVersions`, and
    /// `Assets` start empty. The root's `ParentReference` is a fresh id.
    pub fn empty<I, K>(root_name: &str, version_number: &str, feature_flags: I) -> Result<Document>
    where
        I: IntoIterator<Item = (K, i64)>,
        K: AsRef<str>,
    {
        let bson = empty::empty_bson(root_name, version_number, feature_flags)?;
        let index = index::build(&bson)?;
        Ok(Document {
            inner: Arc::new(Mutex::new(Inner {
                bytes: bson,
                index,
                generation: 0,
            })),
        })
    }

    /// Open a Resonite `.brson` (`FrDT`) or a tool working file (`FRWK`).
    pub fn open(bytes: &[u8]) -> Result<Document> {
        let (bson, index) = if bytes.starts_with(work::MAGIC) {
            work::read(bytes)?
        } else {
            let bson = container::decompress(bytes)?;
            let index = index::build(&bson)?;
            (bson, index)
        };
        Ok(Document {
            inner: Arc::new(Mutex::new(Inner {
                bytes: bson,
                index,
                generation: 0,
            })),
        })
    }

    pub fn root(&self) -> SlotHandle {
        let guard = self.lock().expect("frdt document lock");
        handle_at(&self.inner, &guard, guard.index.root_slot).expect("root slot")
    }

    /// Graft `child` under `parent`. `parent` must belong to this document.
    ///
    /// The returned handle is the grafted slot inside this document. Handles
    /// into `child`'s document are not updated.
    pub fn append(&mut self, parent: SlotHandle, child: SlotHandle) -> Result<SlotHandle> {
        if !Arc::ptr_eq(&self.inner, &parent.inner) {
            return Err(Error::Invalid(
                "parent handle is from a different document".into(),
            ));
        }
        // Snapshot the child before locking the destination. The same document
        // would deadlock if both guards were held, and a failed merge must not
        // leave the destination half-updated.
        let (child_bytes, child_off) = {
            let guard = child.inner.lock()?;
            let off = resolve(&guard, &child)?;
            (guard.bytes.clone(), off)
        };
        let mut guard = self.inner.lock()?;
        let parent_off = resolve(&guard, &parent)?;
        let mut bytes = guard.bytes.clone();
        let new_off = merge::append_slot(&mut bytes, parent_off, &child_bytes, child_off)?;
        let index = index::rebuild(&bytes, &guard.index)?;
        let key = index
            .slots
            .iter()
            .find(|slot| slot.offset == new_off)
            .map(|slot| slot.key)
            .ok_or_else(|| Error::Invalid("grafted slot is missing from the index".into()))?;
        let generation = guard.generation.wrapping_add(1);
        guard.bytes = bytes;
        guard.index = index;
        guard.generation = generation;
        Ok(SlotHandle {
            inner: Arc::clone(&self.inner),
            key,
            offset: new_off,
            generation,
        })
    }

    /// Copy `slots` (all from one document) to the end of `parent`'s children.
    ///
    /// Components and fields come with each slot. Every identifier in the
    /// copies, and in the assets they reference, is replaced from one map, so
    /// references among the copied slots and assets keep their targets. A
    /// reference to anything else in the source is left as it was and listed
    /// in [`Import::unresolved`]. Assets that nothing copied references stay
    /// behind. Type names the destination lacks are appended to `Types`, with
    /// their `TypeVersions` entry when the destination has none. `FeatureFlags`
    /// and `VersionNumber` of the destination are not changed.
    ///
    /// The source document is not modified. On error neither document changes.
    pub fn import(&mut self, parent: &SlotHandle, slots: &[SlotHandle]) -> Result<Import> {
        self.import_with(parent, slots, &ImportOptions::default())
    }

    /// [`Document::import`] with options.
    ///
    /// - [`ImportOptions::unresolved`]: keep unresolved references (default),
    ///   fail, or write null in their place.
    /// - [`ImportOptions::versions`]: keep the destination's `VersionNumber`,
    ///   `FeatureFlags`, and `TypeVersions` (default), or move to the newer side
    ///   of each. Either way [`Import::mismatches`] lists what differed.
    pub fn import_with(
        &mut self,
        parent: &SlotHandle,
        slots: &[SlotHandle],
        options: &ImportOptions,
    ) -> Result<Import> {
        if !Arc::ptr_eq(&self.inner, &parent.inner) {
            return Err(Error::Invalid(
                "parent handle is from a different document".into(),
            ));
        }
        let Some(first) = slots.first() else {
            return Ok(Import {
                slots: Vec::new(),
                ids: HashMap::new(),
                unresolved: Vec::new(),
                asset_count: 0,
                mismatches: Vec::new(),
            });
        };
        if slots.iter().any(|s| !Arc::ptr_eq(&s.inner, &first.inner)) {
            return Err(Error::Invalid(
                "imported slots must come from one document".into(),
            ));
        }
        let (src_bytes, spans) = {
            let guard = first.inner.lock()?;
            let mut spans = Vec::with_capacity(slots.len());
            for slot in slots {
                let offset = resolve(&guard, slot)?;
                let loc = guard.index.slot_by_offset(offset).ok_or(Error::NotFound)?;
                spans.push((loc.offset, loc.end));
            }
            (guard.bytes.clone(), spans)
        };
        let mut guard = self.inner.lock()?;
        let parent_off = resolve(&guard, parent)?;
        let dest_info = RootInfo::read(&guard.bytes)?;
        let src_info = RootInfo::read(&src_bytes)?;
        let mut bytes = guard.bytes.clone();
        let outcome = import::import_slots(
            &mut bytes,
            &guard.index,
            parent_off,
            &src_bytes,
            &spans,
            import::Unresolved {
                policy: options.unresolved,
                same_document: Arc::ptr_eq(&self.inner, &first.inner),
            },
        )?;
        let mismatches = versions::mismatches(&dest_info, &src_info, &outcome.used_names);
        if options.versions == VersionPolicy::Newer {
            versions::adopt_newer(&mut bytes, &src_info, &outcome.used_names)?;
        }
        let index = index::rebuild(&bytes, &guard.index)?;
        let generation = guard.generation.wrapping_add(1);
        let mut handles = Vec::with_capacity(outcome.roots.len());
        for id in &outcome.roots {
            let slot = index
                .slots
                .iter()
                .find(|slot| slot.id == *id)
                .ok_or_else(|| Error::Invalid("imported slot is missing from the index".into()))?;
            handles.push(SlotHandle {
                inner: Arc::clone(&self.inner),
                key: slot.key,
                offset: slot.offset,
                generation,
            });
        }
        guard.bytes = bytes;
        guard.index = index;
        guard.generation = generation;
        Ok(Import {
            slots: handles,
            ids: outcome.ids,
            unresolved: outcome.unresolved,
            asset_count: outcome.assets,
            mismatches,
        })
    }

    /// Append a copy of the `component`-th component of `source` (a slot in
    /// this or another document) to `slot`.
    ///
    /// It works like [`Document::import_with`] for one component: every id
    /// the component defines gets a new one and references to them follow;
    /// references to `source` itself and to its fields (`Active`, `Position`,
    /// ...) go to `slot` and its fields; the type name (and type
    /// fields such as `_type`) is mapped into this document's `Types`, with
    /// its `TypeVersions` entry when this document has none; the assets the
    /// component uses come with it. The field values are copied as they are;
    /// change them with [`SlotHandle::set_component_value`]. `options` work
    /// as for imports.
    ///
    /// Use it to add components from a template file saved by Resonite, so
    /// that the fields and type versions follow Resonite. When components
    /// refer to each other (a driver and what it drives), copy them together
    /// with [`Document::copy_components`].
    pub fn copy_component(
        &mut self,
        slot: &SlotHandle,
        source: &SlotHandle,
        component: usize,
        options: &ImportOptions,
    ) -> Result<CopiedComponent> {
        let got = self.copy_components(slot, source, &[component], options)?;
        Ok(CopiedComponent {
            index: got.first,
            id: got.ids.into_iter().next().unwrap_or_default(),
            unresolved: got.unresolved,
            asset_count: got.asset_count,
            mismatches: got.mismatches,
        })
    }

    /// Append copies of several components of `source`, in the order of
    /// `components`, to `slot`, as one copy: references among them follow the
    /// copies, and references to `source` and its fields go to `slot` and its
    /// fields. References to anything else outside the copies (other slots,
    /// children) are unresolved, as the options say. Otherwise as
    /// [`Document::copy_component`]. An index given twice is refused.
    pub fn copy_components(
        &mut self,
        slot: &SlotHandle,
        source: &SlotHandle,
        components: &[usize],
        options: &ImportOptions,
    ) -> Result<CopiedComponents> {
        self.own(slot)?;
        let mut unique = std::collections::HashSet::new();
        if let Some(i) = components.iter().find(|i| !unique.insert(**i)) {
            return Err(Error::Invalid(format!("component {i} is given twice")));
        }
        let (src_bytes, source_ids, offs) = {
            let guard = source.inner.lock()?;
            let offset = resolve(&guard, source)?;
            let types = datatree::read_types(&guard.bytes)?;
            let comps = datatree::components_of_slot(&guard.bytes, offset, &types)?;
            let mut offs = Vec::with_capacity(components.len());
            for &i in components {
                let comp = comps
                    .get(i)
                    .ok_or_else(|| Error::Invalid(format!("no component at {i}")))?;
                offs.push(comp.offset);
            }
            (guard.bytes.clone(), slot_ids(&guard.bytes, offset)?, offs)
        };
        let mut guard = self.inner.lock()?;
        let slot_off = resolve(&guard, slot)?;
        // The source slot and each of its fields, paired with the target's.
        let target_ids = slot_ids(&guard.bytes, slot_off)?;
        let rebind: Vec<(String, String)> = source_ids
            .into_iter()
            .filter_map(|(key, from)| {
                target_ids
                    .iter()
                    .find(|(k, _)| *k == key)
                    .map(|(_, to)| (from, to.clone()))
            })
            .collect();
        let dest_info = RootInfo::read(&guard.bytes)?;
        let src_info = RootInfo::read(&src_bytes)?;
        let mut bytes = guard.bytes.clone();
        let outcome = import::copy_components(
            &mut bytes,
            &guard.index,
            slot_off,
            &src_bytes,
            &rebind,
            &offs,
            import::Unresolved {
                policy: options.unresolved,
                same_document: Arc::ptr_eq(&self.inner, &source.inner),
            },
        )?;
        let mismatches = versions::mismatches(&dest_info, &src_info, &outcome.used_names);
        if options.versions == VersionPolicy::Newer {
            versions::adopt_newer(&mut bytes, &src_info, &outcome.used_names)?;
        }
        let index = index::rebuild(&bytes, &guard.index)?;
        commit(&mut guard, bytes, index);
        Ok(CopiedComponents {
            first: outcome.position,
            ids: outcome.roots,
            unresolved: outcome.unresolved,
            asset_count: outcome.assets,
            mismatches,
        })
    }

    /// A new document whose root is a copy of `slot` and its subtree.
    ///
    /// Ids are kept. Only the assets the subtree uses are kept, and `Types`
    /// and `TypeVersions` are rebuilt from what remains. `VersionNumber`,
    /// `FeatureFlags`, and every other root field are copied as they are.
    /// This document is not modified. `unresolved` decides what happens to
    /// references to ids this document defines outside the subtree; see
    /// [`Extract::unresolved`].
    pub fn extract(&self, slot: &SlotHandle, unresolved: UnresolvedPolicy) -> Result<Extract> {
        if !Arc::ptr_eq(&self.inner, &slot.inner) {
            return Err(Error::Invalid(
                "slot handle is from a different document".into(),
            ));
        }
        let guard = self.inner.lock()?;
        let offset = resolve(&guard, slot)?;
        let out = extract::extract(&guard.bytes, offset, unresolved)?;
        Ok(Extract {
            document: Document {
                inner: Arc::new(Mutex::new(Inner {
                    bytes: out.bytes,
                    index: out.index,
                    generation: 0,
                })),
            },
            unresolved: out.unresolved,
        })
    }

    /// Give every identifier a new id computed from `seed` and the order in
    /// which the ids are defined (the slot tree depth first, then `Assets`),
    /// and rewrite every reference to them. The root slot's
    /// `ParentReference`, which names nothing in the file, gets a generated id
    /// too.
    ///
    /// Two documents with the same content come out byte-identical for the
    /// same seed, whatever random ids `empty`, `add_slot`, `add_component`,
    /// and `import` gave them along the way. Call it last, just before
    /// writing. Handles stay valid. A string naming an id this document does
    /// not define is left as it is. Returns the number of ids renumbered.
    pub fn renumber_ids(&mut self, seed: u64) -> Result<usize> {
        let mut guard = self.inner.lock()?;
        let mut bytes = guard.bytes.clone();
        let count = renumber::renumber(&mut bytes, seed)?;
        let index = index::rebuild(&bytes, &guard.index)?;
        commit(&mut guard, bytes, index);
        Ok(count)
    }

    /// Replace `VersionNumber`. It must read as `year.month.day[.build]`.
    pub fn set_version_number(&mut self, version_number: &str) -> Result<()> {
        empty::check_version(version_number)?;
        let mut guard = self.inner.lock()?;
        let mut bytes = guard.bytes.clone();
        typetable::replace_root_fields(
            &mut bytes,
            &[(
                "VersionNumber".into(),
                crate::bson::STRING,
                crate::bson::string_value(version_number),
            )],
        )?;
        let index = index::rebuild(&bytes, &guard.index)?;
        commit(&mut guard, bytes, index);
        Ok(())
    }

    /// Replace `FeatureFlags` with these flags, written as int64 in the order
    /// given.
    pub fn set_feature_flags<I, K>(&mut self, feature_flags: I) -> Result<()>
    where
        I: IntoIterator<Item = (K, i64)>,
        K: AsRef<str>,
    {
        let mut doc = crate::bson::DocBuf::new();
        for (name, value) in feature_flags {
            doc.int64(name.as_ref(), value);
        }
        let mut guard = self.inner.lock()?;
        let mut bytes = guard.bytes.clone();
        typetable::replace_root_fields(
            &mut bytes,
            &[("FeatureFlags".into(), crate::bson::DOCUMENT, doc.finish())],
        )?;
        let index = index::rebuild(&bytes, &guard.index)?;
        commit(&mut guard, bytes, index);
        Ok(())
    }

    /// Add an empty slot named `name` as the last child of `parent`.
    ///
    /// The slot is laid out like [`Document::empty`]'s root, with
    /// `ParentReference` set to the parent's id.
    pub fn add_slot(&mut self, parent: &SlotHandle, name: &str) -> Result<SlotHandle> {
        self.own(parent)?;
        let mut guard = self.inner.lock()?;
        let parent_off = resolve(&guard, parent)?;
        let parent_pos = guard.index.position(parent_off).ok_or(Error::NotFound)?;
        let mut bytes = guard.bytes.clone();
        let id = edit::add_slot(&mut bytes, &guard.index, parent_off, name)?;
        let key = guard.index.next_key();
        let keys = edit::keys_after_add(&guard.index, parent_pos, key);
        let index = index::rebuild_keys(&bytes, &guard.index, &keys, key + 1)?;
        let offset = index
            .slot_by_key(key)
            .map(|s| s.offset)
            .ok_or(Error::NotFound)?;
        debug_assert_eq!(
            index.slot_by_offset(offset).map(|s| s.id.as_str()),
            Some(id.as_str())
        );
        let generation = commit(&mut guard, bytes, index);
        Ok(SlotHandle {
            inner: Arc::clone(&self.inner),
            key,
            offset,
            generation,
        })
    }

    /// Append a component to `slot`.
    ///
    /// Each field is written as `{ID, Data}` with a new id; `None` writes
    /// null. The component gets new `ID` and `persistent-ID` values, and its
    /// `Type` is int64. The type name is appended to `Types` when missing, and
    /// `type_version` (when given) is added to `TypeVersions` when the name
    /// has no entry. Returns the component's position in
    /// [`SlotHandle::components`] and its id.
    pub fn add_component(
        &mut self,
        slot: &SlotHandle,
        type_name: &str,
        type_version: Option<i64>,
        fields: &[(&str, Option<Value>)],
    ) -> Result<(usize, String)> {
        self.own(slot)?;
        let mut guard = self.inner.lock()?;
        let offset = resolve(&guard, slot)?;
        let mut bytes = guard.bytes.clone();
        let added = edit::add_component(
            &mut bytes,
            &guard.index,
            offset,
            type_name,
            type_version,
            fields,
        )?;
        let keys = guard.index.keys();
        let index = index::rebuild_keys(&bytes, &guard.index, &keys, 0)?;
        commit(&mut guard, bytes, index);
        Ok(added)
    }

    /// Make `slot` the last child of `new_parent`, in this document.
    ///
    /// The subtree keeps its ids; only its `ParentReference` changes. Handles
    /// to slots in the subtree stay valid. The root cannot move, and a slot
    /// cannot move under itself.
    pub fn move_slot(&mut self, slot: &SlotHandle, new_parent: &SlotHandle) -> Result<()> {
        self.own(slot)?;
        self.own(new_parent)?;
        let mut guard = self.inner.lock()?;
        let offset = resolve(&guard, slot)?;
        let parent_off = resolve(&guard, new_parent)?;
        if edit::contains(&guard.index, offset, parent_off)? {
            return Err(Error::Invalid("a slot cannot move under itself".into()));
        }
        let pos = guard.index.position(offset).ok_or(Error::NotFound)?;
        let parent_pos = guard.index.position(parent_off).ok_or(Error::NotFound)?;
        let parent_key = guard.index.slots[parent_pos].key;
        let parent_id = guard.index.slots[parent_pos].id.clone();
        let keys = edit::keys_after_move(&guard.index, pos, parent_pos);

        let mut bytes = guard.bytes.clone();
        let removed = edit::remove_slot(&mut bytes, &guard.index, offset)?;
        let after_remove = edit::keys_after_remove(&guard.index, pos);
        let middle = index::rebuild_keys(&bytes, &guard.index, &after_remove, 0)?;
        let parent_off = middle
            .slot_by_key(parent_key)
            .map(|s| s.offset)
            .ok_or(Error::NotFound)?;
        let moved = edit::with_parent(&removed, &parent_id)?;
        edit::insert_child(&mut bytes, &middle, parent_off, &moved)?;
        let index = index::rebuild_keys(&bytes, &guard.index, &keys, 0)?;
        commit(&mut guard, bytes, index);
        Ok(())
    }

    /// Remove `slot` and everything under it. The root cannot be removed.
    ///
    /// References elsewhere that named the removed slots are left as they
    /// are. Call [`Document::rebuild_types`] afterwards to drop type names
    /// that nothing uses any more.
    pub fn remove_slot(&mut self, slot: &SlotHandle) -> Result<()> {
        self.own(slot)?;
        let mut guard = self.inner.lock()?;
        let offset = resolve(&guard, slot)?;
        let pos = guard.index.position(offset).ok_or(Error::NotFound)?;
        let keys = edit::keys_after_remove(&guard.index, pos);
        let mut bytes = guard.bytes.clone();
        edit::remove_slot(&mut bytes, &guard.index, offset)?;
        let index = index::rebuild_keys(&bytes, &guard.index, &keys, 0)?;
        commit(&mut guard, bytes, index);
        Ok(())
    }

    fn own(&self, handle: &SlotHandle) -> Result<()> {
        if Arc::ptr_eq(&self.inner, &handle.inner) {
            Ok(())
        } else {
            Err(Error::Invalid(
                "slot handle is from a different document".into(),
            ))
        }
    }

    /// Rebuild `Types` from the components and assets that remain.
    ///
    /// Names keep their first-use order (slots depth first, components in
    /// order, then assets). Every component `Type`, and every type field such
    /// as `GizmoLink._type`, is renumbered in place. `TypeVersions` keeps only
    /// entries whose name is still listed. Returns the names that were removed.
    pub fn rebuild_types(&mut self) -> Result<Vec<String>> {
        let mut guard = self.inner.lock()?;
        let mut bytes = guard.bytes.clone();
        let removed = typetable::rebuild(&mut bytes, &guard.index)?;
        let index = index::rebuild(&bytes, &guard.index)?;
        guard.bytes = bytes;
        guard.index = index;
        guard.generation = guard.generation.wrapping_add(1);
        Ok(removed)
    }

    /// The slot whose `ID` is `id`. The first one in depth-first order when
    /// the id is duplicated.
    pub fn slot_by_id(&self, id: &str) -> Result<SlotHandle> {
        let guard = self.lock()?;
        let offset = guard
            .index
            .slots
            .iter()
            .find(|slot| slot.id == id)
            .map(|slot| slot.offset)
            .ok_or(Error::NotFound)?;
        handle_at(&self.inner, &guard, offset)
    }

    /// `VersionNumber` as written. Resonite writes a string such as
    /// `2026.9.18.82`; any other BSON type is an error.
    pub fn version_number(&self) -> Result<String> {
        let guard = self.lock()?;
        let el = datatree::field(&guard.bytes, 0, "VersionNumber")?
            .ok_or_else(|| Error::FieldNotFound("VersionNumber".into()))?;
        if el.ty != crate::bson::STRING {
            return Err(Error::Invalid("VersionNumber is not a string".into()));
        }
        Ok(crate::bson::decode_string(el.value)?.to_string())
    }

    /// Every feature flag in file order. A bool reads as 0 or 1.
    pub fn feature_flags(&self) -> Result<Vec<(String, i64)>> {
        let guard = self.lock()?;
        let Some(doc) = datatree::field(&guard.bytes, 0, "FeatureFlags")? else {
            return Ok(Vec::new());
        };
        if doc.ty != crate::bson::DOCUMENT {
            return Err(Error::Invalid("FeatureFlags is not a document".into()));
        }
        let mut out = Vec::new();
        for el in crate::bson::elements(&guard.bytes, doc.value_at)? {
            let value = match el.ty {
                crate::bson::BOOL => i64::from(crate::bson::decode_bool(el.value)?),
                _ => crate::bson::decode_int(el.value, el.ty)?,
            };
            out.push((el.key.to_string(), value));
        }
        Ok(out)
    }

    pub fn types(&self) -> Result<Vec<String>> {
        Ok(self.lock()?.index.types.clone())
    }

    pub fn slot_count(&self) -> Result<usize> {
        Ok(self.lock()?.index.slots.len())
    }

    pub fn component_count(&self) -> Result<usize> {
        Ok(self.lock()?.index.components.len())
    }

    pub fn type_version(&self, name: &str) -> Result<Option<i64>> {
        let guard = self.lock()?;
        let Some(doc) = datatree::field(&guard.bytes, 0, "TypeVersions")? else {
            return Ok(None);
        };
        if doc.ty != crate::bson::DOCUMENT {
            return Err(Error::Invalid("TypeVersions is not a document".into()));
        }
        datatree::read_number_field(&guard.bytes, doc.value_at, name)
    }

    pub fn feature_flag(&self, name: &str) -> Result<Option<bool>> {
        let guard = self.lock()?;
        let Some(doc) = datatree::field(&guard.bytes, 0, "FeatureFlags")? else {
            return Ok(None);
        };
        if doc.ty != crate::bson::DOCUMENT {
            return Err(Error::Invalid("FeatureFlags is not a document".into()));
        }
        datatree::read_bool_field(&guard.bytes, doc.value_at, name)
    }

    pub fn assets(&self) -> Result<Vec<AssetInfo>> {
        let guard = self.lock()?;
        Ok(datatree::asset_views(&guard.bytes)?
            .into_iter()
            .map(|(id, type_index)| AssetInfo { id, type_index })
            .collect())
    }

    /// Each asset entry's BSON document, for tests.
    pub(crate) fn asset_raw(&self) -> Result<Vec<Vec<u8>>> {
        let guard = self.lock()?;
        let Some(arr) = datatree::asset_array(&guard.bytes)? else {
            return Ok(Vec::new());
        };
        Ok(crate::bson::elements(&guard.bytes, arr.value_at)?
            .into_iter()
            .map(|el| el.value.to_vec())
            .collect())
    }

    /// Decompressed BSON. This is the edit buffer, not a JSON document.
    pub fn bson_bytes(&self) -> Result<Vec<u8>> {
        Ok(self.lock()?.bytes.clone())
    }

    /// Resonite `.brson`: Brotli quality 5 and the 9-byte `FrDT` header.
    pub fn write_brson<W: Write>(&self, out: &mut W) -> Result<()> {
        self.write_brson_with_quality(out, DEFAULT_QUALITY)
    }

    pub fn write_brson_with_quality<W: Write>(&self, out: &mut W, quality: u32) -> Result<()> {
        let guard = self.lock()?;
        container::write_brson(&guard.bytes, out, quality)
    }

    /// Tool file: uncompressed BSON and the index, so the next open skips Brotli.
    pub fn write_work(&self, out: &mut Vec<u8>) -> Result<()> {
        let guard = self.lock()?;
        work::write(&guard.bytes, &guard.index, out)
    }

    fn lock(&self) -> Result<MutexGuard<'_, Inner>> {
        Ok(self.inner.lock()?)
    }
}

impl SlotHandle {
    pub fn name(&self) -> Result<String> {
        let guard = self.lock()?;
        let offset = resolve(&guard, self)?;
        datatree::read_string_field(&guard.bytes, offset, "Name")?
            .ok_or_else(|| Error::Invalid("slot has no Name".into()))
    }

    pub fn id(&self) -> Result<String> {
        let guard = self.lock()?;
        let offset = resolve(&guard, self)?;
        datatree::read_string_field(&guard.bytes, offset, "ID")?
            .ok_or_else(|| Error::Invalid("slot has no ID".into()))
    }

    pub fn parent_reference(&self) -> Result<Option<String>> {
        let guard = self.lock()?;
        let offset = resolve(&guard, self)?;
        datatree::read_string_field(&guard.bytes, offset, "ParentReference")
    }

    pub fn get(&self, field: &str) -> Result<Value> {
        let guard = self.lock()?;
        let offset = resolve(&guard, self)?;
        datatree::read_slot_value(&guard.bytes, offset, field)
    }

    /// Replace a field on this slot and patch ancestor BSON lengths.
    ///
    /// When the field is `{ID, Data}` (as Resonite writes `Name`, `Tag`,
    /// `Position`, ...), only `Data` is replaced and the wrapper keeps its id;
    /// `float3` and `floatQ` are then written as double arrays. An unwrapped
    /// field is replaced as in v1.
    ///
    /// The splice is applied to a copy and installed only after the document
    /// still indexes cleanly.
    pub fn set(&self, field: &str, value: Value) -> Result<()> {
        let mut guard = self.lock()?;
        let offset = resolve(&guard, self)?;
        if field == "ID" {
            reject_duplicate_slot_id(&guard, offset, &value)?;
        }
        let lengths = guard
            .index
            .slot_by_offset(offset)
            .map(|slot| slot.container_lengths.clone())
            .ok_or(Error::NotFound)?;
        let mut bytes = guard.bytes.clone();
        replace_field(&mut bytes, offset, field, &value, &lengths)?;
        let index = index::rebuild(&bytes, &guard.index)?;
        guard.bytes = bytes;
        guard.index = index;
        guard.generation = guard.generation.wrapping_add(1);
        Ok(())
    }

    /// Depth-first search. The predicate sees this slot first.
    ///
    /// The lock is not held while `pred` runs, so the predicate may call
    /// [`SlotHandle::name`].
    pub fn find_slot<F>(&self, mut pred: F) -> Result<SlotHandle>
    where
        F: FnMut(&SlotHandle) -> Result<bool>,
    {
        let (start_gen, start) = {
            let guard = self.lock()?;
            (guard.generation, resolve(&guard, self)?)
        };
        let mut stack = vec![start];
        while let Some(offset) = stack.pop() {
            let handle = {
                let guard = self.lock()?;
                if guard.generation != start_gen {
                    return Err(Error::Invalid("document changed during find_slot".into()));
                }
                handle_at(&self.inner, &guard, offset)?
            };
            if pred(&handle)? {
                return Ok(handle);
            }
            let children = {
                let guard = self.lock()?;
                if guard.generation != start_gen {
                    return Err(Error::Invalid("document changed during find_slot".into()));
                }
                datatree::child_slot_offsets(&guard.bytes, offset)?
            };
            for child in children.into_iter().rev() {
                stack.push(child);
            }
        }
        Err(Error::NotFound)
    }

    /// This slot's BSON document, for tests.
    pub(crate) fn raw(&self) -> Result<Vec<u8>> {
        let guard = self.lock()?;
        let offset = resolve(&guard, self)?;
        let end = crate::bson::doc_end(&guard.bytes, offset)?;
        Ok(guard.bytes[offset..end].to_vec())
    }

    /// Set a field of the `component`-th component (the order of
    /// [`SlotHandle::components`]).
    ///
    /// For a `{ID, Data}` field only `Data` changes, in Resonite's layout
    /// (int64, double arrays); `None` writes null. A reference is the target's
    /// id as [`Value::String`]. The field must already exist.
    pub fn set_component_value(
        &self,
        component: usize,
        field: &str,
        value: Option<Value>,
    ) -> Result<()> {
        let mut guard = self.lock()?;
        let offset = resolve(&guard, self)?;
        let mut bytes = guard.bytes.clone();
        edit::set_component_value(
            &mut bytes,
            &guard.index,
            offset,
            component,
            field,
            value.as_ref(),
        )?;
        let keys = guard.index.keys();
        let index = index::rebuild_keys(&bytes, &guard.index, &keys, 0)?;
        commit(&mut guard, bytes, index);
        Ok(())
    }

    /// Child slots in order.
    pub fn children(&self) -> Result<Vec<SlotHandle>> {
        let guard = self.lock()?;
        let offset = resolve(&guard, self)?;
        datatree::child_slot_offsets(&guard.bytes, offset)?
            .into_iter()
            .map(|child| handle_at(&self.inner, &guard, child))
            .collect()
    }

    /// A field of the `component`-th component (the order of
    /// [`SlotHandle::components`]). A `{ID, Data}` field reads its `Data`.
    /// A null value is `None`. A reference reads as the target id string.
    pub fn component_value(&self, component: usize, field: &str) -> Result<Option<Value>> {
        let guard = self.lock()?;
        let offset = resolve(&guard, self)?;
        let types = datatree::read_types(&guard.bytes)?;
        let comps = datatree::components_of_slot(&guard.bytes, offset, &types)?;
        let comp = comps
            .get(component)
            .ok_or_else(|| Error::Invalid(format!("no component at {component}")))?;
        let data = datatree::field(&guard.bytes, comp.offset, "Data")?
            .ok_or_else(|| Error::FieldNotFound("Data".into()))?;
        if data.ty != crate::bson::DOCUMENT {
            return Err(Error::Invalid("component Data is not a document".into()));
        }
        let el = datatree::field(&guard.bytes, data.value_at, field)?
            .ok_or_else(|| Error::FieldNotFound(field.to_string()))?;
        datatree::decode_optional_value(&guard.bytes, &el)
    }

    /// Like [`SlotHandle::component_value`], but a missing field is
    /// `Ok(None)` instead of an error. A present null field is
    /// `Ok(Some(None))`.
    pub fn try_component_value(
        &self,
        component: usize,
        field: &str,
    ) -> Result<Option<Option<Value>>> {
        match self.component_value(component, field) {
            Ok(v) => Ok(Some(v)),
            Err(Error::FieldNotFound(name)) if name == field && field != "Data" => Ok(None),
            Err(e) => Err(e),
        }
    }

    /// Field names in the `Data` of the `component`-th component, in file
    /// order, without the identifier keys (`ID`, `persistent-ID`).
    pub fn component_field_names(&self, component: usize) -> Result<Vec<String>> {
        let guard = self.lock()?;
        let offset = resolve(&guard, self)?;
        let types = datatree::read_types(&guard.bytes)?;
        let comps = datatree::components_of_slot(&guard.bytes, offset, &types)?;
        let comp = comps
            .get(component)
            .ok_or_else(|| Error::Invalid(format!("no component at {component}")))?;
        let data = datatree::field(&guard.bytes, comp.offset, "Data")?
            .ok_or_else(|| Error::FieldNotFound("Data".into()))?;
        if data.ty != crate::bson::DOCUMENT {
            return Err(Error::Invalid("component Data is not a document".into()));
        }
        Ok(crate::bson::elements(&guard.bytes, data.value_at)?
            .into_iter()
            .filter(|el| !crate::ids::is_id_key(el.key))
            .map(|el| el.key.to_string())
            .collect())
    }

    pub fn components(&self) -> Result<Vec<ComponentInfo>> {
        let guard = self.lock()?;
        let offset = resolve(&guard, self)?;
        let types = datatree::read_types(&guard.bytes)?;
        Ok(datatree::components_of_slot(&guard.bytes, offset, &types)?
            .into_iter()
            .map(|c| ComponentInfo {
                type_index: c.type_index,
                type_name: c.type_name,
                references: c.references,
            })
            .collect())
    }

    fn lock(&self) -> Result<MutexGuard<'_, Inner>> {
        Ok(self.inner.lock()?)
    }
}

/// The slot's own id (keyed `""`) and the id of each of its `{ID, ...}`
/// fields (keyed by field name), such as `Active` or `Position`.
fn slot_ids(buf: &[u8], slot_off: usize) -> Result<Vec<(String, String)>> {
    let mut out = Vec::new();
    if let Some(id) = datatree::read_string_field(buf, slot_off, "ID")? {
        out.push((String::new(), id));
    }
    for el in crate::bson::elements(buf, slot_off)? {
        if el.ty == crate::bson::DOCUMENT {
            if let Some(id) = datatree::read_string_field(buf, el.value_at, "ID")? {
                out.push((el.key.to_string(), id));
            }
        }
    }
    Ok(out)
}

/// Install an edited buffer and its index. Returns the new generation.
fn commit(guard: &mut Inner, bytes: Vec<u8>, index: Index) -> u64 {
    guard.bytes = bytes;
    guard.index = index;
    guard.generation = guard.generation.wrapping_add(1);
    guard.generation
}

fn resolve(guard: &Inner, handle: &SlotHandle) -> Result<usize> {
    if handle.generation == guard.generation {
        if let Some(slot) = guard.index.slot_by_offset(handle.offset) {
            if slot.key == handle.key {
                return Ok(handle.offset);
            }
        }
    }
    guard
        .index
        .slot_by_key(handle.key)
        .map(|slot| slot.offset)
        .ok_or(Error::NotFound)
}

fn handle_at(inner: &Arc<Mutex<Inner>>, guard: &Inner, offset: usize) -> Result<SlotHandle> {
    let key = guard
        .index
        .slot_by_offset(offset)
        .map(|slot| slot.key)
        .ok_or_else(|| Error::Invalid("slot is missing from the index".into()))?;
    Ok(SlotHandle {
        inner: Arc::clone(inner),
        key,
        offset,
        generation: guard.generation,
    })
}

fn reject_duplicate_slot_id(guard: &Inner, offset: usize, value: &Value) -> Result<()> {
    let Value::String(new_id) = value else {
        return Err(Error::Invalid("slot ID must be a string".into()));
    };
    let current = guard
        .index
        .slot_by_offset(offset)
        .map(|slot| slot.id.as_str())
        .ok_or(Error::NotFound)?;
    if new_id == current {
        return Ok(());
    }
    let ids = datatree::document_ids(&guard.bytes)?;
    if ids.iter().any(|id| id == new_id) {
        return Err(Error::Invalid("duplicate PackageNodeIdentifier".into()));
    }
    Ok(())
}

fn replace_field(
    buf: &mut Vec<u8>,
    slot_off: usize,
    name: &str,
    value: &Value,
    lengths: &[usize],
) -> Result<()> {
    let spot = crate::bson::elements(buf, slot_off)?
        .iter()
        .find(|e| e.key == name)
        .map(edit::Spot::from)
        .ok_or_else(|| Error::FieldNotFound(name.to_string()))?;
    edit::replace_value(buf, &spot, Some(value), lengths)
}