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
#![doc(
html_logo_url = "https://raw.githubusercontent.com/automerge/automerge-rs/main/img/brandmark.svg",
html_favicon_url = "https:///raw.githubusercontent.com/automerge/automerge-rs/main/img/favicon.ico"
)]
#![warn(
missing_debug_implementations,
rust_2021_compatibility,
rust_2018_idioms,
unreachable_pub,
bad_style,
dead_code,
improper_ctypes,
non_shorthand_field_patterns,
no_mangle_generic_items,
overflowing_literals,
path_statements,
patterns_in_fns_without_body,
private_in_public,
unconditional_recursion,
unused,
unused_allocation,
unused_comparisons,
unused_parens,
while_true
)]
#![allow(clippy::unused_unit)]
use am::transaction::CommitOptions;
use am::transaction::{Observed, Transactable, UnObserved};
use am::ScalarValue;
use automerge as am;
use automerge::{sync::SyncDoc, Change, ObjId, Prop, ReadDoc, TextEncoding, Value, ROOT};
use js_sys::{Array, Function, Object, Uint8Array};
use serde::ser::Serialize;
use std::borrow::Cow;
use std::collections::HashMap;
use std::collections::HashSet;
use std::convert::TryInto;
use wasm_bindgen::prelude::*;
use wasm_bindgen::JsCast;
mod interop;
mod observer;
mod sequence_tree;
mod sync;
mod value;
use observer::Observer;
use interop::{alloc, get_heads, import_obj, js_set, to_js_err, to_prop, AR, JS};
use sync::SyncState;
use value::Datatype;
use crate::interop::SubValIter;
#[allow(unused_macros)]
macro_rules! log {
( $( $t:tt )* ) => {
web_sys::console::log_1(&format!( $( $t )* ).into());
};
}
type AutoCommit = am::AutoCommitWithObs<Observed<Observer>>;
#[cfg(feature = "wee_alloc")]
#[global_allocator]
static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT;
#[derive(Debug, Eq, PartialEq, Clone, Copy)]
#[wasm_bindgen]
pub enum TextRepresentation {
Array,
String,
}
impl std::default::Default for TextRepresentation {
fn default() -> Self {
TextRepresentation::Array
}
}
#[wasm_bindgen]
#[derive(Debug)]
pub struct Automerge {
doc: AutoCommit,
freeze: bool,
external_types: HashMap<Datatype, Function>,
text_rep: TextRepresentation,
}
#[wasm_bindgen]
impl Automerge {
pub fn new(
actor: Option<String>,
text_rep: TextRepresentation,
) -> Result<Automerge, error::BadActorId> {
let mut doc = AutoCommit::default().with_encoding(TextEncoding::Utf16);
if let Some(a) = actor {
let a = automerge::ActorId::from(hex::decode(a)?.to_vec());
doc.set_actor(a);
}
Ok(Automerge {
doc,
freeze: false,
external_types: HashMap::default(),
text_rep,
})
}
#[allow(clippy::should_implement_trait)]
pub fn clone(&mut self, actor: Option<String>) -> Result<Automerge, error::BadActorId> {
let mut automerge = Automerge {
doc: self.doc.clone(),
freeze: self.freeze,
external_types: self.external_types.clone(),
text_rep: self.text_rep,
};
if let Some(s) = actor {
let actor = automerge::ActorId::from(hex::decode(s)?.to_vec());
automerge.doc.set_actor(actor);
}
Ok(automerge)
}
pub fn fork(
&mut self,
actor: Option<String>,
heads: JsValue,
) -> Result<Automerge, error::Fork> {
let heads: Result<Vec<am::ChangeHash>, _> = JS(heads).try_into();
let doc = if let Ok(heads) = heads {
self.doc.fork_at(&heads)?
} else {
self.doc.fork()
};
let mut automerge = Automerge {
doc,
freeze: self.freeze,
external_types: self.external_types.clone(),
text_rep: self.text_rep,
};
if let Some(s) = actor {
let actor =
automerge::ActorId::from(hex::decode(s).map_err(error::BadActorId::from)?.to_vec());
automerge.doc.set_actor(actor);
}
Ok(automerge)
}
#[wasm_bindgen(js_name = pendingOps)]
pub fn pending_ops(&self) -> JsValue {
(self.doc.pending_ops() as u32).into()
}
pub fn commit(&mut self, message: Option<String>, time: Option<f64>) -> JsValue {
let mut commit_opts = CommitOptions::default();
if let Some(message) = message {
commit_opts.set_message(message);
}
if let Some(time) = time {
commit_opts.set_time(time as i64);
}
let hash = self.doc.commit_with(commit_opts);
match hash {
Some(h) => JsValue::from_str(&hex::encode(h.0)),
None => JsValue::NULL,
}
}
pub fn merge(&mut self, other: &mut Automerge) -> Result<Array, error::Merge> {
let heads = self.doc.merge(&mut other.doc)?;
let heads: Array = heads
.iter()
.map(|h| JsValue::from_str(&hex::encode(h.0)))
.collect();
Ok(heads)
}
pub fn rollback(&mut self) -> f64 {
self.doc.rollback() as f64
}
pub fn keys(&self, obj: JsValue, heads: Option<Array>) -> Result<Array, error::Get> {
let (obj, _) = self.import(obj)?;
let result = if let Some(heads) = get_heads(heads)? {
self.doc
.keys_at(&obj, &heads)
.map(|s| JsValue::from_str(&s))
.collect()
} else {
self.doc.keys(&obj).map(|s| JsValue::from_str(&s)).collect()
};
Ok(result)
}
pub fn text(&self, obj: JsValue, heads: Option<Array>) -> Result<String, error::Get> {
let (obj, _) = self.import(obj)?;
if let Some(heads) = get_heads(heads)? {
Ok(self.doc.text_at(&obj, &heads)?)
} else {
Ok(self.doc.text(&obj)?)
}
}
pub fn splice(
&mut self,
obj: JsValue,
start: f64,
delete_count: f64,
text: JsValue,
) -> Result<(), error::Splice> {
let (obj, obj_type) = self.import(obj)?;
let start = start as usize;
let delete_count = delete_count as usize;
let vals = if let Some(t) = text.as_string() {
if obj_type == am::ObjType::Text && self.text_rep == TextRepresentation::String {
self.doc.splice_text(&obj, start, delete_count, &t)?;
return Ok(());
} else {
t.chars()
.map(|c| ScalarValue::Str(c.to_string().into()))
.collect::<Vec<_>>()
}
} else {
let mut vals = vec![];
if let Ok(array) = text.dyn_into::<Array>() {
for (index, i) in array.iter().enumerate() {
let value = self
.import_scalar(&i, &None)
.ok_or(error::Splice::ValueNotPrimitive(index))?;
vals.push(value);
}
}
vals
};
if !vals.is_empty() {
self.doc.splice(&obj, start, delete_count, vals)?;
} else {
match obj_type {
am::ObjType::List => {
self.doc.splice(&obj, start, delete_count, vals)?;
}
am::ObjType::Text => match self.text_rep {
TextRepresentation::String => {
self.doc.splice_text(&obj, start, delete_count, "")?;
}
TextRepresentation::Array => {
self.doc.splice(&obj, start, delete_count, vals)?;
}
},
_ => {}
}
}
Ok(())
}
pub fn push(
&mut self,
obj: JsValue,
value: JsValue,
datatype: JsValue,
) -> Result<(), error::Insert> {
let (obj, _) = self.import(obj)?;
let value = self
.import_scalar(&value, &datatype.as_string())
.ok_or(error::Insert::ValueNotPrimitive)?;
let index = self.doc.length(&obj);
self.doc.insert(&obj, index, value)?;
Ok(())
}
#[wasm_bindgen(js_name = pushObject)]
pub fn push_object(
&mut self,
obj: JsValue,
value: JsValue,
) -> Result<Option<String>, error::InsertObject> {
let (obj, _) = self.import(obj)?;
let imported_obj = import_obj(&value, &None)?;
let index = self.doc.length(&obj);
let opid = self
.doc
.insert_object(&obj, index, imported_obj.objtype())?;
if let Some(s) = imported_obj.text() {
match self.text_rep {
TextRepresentation::String => {
self.doc.splice_text(&opid, 0, 0, s)?;
}
TextRepresentation::Array => {
self.subset::<error::InsertObject, _>(&opid, imported_obj.subvals())?;
}
}
} else {
self.subset::<error::InsertObject, _>(&opid, imported_obj.subvals())?;
}
Ok(opid.to_string().into())
}
pub fn insert(
&mut self,
obj: JsValue,
index: f64,
value: JsValue,
datatype: JsValue,
) -> Result<(), error::Insert> {
let (obj, _) = self.import(obj)?;
let value = self
.import_scalar(&value, &datatype.as_string())
.ok_or(error::Insert::ValueNotPrimitive)?;
self.doc.insert(&obj, index as usize, value)?;
Ok(())
}
#[wasm_bindgen(js_name = insertObject)]
pub fn insert_object(
&mut self,
obj: JsValue,
index: f64,
value: JsValue,
) -> Result<Option<String>, error::InsertObject> {
let (obj, _) = self.import(obj)?;
let imported_obj = import_obj(&value, &None)?;
let opid = self
.doc
.insert_object(&obj, index as usize, imported_obj.objtype())?;
if let Some(s) = imported_obj.text() {
match self.text_rep {
TextRepresentation::String => {
self.doc.splice_text(&opid, 0, 0, s)?;
}
TextRepresentation::Array => {
self.subset::<error::InsertObject, _>(&opid, imported_obj.subvals())?;
}
}
} else {
self.subset::<error::InsertObject, _>(&opid, imported_obj.subvals())?;
}
Ok(opid.to_string().into())
}
pub fn put(
&mut self,
obj: JsValue,
prop: JsValue,
value: JsValue,
datatype: JsValue,
) -> Result<(), error::Insert> {
let (obj, _) = self.import(obj)?;
let prop = self.import_prop(prop)?;
let value = self
.import_scalar(&value, &datatype.as_string())
.ok_or(error::Insert::ValueNotPrimitive)?;
self.doc.put(&obj, prop, value)?;
Ok(())
}
#[wasm_bindgen(js_name = putObject)]
pub fn put_object(
&mut self,
obj: JsValue,
prop: JsValue,
value: JsValue,
) -> Result<JsValue, error::InsertObject> {
let (obj, _) = self.import(obj)?;
let prop = self.import_prop(prop)?;
let imported_obj = import_obj(&value, &None)?;
let opid = self.doc.put_object(&obj, prop, imported_obj.objtype())?;
if let Some(s) = imported_obj.text() {
match self.text_rep {
TextRepresentation::String => {
self.doc.splice_text(&opid, 0, 0, s)?;
}
TextRepresentation::Array => {
self.subset::<error::InsertObject, _>(&opid, imported_obj.subvals())?;
}
}
} else {
self.subset::<error::InsertObject, _>(&opid, imported_obj.subvals())?;
}
Ok(opid.to_string().into())
}
fn subset<'a, E, I>(&mut self, obj: &am::ObjId, vals: I) -> Result<(), E>
where
I: IntoIterator<Item = (Cow<'a, am::Prop>, JsValue)>,
E: From<automerge::AutomergeError>
+ From<interop::error::ImportObj>
+ From<interop::error::InvalidValue>,
{
for (p, v) in vals {
let (value, subvals) = self.import_value(v.as_ref(), None)?;
let opid = match (p.as_ref(), value) {
(Prop::Map(s), Value::Object(objtype)) => {
Some(self.doc.put_object(obj, s, objtype)?)
}
(Prop::Map(s), Value::Scalar(scalar)) => {
self.doc.put(obj, s, scalar.into_owned())?;
None
}
(Prop::Seq(i), Value::Object(objtype)) => {
Some(self.doc.insert_object(obj, *i, objtype)?)
}
(Prop::Seq(i), Value::Scalar(scalar)) => {
self.doc.insert(obj, *i, scalar.into_owned())?;
None
}
};
if let Some(opid) = opid {
self.subset::<E, _>(&opid, SubValIter::Slice(subvals.as_slice().iter()))?;
}
}
Ok(())
}
pub fn increment(
&mut self,
obj: JsValue,
prop: JsValue,
value: JsValue,
) -> Result<(), error::Increment> {
let (obj, _) = self.import(obj)?;
let prop = self.import_prop(prop)?;
let value: f64 = value.as_f64().ok_or(error::Increment::ValueNotNumeric)?;
self.doc.increment(&obj, prop, value as i64)?;
Ok(())
}
#[wasm_bindgen(js_name = get)]
pub fn get(
&self,
obj: JsValue,
prop: JsValue,
heads: Option<Array>,
) -> Result<JsValue, error::Get> {
let (obj, _) = self.import(obj)?;
let prop = to_prop(prop);
let heads = get_heads(heads)?;
if let Ok(prop) = prop {
let value = if let Some(h) = heads {
self.doc.get_at(&obj, prop, &h)?
} else {
self.doc.get(&obj, prop)?
};
if let Some((value, id)) = value {
match alloc(&value, self.text_rep) {
(datatype, js_value) if datatype.is_scalar() => Ok(js_value),
_ => Ok(id.to_string().into()),
}
} else {
Ok(JsValue::undefined())
}
} else {
Ok(JsValue::undefined())
}
}
#[wasm_bindgen(js_name = getWithType)]
pub fn get_with_type(
&self,
obj: JsValue,
prop: JsValue,
heads: Option<Array>,
) -> Result<JsValue, error::Get> {
let (obj, _) = self.import(obj)?;
let prop = to_prop(prop);
let heads = get_heads(heads)?;
if let Ok(prop) = prop {
let value = if let Some(h) = heads {
self.doc.get_at(&obj, prop, &h)?
} else {
self.doc.get(&obj, prop)?
};
if let Some(value) = value {
match &value {
(Value::Object(obj_type), obj_id) => {
let result = Array::new();
result.push(&obj_type.to_string().into());
result.push(&obj_id.to_string().into());
Ok(result.into())
}
(Value::Scalar(_), _) => {
let result = Array::new();
let (datatype, value) = alloc(&value.0, self.text_rep);
result.push(&datatype.into());
result.push(&value);
Ok(result.into())
}
}
} else {
Ok(JsValue::null())
}
} else {
Ok(JsValue::null())
}
}
#[wasm_bindgen(js_name = getAll)]
pub fn get_all(
&self,
obj: JsValue,
arg: JsValue,
heads: Option<Array>,
) -> Result<Array, error::Get> {
let (obj, _) = self.import(obj)?;
let result = Array::new();
let prop = to_prop(arg);
if let Ok(prop) = prop {
let values = if let Some(heads) = get_heads(heads)? {
self.doc.get_all_at(&obj, prop, &heads)
} else {
self.doc.get_all(&obj, prop)
}?;
for (value, id) in values {
let sub = Array::new();
let (datatype, js_value) = alloc(&value, self.text_rep);
sub.push(&datatype.into());
if value.is_scalar() {
sub.push(&js_value);
}
sub.push(&id.to_string().into());
result.push(&JsValue::from(&sub));
}
}
Ok(result)
}
#[wasm_bindgen(js_name = enableFreeze)]
pub fn enable_freeze(&mut self, enable: JsValue) -> Result<JsValue, JsValue> {
let enable = enable
.as_bool()
.ok_or_else(|| to_js_err("must pass a bool to enableFreeze"))?;
let old_freeze = self.freeze;
self.freeze = enable;
Ok(old_freeze.into())
}
#[wasm_bindgen(js_name = enablePatches)]
pub fn enable_patches(&mut self, enable: JsValue) -> Result<JsValue, JsValue> {
let enable = enable
.as_bool()
.ok_or_else(|| to_js_err("must pass a bool to enablePatches"))?;
let old_enabled = self.doc.observer().enable(enable);
self.doc.observer().set_text_rep(self.text_rep);
Ok(old_enabled.into())
}
#[wasm_bindgen(js_name = registerDatatype)]
pub fn register_datatype(
&mut self,
datatype: JsValue,
function: JsValue,
) -> Result<(), value::InvalidDatatype> {
let datatype = Datatype::try_from(datatype)?;
if let Ok(function) = function.dyn_into::<Function>() {
self.external_types.insert(datatype, function);
} else {
self.external_types.remove(&datatype);
}
Ok(())
}
#[wasm_bindgen(js_name = applyPatches)]
pub fn apply_patches(
&mut self,
object: JsValue,
meta: JsValue,
callback: JsValue,
) -> Result<JsValue, error::ApplyPatch> {
let mut object = object
.dyn_into::<Object>()
.map_err(|_| error::ApplyPatch::NotObjectd)?;
let patches = self.doc.observer().take_patches();
let callback = callback.dyn_into::<Function>().ok();
if patches.is_empty() && !meta.is_undefined() {
let (obj, datatype, id) = self.unwrap_object(&object)?;
object = Object::assign(&Object::new(), &obj);
object = self.wrap_object(object, datatype, &id, &meta)?;
}
let mut exposed = HashSet::default();
let before = object.clone();
for p in &patches {
object = self.apply_patch(object, p, 0, &meta, &mut exposed)?;
}
if let Some(c) = &callback {
if !patches.is_empty() {
let patches: Array = patches
.into_iter()
.map(JsValue::try_from)
.collect::<Result<_, _>>()?;
c.call3(&JsValue::undefined(), &patches.into(), &before, &object)
.map_err(error::ApplyPatch::PatchCallback)?;
}
}
self.finalize_exposed(&object, exposed, &meta)?;
Ok(object.into())
}
#[wasm_bindgen(js_name = popPatches)]
pub fn pop_patches(&mut self) -> Result<Array, error::PopPatches> {
let patches = self.doc.observer().take_patches();
let result = Array::new();
for p in patches {
result.push(&p.try_into()?);
}
Ok(result)
}
pub fn length(&self, obj: JsValue, heads: Option<Array>) -> Result<f64, error::Get> {
let (obj, _) = self.import(obj)?;
if let Some(heads) = get_heads(heads)? {
Ok(self.doc.length_at(&obj, &heads) as f64)
} else {
Ok(self.doc.length(&obj) as f64)
}
}
pub fn delete(&mut self, obj: JsValue, prop: JsValue) -> Result<(), error::Get> {
let (obj, _) = self.import(obj)?;
let prop = to_prop(prop)?;
self.doc.delete(&obj, prop)?;
Ok(())
}
pub fn save(&mut self) -> Uint8Array {
Uint8Array::from(self.doc.save().as_slice())
}
#[wasm_bindgen(js_name = saveIncremental)]
pub fn save_incremental(&mut self) -> Uint8Array {
let bytes = self.doc.save_incremental();
Uint8Array::from(bytes.as_slice())
}
#[wasm_bindgen(js_name = loadIncremental)]
pub fn load_incremental(&mut self, data: Uint8Array) -> Result<f64, error::Load> {
let data = data.to_vec();
let len = self.doc.load_incremental(&data)?;
Ok(len as f64)
}
#[wasm_bindgen(js_name = applyChanges)]
pub fn apply_changes(&mut self, changes: JsValue) -> Result<(), error::ApplyChangesError> {
let changes: Vec<_> = JS(changes).try_into()?;
self.doc.apply_changes(changes)?;
Ok(())
}
#[wasm_bindgen(js_name = getChanges)]
pub fn get_changes(&mut self, have_deps: JsValue) -> Result<Array, error::Get> {
let deps: Vec<_> = JS(have_deps).try_into()?;
let changes = self.doc.get_changes(&deps)?;
let changes: Array = changes
.iter()
.map(|c| Uint8Array::from(c.raw_bytes()))
.collect();
Ok(changes)
}
#[wasm_bindgen(js_name = getChangeByHash)]
pub fn get_change_by_hash(
&mut self,
hash: JsValue,
) -> Result<JsValue, interop::error::BadChangeHash> {
let hash = JS(hash).try_into()?;
let change = self.doc.get_change_by_hash(&hash);
if let Some(c) = change {
Ok(Uint8Array::from(c.raw_bytes()).into())
} else {
Ok(JsValue::null())
}
}
#[wasm_bindgen(js_name = getChangesAdded)]
pub fn get_changes_added(&mut self, other: &mut Automerge) -> Array {
let changes = self.doc.get_changes_added(&mut other.doc);
let changes: Array = changes
.iter()
.map(|c| Uint8Array::from(c.raw_bytes()))
.collect();
changes
}
#[wasm_bindgen(js_name = getHeads)]
pub fn get_heads(&mut self) -> Array {
let heads = self.doc.get_heads();
let heads: Array = heads
.iter()
.map(|h| JsValue::from_str(&hex::encode(h.0)))
.collect();
heads
}
#[wasm_bindgen(js_name = getActorId)]
pub fn get_actor_id(&self) -> String {
let actor = self.doc.get_actor();
actor.to_string()
}
#[wasm_bindgen(js_name = getLastLocalChange)]
pub fn get_last_local_change(&mut self) -> JsValue {
if let Some(change) = self.doc.get_last_local_change() {
Uint8Array::from(change.raw_bytes()).into()
} else {
JsValue::null()
}
}
pub fn dump(&mut self) {
self.doc.dump()
}
#[wasm_bindgen(js_name = getMissingDeps)]
pub fn get_missing_deps(&mut self, heads: Option<Array>) -> Result<Array, error::Get> {
let heads = get_heads(heads)?.unwrap_or_default();
let deps = self.doc.get_missing_deps(&heads);
let deps: Array = deps
.iter()
.map(|h| JsValue::from_str(&hex::encode(h.0)))
.collect();
Ok(deps)
}
#[wasm_bindgen(js_name = receiveSyncMessage)]
pub fn receive_sync_message(
&mut self,
state: &mut SyncState,
message: Uint8Array,
) -> Result<(), error::ReceiveSyncMessage> {
let message = message.to_vec();
let message = am::sync::Message::decode(message.as_slice())?;
self.doc
.sync()
.receive_sync_message(&mut state.0, message)?;
Ok(())
}
#[wasm_bindgen(js_name = generateSyncMessage)]
pub fn generate_sync_message(&mut self, state: &mut SyncState) -> JsValue {
if let Some(message) = self.doc.sync().generate_sync_message(&mut state.0) {
Uint8Array::from(message.encode().as_slice()).into()
} else {
JsValue::null()
}
}
#[wasm_bindgen(js_name = toJS)]
pub fn to_js(&mut self, meta: JsValue) -> Result<JsValue, interop::error::Export> {
self.export_object(&ROOT, Datatype::Map, None, &meta)
}
pub fn materialize(
&mut self,
obj: JsValue,
heads: Option<Array>,
meta: JsValue,
) -> Result<JsValue, error::Materialize> {
let (obj, obj_type) = self.import(obj).unwrap_or((ROOT, am::ObjType::Map));
let heads = get_heads(heads)?;
let _patches = self.doc.observer().take_patches(); Ok(self.export_object(&obj, obj_type.into(), heads.as_ref(), &meta)?)
}
#[wasm_bindgen(js_name = emptyChange)]
pub fn empty_change(&mut self, message: Option<String>, time: Option<f64>) -> JsValue {
let time = time.map(|f| f as i64);
let options = CommitOptions { message, time };
let hash = self.doc.empty_change(options);
JsValue::from_str(&hex::encode(hash))
}
}
#[wasm_bindgen(js_name = create)]
pub fn init(text_v2: bool, actor: Option<String>) -> Result<Automerge, error::BadActorId> {
console_error_panic_hook::set_once();
let text_rep = if text_v2 {
TextRepresentation::String
} else {
TextRepresentation::Array
};
Automerge::new(actor, text_rep)
}
#[wasm_bindgen(js_name = load)]
pub fn load(
data: Uint8Array,
text_v2: bool,
actor: Option<String>,
) -> Result<Automerge, error::Load> {
let data = data.to_vec();
let text_rep = if text_v2 {
TextRepresentation::String
} else {
TextRepresentation::Array
};
let mut doc = am::AutoCommitWithObs::<UnObserved>::load(&data)?
.with_observer(Observer::default().with_text_rep(text_rep))
.with_encoding(TextEncoding::Utf16);
if let Some(s) = actor {
let actor =
automerge::ActorId::from(hex::decode(s).map_err(error::BadActorId::from)?.to_vec());
doc.set_actor(actor);
}
Ok(Automerge {
doc,
freeze: false,
external_types: HashMap::default(),
text_rep,
})
}
#[wasm_bindgen(js_name = encodeChange)]
pub fn encode_change(change: JsValue) -> Result<Uint8Array, error::EncodeChange> {
#[allow(deprecated)]
let change: am::ExpandedChange = change.into_serde()?;
let change: Change = change.into();
Ok(Uint8Array::from(change.raw_bytes()))
}
#[wasm_bindgen(js_name = decodeChange)]
pub fn decode_change(change: Uint8Array) -> Result<JsValue, error::DecodeChange> {
let change = Change::from_bytes(change.to_vec())?;
let change: am::ExpandedChange = change.decode();
let serializer = serde_wasm_bindgen::Serializer::json_compatible();
Ok(change.serialize(&serializer)?)
}
#[wasm_bindgen(js_name = initSyncState)]
pub fn init_sync_state() -> SyncState {
SyncState(am::sync::State::new())
}
#[wasm_bindgen(js_name = importSyncState)]
pub fn import_sync_state(state: JsValue) -> Result<SyncState, interop::error::BadSyncState> {
Ok(SyncState(JS(state).try_into()?))
}
#[wasm_bindgen(js_name = exportSyncState)]
pub fn export_sync_state(state: &SyncState) -> JsValue {
JS::from(state.0.clone()).into()
}
#[wasm_bindgen(js_name = encodeSyncMessage)]
pub fn encode_sync_message(message: JsValue) -> Result<Uint8Array, interop::error::BadSyncMessage> {
let message: am::sync::Message = JS(message).try_into()?;
Ok(Uint8Array::from(message.encode().as_slice()))
}
#[wasm_bindgen(js_name = decodeSyncMessage)]
pub fn decode_sync_message(msg: Uint8Array) -> Result<JsValue, error::BadSyncMessage> {
let data = msg.to_vec();
let msg = am::sync::Message::decode(&data)?;
let heads = AR::from(msg.heads.as_slice());
let need = AR::from(msg.need.as_slice());
let changes = AR::from(msg.changes.as_slice());
let have = AR::from(msg.have.as_slice());
let obj = Object::new().into();
js_set(&obj, "heads", heads).unwrap();
js_set(&obj, "need", need).unwrap();
js_set(&obj, "have", have).unwrap();
js_set(&obj, "changes", changes).unwrap();
Ok(obj)
}
#[wasm_bindgen(js_name = encodeSyncState)]
pub fn encode_sync_state(state: &SyncState) -> Uint8Array {
Uint8Array::from(state.0.encode().as_slice())
}
#[wasm_bindgen(js_name = decodeSyncState)]
pub fn decode_sync_state(data: Uint8Array) -> Result<SyncState, sync::DecodeSyncStateErr> {
SyncState::decode(data)
}
pub mod error {
use automerge::AutomergeError;
use wasm_bindgen::JsValue;
use crate::interop::{
self,
error::{BadChangeHashes, BadJSChanges},
};
#[derive(Debug, thiserror::Error)]
#[error("could not parse Actor ID as a hex string: {0}")]
pub struct BadActorId(#[from] hex::FromHexError);
impl From<BadActorId> for JsValue {
fn from(s: BadActorId) -> Self {
JsValue::from(s.to_string())
}
}
#[derive(Debug, thiserror::Error)]
pub enum ApplyChangesError {
#[error(transparent)]
DecodeChanges(#[from] BadJSChanges),
#[error("error applying changes: {0}")]
Apply(#[from] AutomergeError),
}
impl From<ApplyChangesError> for JsValue {
fn from(e: ApplyChangesError) -> Self {
JsValue::from(e.to_string())
}
}
#[derive(Debug, thiserror::Error)]
pub enum Fork {
#[error(transparent)]
BadActor(#[from] BadActorId),
#[error(transparent)]
Automerge(#[from] AutomergeError),
#[error(transparent)]
BadChangeHashes(#[from] BadChangeHashes),
}
impl From<Fork> for JsValue {
fn from(f: Fork) -> Self {
JsValue::from(f.to_string())
}
}
#[derive(Debug, thiserror::Error)]
#[error(transparent)]
pub struct Merge(#[from] AutomergeError);
impl From<Merge> for JsValue {
fn from(e: Merge) -> Self {
JsValue::from(e.to_string())
}
}
#[derive(Debug, thiserror::Error)]
pub enum Get {
#[error("invalid object ID: {0}")]
ImportObj(#[from] interop::error::ImportObj),
#[error(transparent)]
Automerge(#[from] AutomergeError),
#[error("bad heads: {0}")]
BadHeads(#[from] interop::error::BadChangeHashes),
#[error(transparent)]
InvalidProp(#[from] interop::error::InvalidProp),
}
impl From<Get> for JsValue {
fn from(e: Get) -> Self {
JsValue::from(e.to_string())
}
}
#[derive(Debug, thiserror::Error)]
pub enum Splice {
#[error("invalid object ID: {0}")]
ImportObj(#[from] interop::error::ImportObj),
#[error(transparent)]
Automerge(#[from] AutomergeError),
#[error("value at {0} in values to insert was not a primitive")]
ValueNotPrimitive(usize),
}
impl From<Splice> for JsValue {
fn from(e: Splice) -> Self {
JsValue::from(e.to_string())
}
}
#[derive(Debug, thiserror::Error)]
pub enum Insert {
#[error("invalid object id: {0}")]
ImportObj(#[from] interop::error::ImportObj),
#[error("the value to insert was not a primitive")]
ValueNotPrimitive,
#[error(transparent)]
Automerge(#[from] AutomergeError),
#[error(transparent)]
InvalidProp(#[from] interop::error::InvalidProp),
#[error(transparent)]
InvalidValue(#[from] interop::error::InvalidValue),
}
impl From<Insert> for JsValue {
fn from(e: Insert) -> Self {
JsValue::from(e.to_string())
}
}
#[derive(Debug, thiserror::Error)]
pub enum InsertObject {
#[error("invalid object id: {0}")]
ImportObj(#[from] interop::error::ImportObj),
#[error("the value to insert must be an object")]
ValueNotObject,
#[error(transparent)]
Automerge(#[from] AutomergeError),
#[error(transparent)]
InvalidProp(#[from] interop::error::InvalidProp),
#[error(transparent)]
InvalidValue(#[from] interop::error::InvalidValue),
}
impl From<InsertObject> for JsValue {
fn from(e: InsertObject) -> Self {
JsValue::from(e.to_string())
}
}
#[derive(Debug, thiserror::Error)]
pub enum Increment {
#[error("invalid object id: {0}")]
ImportObj(#[from] interop::error::ImportObj),
#[error(transparent)]
InvalidProp(#[from] interop::error::InvalidProp),
#[error("value was not numeric")]
ValueNotNumeric,
#[error(transparent)]
Automerge(#[from] AutomergeError),
}
impl From<Increment> for JsValue {
fn from(e: Increment) -> Self {
JsValue::from(e.to_string())
}
}
#[derive(Debug, thiserror::Error)]
pub enum BadSyncMessage {
#[error("could not decode sync message: {0}")]
ReadMessage(#[from] automerge::sync::ReadMessageError),
}
impl From<BadSyncMessage> for JsValue {
fn from(e: BadSyncMessage) -> Self {
JsValue::from(e.to_string())
}
}
#[derive(Debug, thiserror::Error)]
pub enum ApplyPatch {
#[error(transparent)]
Interop(#[from] interop::error::ApplyPatch),
#[error(transparent)]
Export(#[from] interop::error::Export),
#[error("patch was not an object")]
NotObjectd,
#[error("error calling patch callback: {0:?}")]
PatchCallback(JsValue),
}
impl From<ApplyPatch> for JsValue {
fn from(e: ApplyPatch) -> Self {
JsValue::from(e.to_string())
}
}
#[derive(Debug, thiserror::Error)]
#[error("unable to build patches: {0}")]
pub struct PopPatches(#[from] interop::error::Export);
impl From<PopPatches> for JsValue {
fn from(e: PopPatches) -> Self {
JsValue::from(e.to_string())
}
}
#[derive(Debug, thiserror::Error)]
pub enum Materialize {
#[error(transparent)]
Export(#[from] interop::error::Export),
#[error("bad heads: {0}")]
Heads(#[from] interop::error::BadChangeHashes),
}
impl From<Materialize> for JsValue {
fn from(e: Materialize) -> Self {
JsValue::from(e.to_string())
}
}
#[derive(Debug, thiserror::Error)]
pub enum ReceiveSyncMessage {
#[error(transparent)]
Decode(#[from] automerge::sync::ReadMessageError),
#[error(transparent)]
Automerge(#[from] AutomergeError),
}
impl From<ReceiveSyncMessage> for JsValue {
fn from(e: ReceiveSyncMessage) -> Self {
JsValue::from(e.to_string())
}
}
#[derive(Debug, thiserror::Error)]
pub enum Load {
#[error(transparent)]
Automerge(#[from] AutomergeError),
#[error(transparent)]
BadActor(#[from] BadActorId),
}
impl From<Load> for JsValue {
fn from(e: Load) -> Self {
JsValue::from(e.to_string())
}
}
#[derive(Debug, thiserror::Error)]
#[error("Unable to read JS change: {0}")]
pub struct EncodeChange(#[from] serde_json::Error);
impl From<EncodeChange> for JsValue {
fn from(e: EncodeChange) -> Self {
JsValue::from(e.to_string())
}
}
#[derive(Debug, thiserror::Error)]
pub enum DecodeChange {
#[error(transparent)]
Load(#[from] automerge::LoadChangeError),
#[error(transparent)]
Serialize(#[from] serde_wasm_bindgen::Error),
}
impl From<DecodeChange> for JsValue {
fn from(e: DecodeChange) -> Self {
JsValue::from(e.to_string())
}
}
}